我有一个具有以下配置的 WebView :
getSettings().setJavaScriptEnabled(true);
getSettings().setSupportMultipleWindows(false);
getSettings().setNeedInitialFocus(false);
getSettings().setSupportZoom(false);
getSettings().setAllowFileAccess(true);
getSettings().setAppCacheEnabled(true);
getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
String cachePath = getContext().getCacheDir().getAbsolutePath();
getSettings().setAppCachePath(cachePath);
我将一个 html 页面加载到其中,然后加载一些 Assets :一些静态图像、几个 js 文件、一个 css 和一个字体。
这些 Assets 与缓存控制 header 一起返回:
HTTP/1.1 200 OK
Date: Wed, 01 Jan 2014 18:40:36 GMT
Last-Modified: Mon, 30 Dec 2013 09:23:55 GMT
Cache-Control: public, max-age=604800
我重新加载了 url,我可以在 fiddler 中看到所有 Assets 都缓存在本地,没有任何内容被重新加载。
但是,如果我关闭应用程序并再次打开它 - 所有内容都会重新下载。
如何确保 Assets (js\css\images) 缓存在设备上,而不是每次都从我的服务器中检索?
最佳答案
事实证明这段代码运行良好。
问题是我在另一个 webview 上调用了 clearCache
,结果是:
the cache is per-application, so this will clear the cache for all WebViews used.
一旦我从另一个 webview 中删除了对 clearCache
的调用,一切都运行良好。
关于应用关闭后 Android WebView 缓存丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20872052/