Search code examples
androidandroid-permissions

Permission denied on writing to external storage despite permission


I have an Android 7.0 test device and my APK targets = "targetSdkVersion 22", with:

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

with:

final File f = new 
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "DressUpBaby" + photonumber + ".png");
f.createNewFile();

and at this point I get the warning:

W/System.err: java.io.IOException: Permission denied

How to get it to save the file? This was working when I created this on Eclipse, but now that I have updated and moved to Android Studio it seems to have broken something.


Solution

  • If you're running your app on API level 23 or greater you have to request permission at runtime.

    Request permission:

    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    requestPermissions(permissions, WRITE_REQUEST_CODE);
    

    Then handle the result:

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
           case WRITE_REQUEST_CODE:
             if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
               //Granted.
    
    
             }
           else{
               //Denied.
             }
            break;
        }
    }
    

    For more information visit Requesting Permissions at Run Time - Android Doc