Krystian Krystian - 4 months ago 125
Android Question

How to handle shouldInterceptRequest parameter change in API21?

In API21 Google modified shouldInterceptRequest method to use

WebResourceRequest request
instead of
String url
.
Is there any way I could write a generic class extending
WebViewClient
and handle both methods?
My minimum API version is 18.

Thanks
Krystian

Answer

Google modified shouldInterceptRequest method to use WebResourceRequest request instead of String url

No, they added a second shouldInterceptRequest() method. Both are available in API Level 21+; the String variant is available on API Level 11+. While the String one is marked as deprecated, the String variant should be supported for quite some time, for backwards compatibility.

Is there any way I could write a generic class extending WebViewClient and handle both methods?

The built-in implementation of the WebResourceRequest version of shouldInterceptRequest() simply calls the String implementation of shouldInterceptRequest():

public WebResourceResponse shouldInterceptRequest(WebView view,
        WebResourceRequest request) {
    return shouldInterceptRequest(view, request.getUrl().toString());
}

(from the source code as of right now)

So, you have two choices:

  1. Just override the String edition, if you do not need the WebResourceRequest, and it will be used on all relevant API levels.

  2. Override both, knowing that the WebResourceRequest one will be used on API Level 21+ and the String edition will be used on API Levels 11-20.