How to open external URL in default browser and al

2020-08-03 03:36发布

问题:

I am using WebView in my page and using local file assets to displaying in WebView but in main HTML page external website (not local) and I want to open just that link in default Browser on the users device

This is my code in 'onCreate' method

WebView v;

v=(WebView) rootView.findViewById(R.id.webView1);
v.getSettings().setJavaScriptEnabled(true);
WebViewClient vc= new WebViewClient();
v.setWebViewClient(vc);
v.loadUrl("file:///android_asset/home.html");

When I run the application the internal link is working good but the external link "www.apple.com" en in the web view

I searched the same question and found this solution but still external link opens in WebView

WebView webView = (WebView) rootView.findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
String url = "file:///android_asset/home.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);

and class

class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("http")){ // Could be cleverer and use a regex
            return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
        } else {
            view.loadUrl(url); // Stay within this webview and load url
            return true;
        }
    }
}

回答1:

Change

  if (url.contains("http")) { // Could be cleverer and use a regex
    return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
  } else {
    view.loadUrl(url); // Stay within this webview and load url
    return true;
  }

to

 if (url.contains("http")) { // Could be cleverer and use a regex
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    mContext.startActivity(intent);
    return true;
 }
 return false;

Note : replace mContext with your activity context.