Android 6.0 Marshmallow Can Not Write on SD Card

Android marshmallow needs some permissions to be granted on runtime.
There are two types of permissions in Android:
1.Dangerous (access to contacts, write to external storage…)
2.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.
1.Check if you have the permission granted
2.If your app is already granted the permission, go ahead and perform normally.
3.If your app doesn’t have the permission yet, ask for user to approve
4.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();
            }
        }
    }
}
You can read more about the new permission model here: https://developer.android.com/training/permissions/requesting.html
For that application which source code is not successfully modified to support Runtime Permission, DO NOT release it with targetSdkVersion 23 or it will cause you a trouble. Move the targetSdkVersion to 23 only when you pass all the test.

 Warning: Right now when you create a new project in Android Studio. targetSdkVersion will be automatically set to the latest version, 23. If you are not ready to make your application fully support the Runtime Permission, I suggest you to step down the targetSdkVersion to 22 first.

Ashraf-ul- Huque

Software Engineer

TopOfStack Software Ltd.