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.
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.
}
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With