【问题标题】:I want it to open url in app, not webview我希望它在应用程序中打开 url,而不是 webview
【发布时间】:2016-03-02 20:23:09
【问题描述】:

我在这里搜索,但几乎所有问题都是相反的......现在我问; 我有一个适用于 android studio 的 webview 应用程序。它通过我的 webview 应用程序打开位于 HTML 页面中的所有 URL。

但我想添加一些例外。例如,我希望 https://play.google.com.... 在默认的 Google Play 应用中,而不是我的 webview 应用中。

总结:webview 应用程序必须通过应用程序本身打开一些正常的 URL,但通过本机另一个应用程序打开一些异常的 URL...

我的 webviewclient 代码是这样的;

public class MyAppWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().endsWith("http://play.google.com")) {

            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}

【问题讨论】:

  • 调试过你的代码了吗?我猜“if”语句是错误的?

标签: java android webview


【解决方案1】:

如文档here中所述:

如果您真的想要一个成熟的网络浏览器,那么您可能想要 使用 URL Intent 调用浏览器应用程序而不是显示 使用 WebView。

例如:

Uri uri = Uri.parse("http://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

至于您的 Google Play 特定问题,您可以在此处了解如何操作:How to open the Google Play Store directly from my Android application?

编辑


可以拦截来自WebView 的链接点击并执行您自己的操作。取自this answer

WebView yourWebView; // initialize it as always...
// this is the funny part:
yourWebView.setWebViewClient(yourWebClient);

// somewhere on your code...
WebViewClient yourWebClient = new WebViewClient(){
    // you tell the webclient you want to catch when a url is about to load
    @Override
    public boolean shouldOverrideUrlLoading(WebView  view, String  url){
        return true;
    }
    // here you execute an action when the URL you want is about to load
    @Override
    public void onLoadResource(WebView  view, String  url){
        if( url.equals("http://cnn.com") ){
            // do whatever you want
        }
    }
}

【讨论】:

  • 我必须使用本地 HTML 页面...网址位于其中...所有网址都使用我的 webview 应用程序打开...很好。但我只想要一个特殊的网址......我只想要用它的应用程序打开谷歌播放链接......而不是我的 webview 应用程序
【解决方案2】:

shouldOverrideUrlLoading 处返回 false 表示当前 WebView 处理 URL。所以你的 if 语句必须改变:

public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (Uri.parse(url).getHost().equals("play.google.com")) {
        // if the host is play.google.com, do not load the url to webView. Let it open with its app
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);

        return true;
    }
    return false;
}

【讨论】:

  • 我用过这个但是一样...任何改变...我使用 loadUrl("file:///android_asset/home.html");显示一个本地 HTML 文件...和 ​​google play URL 位于其中。但是当我单击它时,所有 URL 都使用 webview 打开...我不想要这个,我希望所有链接都使用 webview 打开,但一个 URL 除外:google play url 必须使用自身的应用程序打开..
猜你喜欢
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多