奥利奥在外部存储上创建目录时出现问题

Oreo problem in creating a directory onto the external storage

我尝试在 android 外部存储中创建文件夹。我尝试了很多例子,但都没有用。我设置了 运行 次读写外部存储的权限。它适用于 Android API 6、7。但不适用于 Android Oreo。

File f = new File(Environment.getExternalStorageDirectory(), "MyDir");
    if (!f.exists()) {
        try {
            boolean is_seccess = f.mkdirs();
            if (is_seccess) {
                Toast.makeText(this, "create", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "not create", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

我检查了外部存储是否可以读写,return 正确。

public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

我授予以下权限,我也授予 运行-time 权限并允许它。

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

只是 Android Oreo 不工作,其他设备工作正常。我的代码有什么问题?

应用请求 READ_EXTERNAL_STORAGE,用户同意。如果应用的目标是 API 级别 25 或更低,系统也会同时授予 WRITE_EXTERNAL_STORAGE,因为它属于同一个 STORAGE 权限组,并且也在清单中注册。如果应用的目标是 Android 8.0(API 级别 26),系统当时只授予 READ_EXTERNAL_STORAGE;但是,如果应用稍后请求 WRITE_EXTERNAL_STORAGE

请求 运行 时间许可,如下所示:

private boolean checkAndRequestPermissions() {
    int permissionReadStorage = ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE);
    int permissionCamera = ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA);
    int permissionWriteStorage = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    List<String> listPermissionsNeeded = new ArrayList<>();
    if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }
    if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
    }
    if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions((Activity) this,
                listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}