Android:创建dir失败

时间:2016-11-20 05:06:12

标签: android mkdir android-external-storage

我无法使用这个简单的代码创建目录:

public class ExternalStorage {
    private final String BACKUPS_DIR = "MyDir";

    public String createBackupDir() {
        if (!isExternalStorageWritable()) {
            Log.e("MyApp", "Storage not writable");
            return null;
        }

        String path = Environment.getExternalStorageDirectory() +
                File.separator + BACKUPS_DIR;

        File folder = new File(path);

        boolean success = true;
        if (!folder.exists())
            success = folder.mkdirs();

        if (success)
            return path;

        Log.e("MyApp", "Backup Dir: creation failed");
        return null;
    }

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}

Environment.getExternalStorageDirectory()的返回值是:

/storage/emulated/0

日志是:

MyApp   : Backup Dir: creation failed

清单权限是:

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

mkdirs只返回false,我无法想象会发生什么,任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:0)

运行时权限就是答案,谢谢。