我希望它在应用程序中打开URL,而不是webview

时间:2016-03-02 20:23:10

标签: java android webview

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

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

摘要:webview应用程序必须通过应用程序本身打开一些普通的URL,但是通过原生的另一个应用程序打开一些特殊的URL ......

我的webview客户端代码就是这样;

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;
    }
}

2 个答案:

答案 0 :(得分:2)

如文档here中所述:

  

如果你真的想要一个完整的网络浏览器,那么你可能想要   使用URL Intent而不是show来调用Browser应用程序   它带有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?

<强> EDITS

可以截取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
        }
    }
}

答案 1 :(得分:0)

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;
}
相关问题