Android "open with" 实施

Android "open with" implementation

我正在尝试使用 Kotlin 在 Android 应用中打开下载的文件。目前我可以通过使用以下代码设置文件类型来使用系统上推荐的应用程序打开

class Somelistener(private val workManager: WorkManager, private val adapter: someAdapter, private val lifecycle: LifecycleOwner) : AdapterView.OnItemClickListener {


private fun openWithOther(path: String?, context: Context?) {
    if (path == null || context == null) {
        return
    }
    val uri: Uri = Uri.fromFile(File(path))
    val mime: String? = getMimeType(path)

    val intent = Intent()
    intent.action = Intent.ACTION_VIEW
    intent.setDataAndType(uri, mime)
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    startActivity(context, intent, null)
}

但是,我们不需要直接打开文件,而是通过“打开方式”提示询问用户,用户可以在其中试用他想用哪个应用程序打开它。

这可以做到吗?有什么样的意图?

次要问题,不需要回答,在 startActivity 有意地,包应该是空的,因为我有它吗?另外我似乎找不到一些 startActivity 作为结果。

你要找的是App chooser。你可以通过 Intent.createChooser(target, title) 创建它。在您的场景中,它将是:

with(Intent(Intent.ACTION_VIEW)) {
    setDataAndType(uri, mime)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    val chooserIntent = Intent.createChooser(this, null)
    activity?.startActivity(chooserIntent)
}

App Chooser