Cannot create directory in external storage although permissions are apparently set correctly

家住魔仙堡 提交于 2019-12-04 23:15:00
Mauricio

In my case I had to go under Settings -> Apps -> NameOfApp -> Permissions and activate the Storage permissions. I don't know why this comes deactivated by default if I have all the permissions on AndroidManifest.xml. I'm on a Moto G (3rd Gen) with Android Marshmallow 6.0.

You first need to use file.mkdirs() instead of folder.mkdir().

And if it also not worked then you need to check if you can access the sdcard or not.

For checking you can use below method.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {

    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;

} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {

    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;

} else {

    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;

}

Read at official document .

Hope it will give some clue to you.

You can try this code. I have also emulated sd card on Lg g2 mini and I can only access external card in my package folder

for(File f : getExternalFilesDirs(null)){
    try {
        File f2 = new File(f.getAbsolutePath(), "testFile");

        Log.d("test log", "file path " + f2.getAbsolutePath());
        f2.createNewFile();
        Log.d("test log", "file exist " + f2.exists());
    } catch (IOException e) {
        Log.d("test log", "error");
    }
}

and output is:

D/test log? file path /storage/emulated/0/Android/data/my.awesome.package/files/testFile
D/test log? file exist true
D/test log? file path /storage/external_SD/Android/data/my.awesome.package/files/testFile
D/test log? file exist true

Try this:

     final File externalStoragePublicDirectory = Environment.getExternalStorageDirectory();
     File file = new File(externalStoragePublicDirectory, "test");
     file.mkdirs();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!