java/android - 无法访问 SD 卡上的文件

java/android - Cannot access files on SD card

我正在为 Android 8.0 开发一个 Android 应用程序,我需要在其中 open/read 并从外部存储中删除文件 / SD 卡。

我的问题是,File file[] = directory.listFiles() returns NULL,但目录中有一个文件。

这是我的应用程序的调试器视图:

如您所见,我通过 Intent 请求(变量 resource)获取文件路径作为 URI。当前选择了SD卡上的文件夹Test

然后我想获取这个目录下的所有文件,但是函数listFiles()returns总是NULL!但文件夹中有 1 张图像:

有趣的是,此代码适用于 Android 4.4、5.0、6.0 和 7.0,但不适用于 Android 8!

权限在 Manifest.xml 中设置,每次启动时 requested/checked:

注意:Android启动应用时只显示1个权限请求,但它不应该请求2个权限吗?

希望大家能帮我解决问题。

此致, 迈克尔

解法:

尝试使用:

DocumentFile directory = DocumentFile.fromTreeUri(context, Uri.parse(resources.getUri()));

而不是:

File directory = new File(resources.getPath());

另见

ContextCompat.getExternalFilesDirs solves the access error

普遍真理:

1。 Android 7.0 提供了一个简化的 API 来访问外部存储目录。

Scoped Directory Access In Android 7.0, apps can use new APIs to request access to specific external storage directories, including directories on removable media such as SD cards...

For more information, see the Scoped Directory Access training.


2。 AndroidO变化。

Starting in Android O, the Storage Access Framework allows custom documents providers to create seekable file descriptors for files residing in a remote data source...

Permissions, prior to Android O, if an app requested a permission at runtime and the permission was granted, the system also incorrectly granted the app the rest of the permissions that belonged to the same permission group, and that were registered in the manifest.

For apps targeting Android O, this behavior has been corrected. The app is granted only the permissions it has explicitly requested. However, once the user grants a permission to the app, all subsequent requests for permissions in that permission group are automatically granted.

For example, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE...

希望对您有所帮助。