即使已授予权限也无法读取或写入外部存储

Can not read or write external storage even though permissions granted

有权限但不能读写

boolean write = checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
boolean read = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

Log.e(TAG, "aaaa WRITE=" + write + ", READ=" + read);
File dir = Environment.getExternalStorageDirectory();
Log.e(TAG, "aaaa DIR=" + dir);
Log.e(TAG, "aaaa canRead=" + dir.canRead() + " canWrite=" + dir.canWrite() + " canExecute=" + dir.canExecute());

打印:

2021-06-12 12:30:07.256 3196-3196/ aaaa WRITE=true, READ=true
2021-06-12 12:30:07.257 3196-3196/ aaaa DIR=/storage/emulated/0
2021-06-12 12:30:07.260 3196-3196/ aaaa canRead=false canWrite=false canExecute=true

这已从 API 29 中弃用,作为对用户隐私的改进,因此以 API 29 或更高版本为目标的应用将无法直接访问返回的路径。

这是 link 替代文档 https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

requestLegacyExternalStorage 添加到清单文件:

 <application
    ...
    android:requestLegacyExternalStorage="true"
    ...>