Application Not Asking To Get Permissions
I have this code to get the following permissions (READ_PHONE_STATE, READ_CONTACTS, WRITE_CONTACTS): int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.
Solution 1:
You are using &&
instead of ||
. As it stands, you will not ask for any runtime permissions if you hold just one of the three.
Also, you are calling requestPermissions()
three times. Call it once, with whichever permissions you need. new String[]
creates a string array, and it can hold all three of your desired permission names.
Solution 2:
If you have 10 permissions, will you extend your code by 20 more lines. Noooo!
You have 2 ways
- Follow correct way to ask permission. I am posting my code snippet, copy this code in your Base Activity class.
- Or you use RxPermissions. If you are new to Android.
Here is my code snippet.
String[] permissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS};
getBulkPermissions(permissions, new RequestPermissionAction() {
@Override
public void permissionDenied() {
// TODO: 5/27/2018 handle permission deny
}
@Override
public void permissionGranted() {
// TODO: 5/27/2018 you code do further operations
}
});
Can it be more simpler?
Now you will put this code Base Activity class and use anywhere you need. Or put in your current class if you don't need it at any other place.
RequestPermissionAction onPermissionCallBack;
private final static int REQUEST_BULK_PERMISSION = 3006;
private boolean checkBulkPermissions(String[] permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String permission : permissions) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
} else {
return true;
}
}
public void getBulkPermissions(String[] permissions, RequestPermissionAction onPermissionCallBack) {
this.onPermissionCallBack = onPermissionCallBack;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!checkBulkPermissions(permissions)) {
requestPermissions(permissions, REQUEST_BULK_PERMISSION);
return;
}
}
if (onPermissionCallBack != null)
onPermissionCallBack.permissionGranted();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (onPermissionCallBack != null)
onPermissionCallBack.permissionGranted();
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
if (onPermissionCallBack != null)
onPermissionCallBack.permissionDenied();
}
}
public interface RequestPermissionAction {
void permissionDenied();
void permissionGranted();
}
Post a Comment for "Application Not Asking To Get Permissions"