'How to write into a file picked by user in Android 12
I encounter a problem only on Android 12, I try to add some lines into a file localized in a folder that the user pick.
I worked on a Samsung A70 (Android 11), and to accomplish that I launch an Intent.ACTION_OPEN_DOCUMENT_TREE, check all to have to be checked (not null, file existing etc).
After that, i launch an getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); to keep the permission.
And this is working on the Samsung A70, but I need this in my Samsung S22 (Android 12) too, but it doesn't work.
I got an java.io.FileNotFoundException: Failed to open for writing: java.io.FileNotFoundException: open failed: EACCES (Permission denied) when trying to write something.
What i try:
I decide to change to an Intent.ACTION_OPEN_DOCUMENT to pick only the file i need, take a persistant permission too, but again this error.
I try to print all files access into the folder that the user picked:
DocumentFile dir = DocumentFile.fromTreeUri(this, data.getData());
if(null != dir){
for(DocumentFile d : dir.listFiles()){
System.out.println(d.getName() + "> Access: (R/W) " + d.canRead() + " - " + d.canWrite());
}
}
And I got this with Android 12:S22 logcat of the function above
And this on Android 11: A70 logcat of the function above
With the same code.
The file I need to write on is the json file (hardware[...].json)
In the Android Doc I saw that the canWrite methods can return true, even though my app cannot write into, so they recommended to query the flag FLAG_SUPPORTS_WRITE directly, what i done:
try{
System.out.println(data.getFlags());
System.out.println(data.getFlags() & DocumentsContract.Document.FLAG_SUPPORTS_WRITE);
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(data.getData(), "w"); //Error here
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fos.close();
}catch//***//
And got this into the logcat (Android 12): logcat test flags android 12
And on Android 11: logcat test flags android 11
The first value is 0b1000011, the FLAG_SUPPORTS_WRITE value is 0b10 (1 << 1) (Doc)
So the second print is 2, showing that the flag is ok. But the line after, an error is throwed.
That all, if anyone have an idea to solve this problem with me, thank you! :D
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
