Android - Requesting Runtime Permissions

2019-03-02 16:44发布

问题:

I am trying to understand how to request Runtime Permissions in android for "Dangerous permissions" like Location.

What i understand is that the code should go like this

public void checkPermission(){ 
  if (ActivityCompat.checkSelfPermission(..) == PackageManager.PERMISSION_GRANTED){

    getLocation();

  } else {

    ActivityCompat.requestPermissions(..);

  }
}

public void onRequestPermissionsResult(..){
  switch (requestCode) {
    case MY_PERMISSIONS_REQUEST: {
      if (..) {
                // permission was granted, yay!
                getLocation();
            } else {
                // permission denied, boo!
            }
            return;
        }
     }
}

public Location getLocation(){
  locationManager.requestLocationUpdates(..)
  ..
}

The thing is, this code gives me error on locationManager telling me i have to request the location permission

So what is the proplem with this sequence?

回答1:

Try this, it worked for me

private void checkPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
                MY_PERMISSIONS_REQUEST_FINE_LOCATION);

    } else {
        getLocation();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
             getLocation();
            } else {
                // permission denied, boo! Disable the
            }
            return;
        }
    }
}