Android: checking if location service is enabled crashes the app

时间:2017-05-16 09:21:39

标签: java android service location

This is what I currently have running:

    public void GPSStatus(){
            locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
            GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

For some reason when calling it and checking what it sets the predefined variable as:

    GPSStatus();
    if(GpsStatus == true) {
        ...
    } else {
        ...
    }

or even when just calling the method:

    GPSStatus();

crashes the whole app. Any ideas why this might happen?

2 个答案:

答案 0 :(得分:0)

  private void requestGPS_Permission() {

        String requiredPermission = Manifest.permission.ACCESS_COARSE_LOCATION;
        String requiredPermission1 = Manifest.permission.ACCESS_FINE_LOCATION;

        // If the user previously denied this permission then show a message explaining why
        // this permission is needed
        if (getActivity().checkCallingOrSelfPermission(requiredPermission) == PackageManager.PERMISSION_GRANTED &&getActivity().checkCallingOrSelfPermission(requiredPermission1) == PackageManager.PERMISSION_GRANTED) {
            GPSStatus();
        } else {

            Toast.makeText(getActivity(), "This app needs to record audio through the microphone....", Toast.LENGTH_SHORT).show();
            requestPermissions(new String[]{requiredPermission}, 101);
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            GPSStatus();
            // This method is called when the  permissions are given
        }

    }

Run this code.

答案 1 :(得分:0)

我认为正确的答案取决于您定位的SDK,但您可以使用它来检查应用是否具有该权限,因为在最新版本中您必须要求用户授予它们:

if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    //do your checks
    //...
} else {
    ActivityCompat.requestPermissions(getApplicationContext(), new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, SINGLE_PERMISSION_REQUEST_CODE);
}

我不能100%确定你是否可以在requestPermission中使用getApplicationContext(),否则,只需使用你活动的上下文