Android Webview Loading Resources from Expired Cache
I am creating a hybrid application where the UI is on the server and I use webview in my application and only use native functionality where needed (where hardware access is required).
Sometimes my problem is that Webview is loading resources from the cache even when new resources (like javascript, etc.) are loaded onto the server. I don't run into this issue when I open the same URL at the same time from a browser on my computer. How can I make sure the webview will update its content from the server. This behavior is also not predictable as the webview updates its cache eventually, but after many page loads.
Clearing the cache on every startup or LOAD_NO_CACHE mode is not an option, as I want to use the cache functionality (but without risking loading old resources from the cache when new ones are available on the server).
Here is a code snippet. browser.loadURL (); called elsewhere in the application
browser = (WebView) findViewById(R.id.browser);
progress_bar = (ProgressBar) findViewById(R.id.progressBar1);
browser.getSettings().setSavePassword(false);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebChromeClient( .... )
browser.setWebViewClient( .... ) // omitted complete functions to save space
source to share
Something I did in the web app was to add a fake version flag to my JavaScript and CSS files in the script and link tags. So it looked something like this on the web page. This makes the browser think the resources are different and forces it to reload it.
<link href="./css/my_style.css?version=1.0" rel="stylesheet" type="text/css" />
<script src="./js/my_script.js?version=1.3" type="text/javascript"></script>
If you want to control this on the application side. In the SharedPreferences file you can add some sort of "expiration date". I am doing this for the image cache I have in some applications. Basically, you clear the cache when that date passes. It will look something like this.
String expireDateString = getSharedPreferences("WebviewExpireCache", Context.MODE_PRIVATE);
Date today = new Date();
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
if(today.after(format.parse(expireDateString ))){
browser.clearCache(true);
}
source to share