Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onRequestPermissionsResult grantResults size > 1

After requesting permission, the ActivityCompat.OnRequestPermissionsResultCallback sometimes contains multiple grantResults, is it safe to just check the first one?

The training doc check the param like this:

    if (grantResults.length > 0
      && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      // permission was granted, yay! Do the
      // contacts-related task you need to do.
    } else {
      // permission denied, boo! Disable the
      // functionality that depends on this permission.
    }

but it's not clearly and no documents found.

like image 885
Hong Duan Avatar asked Jul 08 '16 06:07

Hong Duan


2 Answers

No, It is not a good way to just check first permission, it might be possible that user have allowed first permission but denied for rest permissions. Here is function i am sharing to check whether all permissions are granted or not

public boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
    for (int grantResult : grantResults) {
        if (grantResult == PackageManager.PERMISSION_DENIED) {
            return false;
        }
    }
    return true;
}

and in your onRequestPermissionsResult

if(hasAllPermissionsGranted(grantResults)){
    // all permissions granted
}else {
    // some permission are denied.
}
like image 174
Ravi Avatar answered Oct 19 '22 10:10

Ravi


The shortest way you can make sure all the permissions are granted by the user.

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (Arrays.binarySearch(grantResults, -1) >= 0) {

        /* Some permissions are not granted
        request permission again if required */

        return;
    }
}

The integer array that you can use to validate permissions :

if (Arrays.binarySearch(grantResults, -1) >= 0) { // some permissions are not granted }
like image 25
Googlian Avatar answered Oct 19 '22 11:10

Googlian