查看intent.resolveActivity != null 但启动意图会引发 ActivityNotFound 异常,我写的是打开浏览器或具有深度链接的应用程序:
private fun openUrl(url: String) {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
data = Uri.parse(url)
// setDataAndType(Uri.parse(url), "text/html")
// component = ComponentName("com.android.browser", "com.android.browser.BrowserActivity")
// flags = Intent.FLAG_ACTIVITY_CLEAR_TOP + Intent.FLAG_GRANT_READ_URI_PERMISSION
}
val activityInfo = intent.resolveActivityInfo(packageManager, intent.flags)
if (activityInfo?.exported == true) {
startActivity(intent)
} else {
Toast.makeText(
this,
"No application can handle the link",
Toast.LENGTH_SHORT
).show()
}
}
它不起作用。在 API 30 模拟器中找不到浏览器,而通用解决方案有效:
private fun openUrl(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(
this,
"No application can handle the link",
Toast.LENGTH_SHORT
).show()
}
}
第一种方法不起作用,因为intent.resolveActivityInfo
orintent.resolveActivity
返回null
。但是对于 PDF 查看器,它可以工作。
我们应该解雇intent.resolveActivity
吗?