How To Check If Permission Is Granted By User At Runtime On Android?
Solution 1:
Use onRequestPermissionResult, It handles the action if user press ALLOW and DENY, Just call the intent in the condition "if the user presses allow":
@OverridepublicvoidonRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case123: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//If user presses allow
Toast.makeText(Main2Activity.this, "Permission granted!", Toast.LENGTH_SHORT).show();
Intentin=newIntent(Intent.ACTION_CALL, Uri.parse("tel:" + num.getText().toString()));
startActivity(in);
} else {
//If user presses deny
Toast.makeText(Main2Activity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
Hope this helps.
Solution 2:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
is terrible logic for checking permission result, i don't know why Google implemented such a terrible code.
It's a mess especially when you check multiple permissions. Let say you ask for
CAMERA
, ACCESS_FINE_LOCATION
and ACCESS_NETWORK_STATE
.
You need to check for ACCESS_FINE_LOCATION but user only granted CAMERA at first run and you check for grantResults[1] but in second run ACCESS_FINE_LOCATION becomes the permission with index 0. I got so many problems with user not granting all permissions at once.
You should either use
int size = permissions.length;
boolean locationPermissionGranted = false;
for (int i = 0; i < size; i++) {
if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)
&& grantResults[i] == PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true;
}
}
Or simpler one
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
// Do something ...
}
in onPermissionRequestResult
method.
Post a Comment for "How To Check If Permission Is Granted By User At Runtime On Android?"