Java – WebView cache background preloading

WebView cache background preloading… here is a solution to the problem.

WebView cache background preloading

I want to use a cache that preloads WebView with web pages from the internet. This needs to be done asynchronously and hidden so as not to interfere with other UI interactions. The purpose of preloading is to avoid subsequent network calls (and ultimately for faster display) when the WebView is rendered with an optional button click.

The web page contains Javascript and AJAX, so I don’t think preloading caching with something like HttpClient will work. I also looked at loadUrl() using WebView in AsyncTask, but I found that this conflicts with the main UI thread.

Is there a similar situation where friends find a way to implement background preloading/caching?

Solution

WebView loads data in a separate thread by default, so you don’t need to use AsyncTask. Just create a hidden WebView and call loadUrl().

If you want to preload multiple URLs, you can use WebViewClient and override onPageFinished() to detect when the first completed time. When you’re done using the WebView, be sure to remove references to it so that it can be garbage collected.

Finally, if you want to ensure that the visible WebView always uses the cached version of the URL when available, you can call:

webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK).

Related Problems and Solutions