【发布时间】:2020-10-13 13:54:33
【问题描述】:
看着intent.resolveActivity != null but launching the intent throws an ActivityNotFound exception我写了用深度链接打开浏览器或应用程序:
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 模拟器中找不到浏览器,而常见的 solution 可以工作:
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 或intent.resolveActivity 返回null。但对于 PDF-viewer,works.
我们应该解雇intent.resolveActivity吗?
【问题讨论】:
-
假设您的目标是 API 级别 30,这似乎是由于:Package visibility in Android 11。事实上,当我在清单中使用适当的
<queries>元素测试您的第一个 sn-p 时,它按预期工作。如果您不想包含这样的<queries>,那么您可以坚持使用try-catch。 -
@MikeM.,谢谢!您可以将其发布为答案吗?我稍后会测试它。
-
哦,抱歉,我误读了您的评论。我以为你会在测试后发布它。我现在无法整理出正确的答案,但稍后我会在有空的时候讨论。如果您只是想完成这个问题,请随时自己发布一个,如果您愿意的话。我并不十分担心代表或其他任何事情。 :-) 干杯!
-
抱歉拖了这么久。我真的很想找到一些与您的具体示例更相关的文档或源代码,但我从来没有这样做过。然后我有点忘记了。我的错。干杯!
标签: android android-intent android-manifest android-11 activitynotfoundexception