Skip to content Skip to sidebar Skip to footer

Android - Get Documentfile With Write Access For Any File Path On Sd Card (having Allready Gained Sd Card Permission)

In my app I gain sd card write permission using the following intent. If the user selects the sd card folder from the system file explorer then I have sd card write access. Intent

Solution 1:

Document.fromFile(File) doesn't seem to work properly for this purpose on recent devices

Here is link to the answer I've got the most information about the problem https://stackoverflow.com/a/26765884/971355

The key steps are:

  1. Get the write access to the SD card and make it persistent over the phone reboots

    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {

    ...

    getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    }

  2. After that you can access files and folders no matter how deeply they are nested, but you have to be aware of the complex URL that you'll have to deal with.

If you're a linux guy like me and used to think that everything is a file and everything is simple. This time it's not. A file on SD card, say /storage/13E5-2604/testDir/test.txt where 13E5-2604 is your SD card root folder will be:

content://com.android.externalstorage.documents/tree/13E5-2604%3A/document/13E5-2604%3A%2FtestDir%2Ftest.txt

in the new reality. Why they did it so complex - is another question...

I don't know an API method that transparently and easy converts a normal linux path to this new reality-path. But after you've done it (%3A is : and %2F is / See https://www.w3schools.com/tags/ref_urlencode.ASP for reference) you can create an instance of DocumentFile easily:

DocumentFile txtFile = DocumentFile.fromSingleUri(context,
Uri.parse("content://com.android.externalstorage.documents/tree/13E5-2604%3A/document/13E5-2604%3A%2FtestDir%2Ftest.txt"));

and write to it.

Solution 2:

to respond to @AndiMar (21 Mar), I just check if it exists on internal storage, if it does no need to worry.

try {
        if (sourcefile.toString().contains(Environment.getExternalStorageDirectory().toString())) {
            if (sourcefile.exists()) {
                sourcefile.delete();
            }
        } else {
            FileUtilitiesfio=newFileUtilities();
            DocumentFilefiletodelete= fio.getDocumentFileIfAllowedToWrite(sourcefile, context);
            if (filetodelete.exists()) {
                filetodelete.delete();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();

    }

Post a Comment for "Android - Get Documentfile With Write Access For Any File Path On Sd Card (having Allready Gained Sd Card Permission)"