I faced the same problem. There are two types of permissions in Android:
- Dangerous (access to contacts, write to external storage...)
- Normal (Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.)
Here is the strategy to get dangerous permissions in Android 6.0
- Check if you have the permission granted
- If your app is already granted the permission, go ahead and perform normally.
- If your app doesn't have the permission yet, ask for user to approve
- Listen to user approval in
onRequestPermissionsResult
Here is my case: I need to write to external storage.
First, I check if I have the permission:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check the user's approval:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}