'How can I set the ACTION_OPEN_DOCUMENT_TREE start path the first time a user uses my app?

I've seen a lot of questions regarding setting the start Uri for the Intent.ACTION_OPEN_DOCUMENT_TREE but all of those require a Uri that comes from having used that folder picker before.

What I want to do is send my users directly to the Download folder when picking the folder but I do not know how to convert /storage/emulated/0/Download to a Uri that I can pass as an extra using DocumentsContract.EXTRA_INITIAL_URI.

Is there a way to convert any file path to a DocumentsContract style Uri?

Edit: Just to be clear, I'm talking about the uri passed here:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
        .setFlags(
            Intent.FLAG_GRANT_READ_URI_PERMISSION
            or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
        )
        .putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)


Solution 1:[1]

We manupulate INITIAL_URI of .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";

    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;
}

The logs will print something like:

INITIAL_URI scheme: content://com.android.externalstorage.documents/root/primary
uri: content://com.android.externalstorage.documents/document/primary%3ADownload

Solution 2:[2]

The easiest way to do it is:
for example, if i want the user to select MEDIA folder of WhatsApp

                    val i = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
                    val initial = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia")
                    i.putExtra(DocumentsContract.EXTRA_INITIAL_URI, initial)
                    startActivityForResult(i, SCOPED_REQUEST_WA)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hata
Solution 2 Nasib