简体   繁体   中英

Cannot create new file on Android 10 SD card

My issue is that on some devices, in this particular case on Android 10, stock Huawei p30 EMUI 10, I cannot create a new SD card file. documentFile.createFile(...) returns null, DocumentsContract.createDocument(...) throws a weird exception that I cannot find anywhere. It says " java.lang.IllegalArgumentException: Requested path ... doesn't appear under ... ", as seen on the attached image.

异常吐司

Both mentioned functions have proper arguments, like mimetype and path. I don't have the device myself, I'm debugging it with a guy via email. At listing his storages there is no "/mnt/media_rw" mentioned anywhere, the SD card partition seems to be called "/storage/0123-4567". All other SD card file operations work, those extra SAF permissions are requested and handled properly. The code itself works just fine on the vast majority of devices, on my Android 10 too. I have target, compile SDKs set to 28, build tools 28.0.3.

Has anyone encountered such an issue? Any ideas how could it be solved? I'm afraid that it will be happening always more often as Android 10 grows and manufacturers continue doing things differently. Not to talk about the changes coming from SDK 29. Thanks

alright, so it looks like documentFile.createFile actually works, but it returns null. So just creating a brand new DocumentFile with the targeted path seems to work just fine.

Some additional info if someone encounters the same problem:

Context: As many Huawei users 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 that

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

and suspects that

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

Solution: As the question's author has already found, even though calling createFile() returns null , the file has been properly created. You can use findFile() to get it, for example:

// 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);
}

If at that point file is still null , then I think it's another issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM