Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android 11 ACTION_OPEN_DOCUMENT_TREE: set initial URI to the Documents folder [duplicate]

using the Scoped Storage model in Android 11 I want to give the user the ability to choose a folder, starting in the documents folder:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI,    ???     )
startActivityForResult(intent, OPEN_DIRECTORY_REQUEST_CODE,null)

The problem is, how can I generate a proper URI of the phone's documents folder? (It sits just in root / ) In the official documentation, no examples are given. I really hope there are some neat constants for all the standard locations?

like image 453
Kenobi Avatar asked Oct 23 '25 16:10

Kenobi


1 Answers

We have to manipulate INITIAL_URI obtained from StorageManager..getPrimaryStorageVolume().createOpenDocumentTreeIntent().

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
    StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

    Intent intent = sm.getPrimaryStorageVolume().createOpenDocumentTreeIntent();
    //String startDir = "Android";
    //String startDir = "Download"; // Not choosable on an Android 11 device
    //String startDir = "DCIM";
    //String startDir = "DCIM/Camera";  // replace "/", "%2F"
    //String startDir = "DCIM%2FCamera";
    String startDir = "Documents";

    Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");

    String scheme = uri.toString();

    Log.d(TAG, "INITIAL_URI scheme: " + scheme);

    scheme = scheme.replace("/root/", "/document/");

    scheme += "%3A" + startDir;

    uri = Uri.parse(scheme);

    intent.putExtra("android.provider.extra.INITIAL_URI", uri);

    Log.d(TAG, "uri: " + uri.toString());

    ((Activity) context).startActivityForResult(intent, REQUEST_ACTION_OPEN_DOCUMENT_TREE);

    return;
}
like image 159
blackapps Avatar answered Oct 26 '25 07:10

blackapps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!