mkdirs()使用write external权限返回false

时间:2015-11-11 15:00:14

标签: android

我的mkdirs功能有问题。请参阅我的权限清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="xxxxxx"
android:versionCode="15"
android:versionName="3.1.1508">

<!-- Global permissions -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我的代码

String APP_PATH_SD_CARD = "/xxxxx";
    String fullPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + APP_PATH_SD_CARD;

    if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        ToastDressmup.make(this, "External SD card not mounted", 0, ToastAction.CLOSE.getValue()).show();
    }

    try {
        File dir = new File(fullPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        ==> My file doesn't exist

已安装SD卡。我不明白。我在互联网上阅读了很多答案,但它仍然是错误的。

我在模拟器上测试过(使用模拟的SD卡),在Nexus 5上,它不起作用。在我的HTC One X上工作,为什么?我绝望了

谢谢大家! -G。

1 个答案:

答案 0 :(得分:1)

正如评论中所解决的那样,答案是缺少权限。

自Android 6以来,权限处理已按规定更改:

Exception 'open failed: EACCES (Permission denied)' on Android

Android permission doesn't work even if I have declared it

您需要在运行时再次收集这些权限:

  

引用第一个回答:

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}