shubh jaiswal
shubh jaiswal

Reputation: 438

How to open extarnal url in default browser and all internal links in WebView Android?

I use this logic that every internal link contains 'myurl' string so it should be open in WebView and other external link in default browser.

package com.package.webviewapp;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        WebView webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new MyWebViewClient());

        String url = "http://myurl.com";
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);

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

but it is opening all links in WebView. as it is mentioned here Open link from Android Webview in normal browser as popup it should work.

Upvotes: 2

Views: 744

Answers (1)

Roll no1
Roll no1

Reputation: 1403

When you want to load other url use below method , it will open in default browser

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);

Upvotes: 1

Related Questions