无法在 Android 10 SD 卡上创建新文件

Cannot create new file on Android 10 SD card

我的问题是在某些设备上,在 Android 10 的这种特殊情况下,库存华为 p30 EMUI 10,我无法创建新的 SD 卡文件。 documentFile.createFile(...) returns null, DocumentsContract.createDocument(...) 抛出一个奇怪的异常,我在任何地方都找不到。如附图所示,它显示“java.lang.IllegalArgumentException: Requested path ... doesn't appear under ...”。

上述两个函数都有适当的参数,例如 mimetype 和路径。我自己没有设备,我正在通过电子邮件与一个人一起调试它。在列出他的存储时,没有任何地方提到“/mnt/media_rw”,SD 卡分区似乎被称为“/storage/0123-4567”。所有其他 SD 卡文件操作都有效,这些额外的 SAF 权限已被正确请求和处理。代码本身在绝大多数设备上都运行良好,在我的 Android 10 上也是如此。我有目标,编译 SDK 设置为 28,构建工具 28.0.3。

有人遇到过这样的问题吗?任何想法如何解决?恐怕随着 Android 10 的增长和制造商继续以不同的方式做事,这种情况会越来越频繁地发生。更不用说 SDK 29 带来的变化了。谢谢

好吧,看起来 documentFile.createFile 确实有效,但它 returns 无效。因此,只需使用目标路径创建一个全新的 DocumentFile 似乎就可以了。

如果有人遇到同样的问题,请补充一些信息:

背景:have noticed, the update from EMUI 9 to EMUI 10 has broken a number of apps that rely on write access to the SD card. The problem has been reported to Huawei, who shifted the blame onto Google and does not seem to be taking any further action. The developer of the app Total Commander, which was affected by the problem, found out 一样多的华为用户

On Huawei devices with Android 10, DocumentsContract.createDocument successfully creates the file, but then causes an exception

并怀疑

apparently Huawei hardcoded some paths where the user should be allowed to create files, but made a mistake.

解决方法:正如题主已经发现的,即使调用createFile()returnsnull,文件也已经正确创建.可以使用findFile()获取,例如:

// treeUri comes from the file picker
DocumentFile directory = DocumentFile.fromTreeUri(context, treeUri);
DocumentFile file = docFile.createFile(mimeType, filename);

if (file == null) {
    file = docFile.findFile(filename + "." + mimeTypeExtension);
}

如果那时 file 仍然是 null,那么我认为这是另一个问题。