【问题标题】:need to check if gps is enabled or not需要检查gps是否启用
【发布时间】:2019-07-08 07:13:15
【问题描述】:

我正在制作一个应用程序,在该应用程序中单击按钮时,它会从 1 个活动移动到第 2 个活动,在该活动上我需要 gps 处于活动状态我使用警报对话框通过单击设置来打开 gps,它将打开到设置和如果我启用它,对话框消散并且 gps 开始工作,但是如果我在不启用 gps 的情况下按下后退按钮,它会工作并且活动开始我想检查 gps 是否已启用,如果没有,它不应该向我显示第二个活动

没有错误出现,但只是在不启用的情况下按设置将启动活动而不会出现任何错误,并且 gps 仍然处于关闭状态。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);
    textView1 = (TextView) findViewById(R.id.location_view);
    button1 = (Button) findViewById(R.id.camera);
    button2 = (Button) findViewById(R.id.upload);
    editText1 = (EditText) findViewById(R.id.remarks);
    imageView11 = (ImageView) findViewById(R.id.image1);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);


    locationText = (TextView) findViewById(R.id.location_view);
    if (ContextCompat.checkSelfPermission(getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat
            .checkSelfPermission(getApplicationContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
                .ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
    }

    getLocation();
}



public void getLocation() {
    try {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (LocationListener) this);
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.item1:
            Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
            return true;
         case R.id.item2:
            Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
            return true;
         case R.id.item3:

             AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
             alerDialogbuilder.setTitle("Confirm Logout");
             alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
             alerDialogbuilder.setMessage("Are You Sure You Want to Logout ");
             alerDialogbuilder.setMessage("Logingout will need id password again");
             alerDialogbuilder.setCancelable(false);
             alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialogInterface, int i) {
                     Intent intents = new Intent(Main3Activity.this,MainActivity.class);
                     startActivity(intents);
                     Toast.makeText(getApplicationContext(),"Successfull Logout",Toast.LENGTH_SHORT).show();
                                         }
             });
             alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialogInterface, int i) {
                     Toast.makeText(getApplicationContext(),"Logout Canceled",Toast.LENGTH_SHORT).show();
                 }
             });
             AlertDialog alertDialog = alerDialogbuilder.create();
             alertDialog.show();


            return true;
           default:return super.onOptionsItemSelected(item);
    }
    }

private void camera(){
    Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intents,CAMERA_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==CAMERA_REQUEST&&resultCode== Activity.RESULT_OK){
        Bitmap photo= (Bitmap)data.getExtras().get("data");
        imageView11.setImageBitmap(photo);

    }
}

private void upload(){
    AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
    alerDialogbuilder.setTitle("Confirm Upload ?");
    alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
    alerDialogbuilder.setMessage("Are You Sure You Want to Upload Data");
    alerDialogbuilder.setCancelable(false);
    alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
          Toast.makeText(getApplicationContext(),"File Uploading...",Toast.LENGTH_SHORT).show();
        }
    });
    alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(getApplicationContext(),"Recheck Data",Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alertDialog = alerDialogbuilder.create();
    alertDialog.show();
}

@Override
public void onClick(View view) {

    if(view==button1){
        camera();
    }

    else if (view == button2){
        upload();
    }

}


@Override
public void onLocationChanged(Location location) {

    double lati = location.getLatitude();
    double longi = location.getLongitude();

    locationText.setText("Latitude: " + lati + "\n Longitude: " + longi);

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

    Toast.makeText(this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {
    AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
    alerDialogbuilder.setTitle("Enable Gps to Continue");
    alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
    alerDialogbuilder.setMessage("If You Want To Enable Gps Go To Settings");
    alerDialogbuilder.setCancelable(false);
    alerDialogbuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent1);
            Toast.makeText(getApplicationContext(),"Enable Gps..",Toast.LENGTH_SHORT).show();
        }
    });
    alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            finish();
            Toast.makeText(getApplicationContext(),"Uploading Failed,Enable Gps",Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alertDialog = alerDialogbuilder.create();
    alertDialog.show();
    }
  }

我只想在我的活动开始时检查 gps 是否已启用,如果未启用,请转到设置,如果用户未启用 gps 设置,它不应该进一步工作,请帮助我了解 android 新手

