Issue
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?
Solution
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")
Answered By - user17321981
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.