How to make Android WebView clear cache?

孤街醉人 提交于 2021-02-10 12:18:51

问题


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? E.g. 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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34572748/how-to-make-android-webview-clear-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!