Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Webview, make urls open in different browser

when I click on links in my app, they open in the same webview. I want them to open in an external browser.

I did this:

myWebView.setWebViewClient(new WebViewClient()
{
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }

});

returning false makes it load within the same webview, and returning "true" makes nothing happen when a link is clicked.

I looked at other questions but it seems that everyone else has the exact opposite problem. (they want links to load in their app)

what am I doing wrong?

like image 966
CQM Avatar asked Dec 15 '11 18:12

CQM


2 Answers

In your WebViewClient

@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url){
    if (loadUrlExternally){
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        return true; //the webview will not load the URL
    } else {
        return false; //the webview will handle it
    }
}

That way it opens a new browser window the same way any other app would.

like image 78
Reed Avatar answered Nov 17 '22 09:11

Reed


Here's a more complete answer. Note: I'm calling from a fragment hence the getActivity() before startActivity()

    @Override
    public boolean shouldOverrideUrlLoading(final WebView view, final String url)
    {
        //check if the url matched the url loaded via webview.loadUrl()
        if (checkMatchedLoadedURL(url))
        {
            return false;
        } else
        {
            getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }

/**
     * used to check if the loaded url matches the base url loaded by the fragment(mUrl)
     * @param loadedUrl
     * @return true if matches | false if doesn't or either url is null
     */
    private boolean checkMatchedLoadedURL(String loadedUrl)
    {
        if (loadedUrl != null && mUrl != null)
        {
            // remove the tailing space if exisits
            int length = loadedUrl.length();
            --length;
            char buff = loadedUrl.charAt(length);
            if (buff == '/')
            {
                loadedUrl = loadedUrl.substring(0, length);
            }

            // load the url in browser if not the OTHER_APPS_URL
            return mUrl.equalsIgnoreCase(loadedUrl);
        }
        return false;
    }
like image 41
scottyab Avatar answered Nov 17 '22 10:11

scottyab