Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling WebView links works on emulator but no on device

I wish to disable links of a page I am loading to my WebView object. My code works perfectly on my emulator with api 25, but not on my phone with 23 api.

This is the code that blocks the links of my WebView:

public class NoLinksWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        return true;
    }
}

I am setting my WebViewClient to be an object of type NoLinksWebViewClient. It does the trick on the emulator but not on my real phone.

How to solve this?

like image 626
Tal Angel Avatar asked Mar 06 '17 16:03

Tal Angel


2 Answers

The short answer is you need to override both the methods which given below.The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24.

 @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
       return true;
    }

Hope these help you.

like image 28
Jitesh Mohite Avatar answered Sep 22 '22 07:09

Jitesh Mohite


My code works perfectly on my emulator with api 25, but not on my phone with 23 api.

I think the crucial difference is not emulator vs device but different API levels. If you look at the documentation on WebViewClient you'll notice that there are two similar but different methods:

// since API 24
boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
// before API 24, now deprecated
boolean shouldOverrideUrlLoading(WebView view, String url)

As you have overridden only the newer method, on your older device default logic works. This happens because obviously API 23 device couldn't know that in API 24 the method will be replaced with a different one, so it still calls the old (now deprecated) method.

I believe that to fix the issue you just should override both these methods.

like image 73
SergGr Avatar answered Sep 19 '22 07:09

SergGr