Why your app can’t see SD Card on Android Marshmallow

On Android Marshmallow just having the READ_EXTERNAL_STORAGE in your AndroidManifest.xml is not enough anymore to read the SD Card. Your app now needs to explicitly request this permission from the user. This is true even if your app was built with targetSDKVersion well below Marshmallow.

This can be fixed in the application by adding the following code into your main activity (or into an activity which attempts to access SD Card).

a) If your application is targeting API < 23:

if ( ContextCompat.checkSelfPermission( this, 
                                        android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                                           != PackageManager.PERMISSION_GRANTED )
 ActivityCompat.requestPermissions( this, 
                   new String[]{ android.Manifest.permission.READ_EXTERNAL_STORAGE }, 0 );

You will also need to include the Android support library if you haven’t done so already, by adding the following line into your module (not global) build.gradle:

dependencies {
 compile 'com.android.support:appcompat-v7:23.2.0'
 }

since this functionality was only added in version 23, you also need to ensure that your compileSdkVersion (in the same file) is at least 23.

b) If your application is targeting API 23+ (meaning your minSdkVersion is at least 23), you do not need Compat libraries, and just need to add:

if ( checkSelfPermission( android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                                              != PackageManager.PERMISSION_GRANTED )
    requestPermissions( new String[]{ android.Manifest.permission.READ_EXTERNAL_STORAGE }, 0 );
This entry was posted in Uncategorized.

Comments are closed.