【问题讨论】:

  • 请向我提供一个工作答案,以更新或更改哪个班级的代码

标签: java android android-gps


【解决方案1】:

实现以下检查状态的方法-:

public boolean CheckGpsStatus() {

         LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

         boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            return GpsStatus;
        }

【讨论】:

  • 在哪里实施??
  • 请检查我的代码并帮助我,我将非常感谢你
  • 在 if 条件语句中的 onCreate(Bundle savedInstanceState) 方法中调用此方法,如果为真则获取位置,否则完成活动,或者您可以再次请求权限或动态进入 gps 设置页面。
  • @DaRkwArRiOr 检查我的答案,它将指导您如何操作。
【解决方案2】:
protected LocationRequest locationRequest;



public void checkForLocationRequest() {
        locationRequest = LocationRequest.create();
        locationRequest.setInterval(MIN_UPDATE_INTERVAL);
        locationRequest.setNumUpdates(1);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }
    public void checkForLocationSettings() {
        try {
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
            builder.addLocationRequest(locationRequest);
            SettingsClient settingsClient = LocationServices.getSettingsClient(MainActivity.this);
            settingsClient.checkLocationSettings(builder.build())
                    .addOnSuccessListener((Activity) MainActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
                        @Override
                        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
//                            delay(1);
                            //Setting is success...
                            //  Toast.makeText(SplashActivity.this, "Enabled the Location successfully. Now you can press the buttons..", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnFailureListener((Activity) MainActivity.this, new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            int statusCode = ((ApiException) e).getStatusCode();
                            switch (statusCode) {
                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                    try {
                                        // Show the dialog by calling startResolutionForResult(), and check the
                                        // result in onActivityResult().

                                        ResolvableApiException rae = (ResolvableApiException) e;
                                        rae.startResolutionForResult((Activity) MainActivity.this, GET_PERMISSION_REQ_CODE);
                                    } catch (Exception ex) {
                                        new MyUtils().catchError(MainActivity.this, ex);
                                    }
                                    break;
                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                    Toast.makeText(MainActivity.this, "Setting change is not available.Try in another device.", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        } catch (Exception e) {
            new MyUtils().catchError(MainActivity.this, e);

        }
    }

如果 gps 未启用,上面的代码显示了启用 gps 的弹出窗口,并为您提供成功和失败的回调

【讨论】:

  • okie,这是你单独定义的两种方法,我必须在我想检查的地方使用它??
  • 为我工作,但先生,我用 Onstatus 中的 backpressed() 命令更新了代码,现在它的工作改变了,但是当我按下返回按钮时,它的工作意味着返回按钮而不启用 gps,它打开返回活动但是当我启用 gps 然后我们按下返回按钮它再次返回上一个活动
【解决方案3】:
        public class MainActivity extends AppCompatActivity
                implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{

     protected static final String TAG = "MainActivity";
        protected static final int REQUEST_CHECK_SETTINGS = 0x1;

        Marker mCurrLocationMarker;
        GoogleMap mgooglemap;
        private LocationManager locationManager;


@Override
    public void onLocationChanged(Location location) {

        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
      //  MarkerOptions markerOptions = new MarkerOptions();
      //  markerOptions.position(latLng);
      //  markerOptions.title("Current Position");
       // markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
      // mCurrLocationMarker = mgooglemap.addMarker(markerOptions);


        //move map camera
        mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
      //  locationManager.removeUpdates(this);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();

//for you want to open Settings screen
while(!onProviderEnabled())
{
    startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}

    }

上述代码的onProviderDisabled() 将为您提供所需的流程。

【讨论】:

  • 但它只会烤一个文本以启用 gps。但我想在设置中显示 gps 设置然后呃不能在不启用 gps 的情况下返回按钮我想要这个先生
  • 我得到了代码先生,但是如果我打开活动并且没有启用我的 gps 点击后退按钮我的活动在没有 gps 的情况下开始
  • 我不想在我的程序中进行任何更新,只需要一个代码来检查是否启用了 gps,如果没有,它会移动到下一个位置
  • 下一个位置是什么?
  • 检查更新的答案。这是获得所需解决方案的最可能方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 2021-11-06
相关资源
最近更新 更多