Failed to create directory on Android 6.0 using mkdirs (storage permission is ok)

I am trying to update the application source code to Android 6.0 with new runtime permissions.

But if the user grants storage permission, the application cannot create directories in the method 'onRequestPermissionsResult'using 'mkdirs'.

In AndroidManifest.xml I put 'uses-permission':

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xample.provasd"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="23" />

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

    <!-- application, activity, etc -->

Then in MainActivity I deal with a permission request:

public void executeButton(View view){
        final String[] PERMISSIONS_STORAGE = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
        //Asking request Permissions 
        ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE, 9);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean writeAccepted = false;
        switch(requestCode){
        case 9:
            writeAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
            break;
        }
        if(writeAccepted){
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File dir = new File(Environment.getExternalStorageDirectory()+"/"+"TestFolder");
                boolean b = dir.mkdirs();
                if(b){
                    Log.i("TAG", "WOW! "+dir+" created!");
                }else{
                    Log.e("TAG", "OPS! "+dir+" NOT created! To be sure: new dir exist? "+dir.exists());
                }
            }
        }       
    }

Starting the application on the emulator, a request dialog box is displayed: permission to allow the body 'onRequestPermissionsResult'is executed (writeAccepted=true), but the folder has not been created!

This is what appears in LogCat:

I/TAG(9020): Permission ok
I/TAG(9020): Try to create dir: /storage/3143-1CEA/TestFolder
E/TAG(9020): OPS! /storage/3143-1CEA/TestFolder NOT created! To be sure: new dir exist? false

I do not understand the reason.

Please can someone help me?

Thanks,

Mirko

+4
1

. Android 6.0, , .

+1

Source: https://habr.com/ru/post/1628591/


All Articles