Prevent Android WebView caching data

后端 未结 2 628
南方客
南方客 2020-12-24 04:28

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:

相关标签:
2条回答
  • 2020-12-24 04:55

    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!

    0 讨论(0)
  • 2020-12-24 05:02

    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

    0 讨论(0)
提交回复
热议问题