在浏览器中打开 URL,即使我的应用程序为它注册了一个 intent-filter

Open URL in browser even though my app registered an intent-filter for it

我的应用为某些 URL 注册了一个 Intent 过滤器,因为它可以处理来自那些 URL 的数据。

但是,在应用程序内部,我想提供一个按钮来在浏览器中打开这样一个 URL。也就是说,如果已设置,则在默认浏览器中打开它,否则提供一个选择器 - 就像正常一样。

现在,当我的应用程序被设置为那些 URL 的默认值并且我按下按钮时,我自然会一次又一次地在我的应用程序中得到相同的 activity。

有什么想法吗?

您可以执行以下两项操作之一:

  1. 如果您知道浏览器将安装一个明确的 Intent(例如 Chrome)
  2. 使用

    创建选择器

    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.com")); Intent chooserIntent = Intent.createChooser(i, "Title for chooser"); startActivity(chooserIntent);

您可以阅读有关 createChooser 的更多信息here

我最后做的是:

Intent i = new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://website.com/entries/" + entry_id));

// Check what is the default app to handle these entry URLs

ResolveInfo defaultResolution = getPackageManager().resolveActivity(i,
        PackageManager.MATCH_DEFAULT_ONLY);

// If this app is the default app for entry URLs, use the browser instead

if (defaultResolution.activityInfo.packageName.equals(getPackageName())) {

    Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));

    ResolveInfo browseResolution = getPackageManager().resolveActivity(browseIntent,
            PackageManager.MATCH_DEFAULT_ONLY);

    i.setComponent(new ComponentName(
            browseResolution.activityInfo.applicationInfo.packageName,
            browseResolution.activityInfo.name));

}

startActivity(i);