简体   繁体   中英

How to make Android WebView clear cache?

Here is my scenario. I am using WebView to show my mobile-ready website inside an app. We regularly update our website and automatically clear our website cache, so visitors get the latest version of our website instead of stale versions. I've noticed that sometimes WebView is serving old content -- it sometimes doesn't load newer versions of our website. Hence, I'm looking for a way to force WebView to show new content.

I know I could totally disable WebView cache and force it to grab the page from our server every time, but that is inefficient. I want the cache used when the cached page is the latest version; if it isn't, then the cache should not be used.

The only way I can think of doing this is by manually clearing the cache, something like this:

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

But, again, this is inefficient -- there is no need to clear the whole cache after each page view. My question is, is there any way to clear just cached HTML files and leave CSS / JS / etc.? This would be a nice compromise between always clearing the cache and sometime serving stale content. By removing just the cached HTML files after each page view, WebView is forced to grab the latest HTML pages from my server, without having to reload CSS or JS.

Better yet, to save wasting unnecessary processing power, is there a way to remove from cache only the specific page the user is on? Eg After loading google.com, the cached HTML page for google.com (but not the CSS, JS, etc.) is removed so that the next time google.com is loaded, the latest version is grabbed.

Thanks!

Add a parameter to your js/css file link in the html code, that can be a datetime or version string, just like:

<link rel='stylesheet' href='style/jquery.mobile-1.3.2.min.css?ver=1.3.2'>
<script src="js/jquery-1.8.3.min.js?ver=1.8.3"></script>
<script src="js/jquery.mobile-1.3.2.min.js?ver=1.3.2"></script>
<script src="js/my_script.js?ver=201603111428"></script>

When your script or style sheet file updtated, just change to a new parameter value, then the webview will treat it as a new url and make a reload.

mWebView.getSettings().setAppCacheEnabled(false);
mWebView.clearCache(true);
mWebView.loadUrl("about:blank");
mWebView.reload();
mWebView.loadUrl("http:xxxxxxx");

I was looking for solutions too, but the only works for me was this commands.

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