androidandroid-permissionsandroid-sdcarddocumentfile

Android: How to get permanent write permission on removable sd-card?


I went through the Storage Access Framework for the last days and still don't get it.

My Question is: How can I create a file with those permissions on the sd-card without beeing prompt to select a patha after selecting the sd-card location once?

I can select a path on my sd-card for creating a file there with following code. (that works)

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(intent, 42);

And in onActivityResult I do

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

    if(resultCode!=RESULT_OK)
        return;
    Uri treeUri=resultData.getData();
    pickedDir= DocumentFile.fromTreeUri(getContext(), treeUri);
    getContext().grantUriPermission(getContext().getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    getContext().getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );

    writeFile(pickedDir, "testfile.txt");

}

public void writeFile(DocumentFile pickedDir, String filename) {
    try {
        DocumentFile file = pickedDir.createFile("text/plain", filename);
        OutputStream out = getContext().getContentResolver().openOutputStream(file.getUri());
        try {
            // write the file content
        } finally {
            out.close();
        }

    } catch (IOException e) {
        throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
    }
}

Solution

  •   Uri treeUri=resultData.getData();
    

    Save the treeUri for further use. For later use.

    You can save treeUri.toString() as a content scheme path in shared preferences.

    Then later retrieve the path string and reconstruct the Uri wit Uri.parse(path);

    After that use DocumentFile as you do now.

    Have a look at getPersistableUriPermissions(). If you use only one uri you dont have to save but can use this function.