Previously I wrote a post How to use OkHttp for loading resources in WebView.
Now, I definitely can say that it was bad idea. And it's not an
NotOk: loading WebView resources via OkHttp was bad idea (not OkHttp's fault). Flucking WebView :(— Artem Zinnatullin (@artem_zin) October 27, 2015
- If you can avoid
WebView— avoid it.
shouldInterceptRequest()synchronously in a single IO thread, so resources will be loaded synchronously one after another. Though,
OkHttpis fast enough (SPDY, HTTP/2) that it may give better results on a good connection in compare to native loading of the resources via
- Looks like
shouldInterceptRequest(). Also looks like native resources loading in the
WebViewsomehow integrated into
JScan do its work "in parallel" to native resources loading.
Unfortunately, most of integrated
WebViews on Android < 5 and
Android System WebView from Google Play affected with these problems.
But I still want to load resources myself!
If you still want to manually load resources of pages that you're displaying you can do it.
Suggested algorithm (suitable for email clients btw):
- Load resources in background before
WebVieweven displayed (for example if email app receives a new message in background, it can start pre-fetching images from the message even before user opens the app, of course with respect to connection quality and battery level).
shouldInterceptRequest()and return result from pre-fetched cache if it exists, otherwise you can either return
falseand leave loading of the resource to the
WebViewor synchronously load it manually, but as mentioned before —
WebViewmay stuck on a bad connection.
Another approach if you can't pre-fetch resources is to override
shouldInterceptRequest(), immediately return some fake result and start async load of the requested resource, then when the resource will be downloaded you can trigger it's reload via
If you need relatively fast
WebView with support for "new" web features and your app supports Android versions that can not use
Android System WebView from the Google Play — take a look at Crosswalk project.
Crosswalk is a
WebView based on relatively fresh versions of
Chromium which you can include into your apk statically or dynamically as a shared library.