Kushal Sharma Kushal Sharma - 7 months ago 76
Android Question

Android M User Permission Error - READ and WRITE

I just started off with android M and I am unable to access the external storage. I get the following error

Caused by: java.lang.SecurityException: Permission Denial: reading
com.android.providers.media.MediaProvider uri
content://media/external/images/media from pid=15355, uid=10053 requires
android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

I am adding user-permission in manifest like

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and my build file is with following settings :

compileSdkVersion 23
buildToolsVersion "22.0.1"

minSdkVersion 16
targetSdkVersion 23

How to read and write from external storage in android M?


Reading from the documentation. I have to ask user for permission at runtime. Code example :

Add permission to android manifest like we used to do earlier :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Check if the user has already granted the permission. If yes, skip asking for permission and continue with your work flow else ask user for permission :

    if (!Settings.System.canWrite(this)) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
    } else {
        // continue with your code
} else {
    // continue with your code

Now to check if the user granted the permission or denied it @Override OnRequestPermissionResult to get a callback :

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 2909: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("Permission", "Granted");
            } else {
                Log.e("Permission", "Denied");

I was not able to READ external storage only by asking WRITE permission, so i had to request for Manifest.permission.READ_EXTERNAL_STORAGE as well.

Also if you want to target versions below api 23, check the Build VERSION at runtime with IF statement and ask for permissions only if VERSION is equal or above Android M.