简体   繁体   中英

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?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM