1
private val directoryLauncher =
    registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {...}
val i = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
directoryLauncher.launch(Intent.createChooser(i, "Choose directory"))

I used to use this piece of code to launch a folder picker with the AOSP Files app. Now when I try it on my new Xiaomi phone, it launches a file picker on the Xiaomi File Manager app. Is there an alternative that works on all phones?

Shazniq
  • 423
  • 4
  • 16

1 Answers1

4

You're using a wrong way to do this. Use this code:

For Java

private final ActivityResultLauncher<Uri> mDirRequest = registerForActivityResult(
            new ActivityResultContracts.OpenDocumentTree(),
            uri -> {
                if (uri != null) {
                    // call this to persist permission across decice reboots
                    getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    // do your stuff
                } else {
                    // request denied by user
                }
            }
    );

For Kotlin

private val dirRequest = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
    uri?.let {
       // call this to persist permission across decice reboots
       contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
       // do your stuff
    }
}

Then, when you want to launch this request, call:

dirRequest.launch()
// or optionally pass an initial path as uri string
dirRequest.launch("content://some_path")
  • It's dirRequest.launch(null) instead of no arguments apparently. Also, thanks a lot, you've saved me from a lot of headache. – Shazniq Jan 31 '22 at 23:47
  • I can not seem to edit this answer but you indeed need to pass a null variable – Zun Oct 17 '22 at 18:10