Search code examples
javaandroidandroid-10.0storage-access-frameworkandroid-11

can't control the initial directory where the SAF UI should start


I'm trying to save a text file using SAF (Storage Access Framework) but I can't control where it should be saved, I used this method from the Documentation as follows:

private void createFile(Uri pickerInitialUri) {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/*");
    intent.putExtra(Intent.EXTRA_TITLE, "new.txt");

    // Optionally, specify a URI for the directory that should be opened in
    // the system file picker when your app creates the document.
    intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);


    startActivityForResult(intent, CREATE_FILE);
}

Passing the root directory Uri as follows:

Uri.parse(Environment.getExternalStorageDirectory().toString())

But whatever string I parse and even if I pass null as Uri, the framework UI always starts in Downloads.

I want to save the file in the root directory. also, I want to save it automatically without any user interaction.


Solution

  • Quoting the documentation for EXTRA_INITIAL_URI:

    [The extra] should specify a document URI or a tree URI with document ID.

    A "document URI" is one that you obtained previously from ACTION_OPEN_DOCUMENT or ACTION_CREATE_DOCUMENT. A "tree URI" is one that you obtained previously from ACTION_OPEN_DOCUMENT_TREE. Uri.parse() is neither of those.