Open external links in the browser with android we

2019-01-07 11:29发布

I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in your default browser. Any idea? thanks

private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              if(url.contains("message2space.es.vu")){
                view.loadUrl(url);
                return true;
            }else{
                return super.shouldOverrideUrlLoading(view, url);
            }

            }
        }

3条回答
戒情不戒烟
2楼-- · 2019-01-07 11:54

Since API level 24 shouldOverrideUrlLoading(WebView view, String url) is deprecated.

Up to date solution:

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
            view.getContext().startActivity(intent);
            return true;
        }
    });
查看更多
男人必须洒脱
3楼-- · 2019-01-07 12:13

The problem is you need to send an Intent to the default web browser to open the link. What you are doing is just calling a different method in your Webview to handle the link. Whenever you want another app to handle something you need to use Intents. Try this code instead.

private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              if(url.contains("message2space.es.vu")) {
                view.loadUrl(url);
              } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
              }
              return true;
            }
        }
查看更多
一夜七次
4楼-- · 2019-01-07 12:21

Here is very sweet and short solution

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    context.startActivity(i);
    return true;
}
查看更多
登录 后发表回答