我正试图用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
。U可以通过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)
}
请参阅应用程序选择器