Android 文件夹选择器意图启动文件选择器

Android folder picker intent launches file picker

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

我曾经使用这段代码通过 AOSP 文件应用启动 文件夹 选择器。现在,当我在我的新小米 phone 上试用它时,它会在小米文件管理器应用程序上启动一个 文件 选择器。是否有适用于所有 phone 的替代方案?

您使用了错误的方法来执行此操作。使用此代码:

对于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
                }
            }
    );

对于 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
    }
}

然后,当你想发起这个请求时,调用:

dirRequest.launch()
// or optionally pass an initial path as uri string
dirRequest.launch("content://some_path")