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

We will manupilate 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;
}

Leave a Comment