Rafael
Rafael

Reputation: 11

Load offline updated pages on Webview

I'm running my app that has webview on different activities, they are loading online pages, the issue is that everytime the activity opens the webview takes a couple of seconds to load the page and the page is not available offline.

I was looking for a solution where the webview would always be accessing an offline copy of the website, and the app would download and replace the local website every 24 hours.

I thought it would be simple Thanks

Upvotes: 1

Views: 1402

Answers (1)

anthonycr
anthonycr

Reputation: 4186

I see a couple potential solutions to this problem.

Change WebView Cache Mode

The first and simplest would be to change the cache mode of the WebView so that it is forced to load from the cache. This way it will try to load from the cache, and if any resources are not cached, then it will do a network load. This can be simply accomplished by using:

WebView webView; // initialized somewhere
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

Theoretically, you could use LOAD_CACHE_ONLY if the WebView has already loaded once and it doesn't need updating, otherwise you could use LOAD_DEFAULT. Using the LOAD_CACHE_ELSE_NETWORK should definitely speed up loading time, but it might still load some stuff from the network.

However, in practice, I have seen the cache settings not work as consistently as I would like them to.

Utilize WebView.saveWebArchive()

Another more robust solution would be to use the web archive capability that the WebView has. I have not used this solution myself, but you can read about it in this question.

Basically, you can save the contents of the WebView using the following:

WebView webView; // initialized somewhere
webView.loadUrl("http://blahblahblah.com"); // URL to save
Context context = this;
String pathFilename = context.getFilesDir().getPath() + File.separator + "savedWebPage.mht"; // You can use any path you want
webView.saveWebArchive(pathFilename);

Then you can load the saved archive file by using:

webView.loadUrl("file://" + pathFilename);

Please note that I am leaving out the logic for handling when to load from the website and when to load from the archive file, that's up to you how to handle it.

Upvotes: 1

Related Questions