Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Android WebView caching data

Is it possible to prevent a WebView from caching data in /data/data/???/cache/webViewCache? I've set the following on the WebSettings but the cache folder is still used:

webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);

I've noticed that the cache files are deleted on application exit or when the application goes into the background but I'd prefer for them not to be created at all. Furthermore I'd like to prevent the use of the webview.db & webviewCache.db found in /data/data/???/database. I currently delete the databases like so:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");

This appears to have the desired effect and the files don't appear to be recreated again for use. Is it safe to assume this is the case?

like image 528
dbotha Avatar asked Sep 24 '11 07:09

dbotha


2 Answers

The notes on this page lead me to believe they don't want you to have fine access to the cache:

http://developer.android.com/reference/android/webkit/CacheManager.html

As far as I can tell, there are (at least) two ways around keeping cache. I haven't written any of this in an app, so no guarantees:

(1) Every time your WebView finishes a page, clear the cache. Something like this in your WebViewClient:

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    view.clearCache(true);
}

(2) If you don't care too much what is stored, but just want the latest content, you might be able to achieve this by setting the right http headers on loadUrl (obviously you'd want to test this against your server). Also, this is only available for Android API 8+

    Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
    noCacheHeaders.put("Pragma", "no-cache");
    noCacheHeaders.put("Cache-Control", "no-cache");
    view.loadUrl(url, noCacheHeaders);

Maybe you tried this, but maybe also set the WebView Cache size to something small. I'm not sure if 0 will work, so maybe 1:

wv.getSettings().setAppCacheMaxSize(1);

Good Luck!

like image 96
Matt Avatar answered Oct 15 '22 08:10

Matt


In my application (on Android 4.2.2) I load on a webview a web page with images that I can change at runtime (I replace the images while keeping the path). The Matt's solution (1)

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    view.clearCache(true);
}

works for me, the solution (2) no! Cheers

like image 29
DSoldo Avatar answered Oct 15 '22 07:10

DSoldo