【问题标题】:Launch Browser Intent with Custom Class - cannot find Activity使用自定义类启动浏览器意图 - 找不到活动
【发布时间】:2011-03-20 17:38:00
【问题描述】:

我想专门为给定的 URL 运行默认的 Android 浏览器。我正在使用此代码:

Intent i = new Intent();
i.setAction("android.intent.action.VIEW"); 
i.addCategory("android.intent.category.BROWSABLE");
i.setClassName("com.google.android.browser", "com.android.browser.BrowserActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(url));
startActivity(i);

我收到的错误是:

Unable to find explicit activity class {
com.google.android.browser/com.android.browser.BrowserActivity}; 
have you declared this activity in your AndroidManifest.xml?

我也试过按包过滤意图:

i.setPackage("com.google.android.browser");

而不是setClassName,但无济于事:

No Activity found to handle Intent { act=android.intent.action.VIEW 
cat=[android.intent.category.BROWSABLE] 
dat=http://www.google.com/ flg=0x10000000 pkg=android }

我还尝试将<uses-library android:name="com.google.android.browser" /> 添加到清单中。

我错过了什么吗?

PS:我对使用startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"))) 不感兴趣,因为它会列出浏览Intent 的所有选项。

【问题讨论】:

    标签: android android-emulator android-intent android-browser


    【解决方案1】:

    我用这个,没关系。

    intent.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
    

    我想你知道哪里错了。 :)

    【讨论】:

      【解决方案2】:

      请注意默认浏览器可以被覆盖,它并不总是内置的浏览器应用程序,它可以是例如 Opera Mini。

      你需要这样做:

      Intent intent = new Intent(Intent.ACTION_VIEW);
      Uri data = Uri.parse("http://www.google.com");
      intent.setData(data);
      startActivity(intent);
      

      【讨论】:

      • 正如我在问题中所述,我希望能够运行 默认 Android 浏览器,而不是 默认选择 浏览器。作为一个侧节点,我首先尝试了您提到的解决方案,但无济于事,因为它显然会启动设置为默认的浏览器(或启动应用程序选择器)。
      • 如何在非活动类中使用这个意图??
      • 这样做的缺点 - 对于本地 html 文件,它会启动 HTMLViewer 应用程序而不是浏览器。
      【解决方案3】:

      通过代码在浏览器中打开 URL 的一种方法是使用 webview。

      创建一个扩展 WebViewClient 的 WebViewClientClass:

      public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return true;
      }
      

      然后创建一个 webview。 Set webview.setWebViewClient(new WebViewClientClass()); --- 这是一个小的解决方法,因此默认的网络浏览器不会接管。

      然后在edittext中获取url并将其设置为加载浏览器:

      webview.loadurl(urlfield.getText().toString());
      webview.requestFocus();
      

      这应该会使用您请求的 URL 加载 Web 浏览器。

      希望这会有所帮助... :)

      【讨论】:

      • 如果您希望您的默认网络浏览器接管您的请求,请不要设置 webview.setWebViewClient ...
      • 我不想启动浏览器窗口(或者为此使用我自己的浏览器)。我想启动 Android 自带的默认浏览器。此外,启动浏览器窗口会带来额外的复杂性,例如管理缓存、书签、后退按钮等。顺便说一句,请格式化您的代码;)
      猜你喜欢
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多