未找到可使用有效 url 处理 Intent 错误的活动

jus*_*ust 3 android android-intent activitynotfoundexception

我有这个小方法:

private fun showWebsiteWithUrl(url: String) {
    val i = Intent(Intent.ACTION_VIEW)
    i.data = Uri.parse(url)
    startActivity(i)
}
Run Code Online (Sandbox Code Playgroud)

我在 google play 中看到有时这种方法会抛出android.content.ActivityNotFoundException异常。

url参数是一个有效的 url,如下所示:http : //www.stackoverflow.com/

这是堆栈跟踪的开始:

由 android.content.ActivityNotFoundException 引起:No Activity found to handle Intent { act=android.intent.action.VIEW dat= http://www.stackoverflow.com/ ... }

我无法在我的手机上重现该问题,用户在华为 Y5 (DRA-L21) Android 8 上遇到此错误,有时在使用 android 9 的小米设备上也会遇到此错误。

rah*_*mli 5

您正在使用隐式意图打开 Web 链接。用户可能没有任何应用程序来处理您发送到的隐式意图startActivity()。或者,由于配置文件限制或管理员实施的设置,应用程序可能无法访问。如果发生这种情况,调用将失败并且您的应用程序崩溃。要验证活动是否会收到意图,请调用resolveActivity()您的Intent对象。如果结果为非空,则至少有一个应用程序可以处理该意图并且调用是安全的startActivity(). 如果结果为空,请不要使用意图,如果可能,您应该禁用发出意图的功能。以下示例显示了如何验证意图是否解析为活动。此示例不使用 URI,但声明了意图的数据类型以指定附加内容携带的内容。

// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");

// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}
Run Code Online (Sandbox Code Playgroud)