1

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);
    }
}
MSeiz5
  • 182
  • 1
  • 9
  • 28

1 Answers1

3
  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.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • This works fine. I get the sharedPrefs with value `content://com.android.externalstorage.documents/tree/B9BE-18A6%3ADownload` and can create a file with `writeFile(pickedDir, "testfilewhatever.txt");` How can I add a new folder named "test" in the folder "Download" to create a file there? `String str_pref = prefs.getString("treeUri", "defaultValue") + "/test";` doesn't work. It still creates the file in the "download" folder – MSeiz5 Apr 19 '17 at 09:47
  • Your question is answered. If you have another question then make a new post. – greenapps Apr 19 '17 at 10:13