luisfer
luisfer

Reputation: 603

WebView in Android fires standard browser

I have created an Activity in Android for displaying websites. I used this code:

private WebView mWebview; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    mWebview = new WebView(this);
    mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
    mWebview.loadUrl("http://blablabla");
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    setContentView(mWebview);

But when I use it with for example www.bild.de, or its mobile version wap.bild.de, it fires the standard browser and gets out from my app. The same if I tap a link from that website. I don't want that. What am I doing wrong? Thanks.

Upvotes: 0

Views: 193

Answers (2)

mattgmg1990
mattgmg1990

Reputation: 5876

I just ran your code in a test project on my phone and it seems to work perfectly when loading the first page. It loaded wap.bild.de without any problems for the first time.

I did, however, experience the same problem that the default browser is launched when I tap on a link. To fix that, just add the following lines:

mWebview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url); // open link in the same web view.
            return true;
        }
    });

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1007276

You are not really doing anything "wrong". Link clicks and redirects, by default, bring up the user's chosen Web browser instead of keeping them within your WebView.

To counteract this, you will need to add a WebViewClient implementation to your WebView, via setWebViewClient(). Your WebViewClient subclass will need to override shouldOverrideUrlLoading() to handle whichever URLs you want to keep in the WebView:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
  if (/* url is one you want to keep in the WebView */) {
    view.loadUrl(url);

    return(true);
  }

  return(false);
}

Upvotes: 2

Related Questions