I'm calling an intent using this:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, 42);
and selecting the root of my external SD card then taking the persisting permissions using this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 42) {
Uri treeUri = data.getData();
this.getContentResolver().takePersistableUriPermission(treeUri, (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
}
}
I can write files using an outputstream to the root (my initial selection) but I can not write to any other sub folders unless I ask for permission to them again and explicitly select them.
I am not doing anything fancy right now to determine what folders I have permissions to, I'm just creating a POC and trying to write files to sub folders of a folder that I have selected and given permissions to. I get a null exception on the DocumentFile object for the destination variable below using this:
DocumentFile dir = DocumentFile.fromTreeUri(cont, Uri.parse(myUriToRoot+"/subfolder"));
DocumentFile destination = dir.createFile("image/jpeg", "myfile.jpg");
Again, if I explicitly give permission to that subfolder it works. Everything I've read says that all existing subfolders and any newly created folders underneath the folder to which you've given permissions should allow access to write files but it's not working for me.
What am I missing?
TIA
EDIT: I've also tried using the URL encoding characters for the slashes in my URI and still doesn't work unless I select the subfolder directly with another call to my intent.
I was able to resolve this by instead of setting the fromTreeUri() method to the subfolder directly, keeping that at the root and then using findFile on another DocumentFile object, then using createFile on that next DocumentFile object.