WebVeiw的缓存清理
webView的缓存有两种形式,页面内容缓存以及账号Cookie缓存,所以缓存清理分两种形式。情形一:例如某个app软件切换账号后发现用户界面显示的还是之前一个用户的数据,这时需要使用Cookie清理;另一种情形是,第一次加载网页时是一个样式,当前端修改网页的样式之后,如果不进行缓存清理,可能加载的还是第一次加载的样式,这时需要进行内容缓存清理。
-
一:Cookie缓存清理
- 在切换账号的时候,页面可能会保存上一个账号的信息,可以使用下面的方法进行缓存清理。
@SuppressWarnings("deprecation")
public static void clearCookies(Context context, WebView webView){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else{
CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
-
二:内容缓存清理
-
webview缓存的内容主要包括网页中的css渲染、图片和javascript
交互。
在webView的属性设置里面:
缓存模式(5种)
LOAD_DEFAULT: 默认的缓存使用模式。如果没有使用setCacheMode方法,当内存资源可用且不过期,则从内存中获取资源;否则从网络加载资源。使用{ @link # setCacheMode }。
LOAD_NO_CACHE: 不使用缓存,只从网络获取数据.
LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据
LOAD_CACHE_NORMAL: API level 17中已经废弃, 从API level 11开始作用同LOAD_DEFAULT模式
LOAD_CACHE_ELSE_NETWORK:当内存资源可用时,无论是否过期,都从内存中获取;否则从网络上获取。
总结:当设置cacheMode为LOAD_NO_CACHE时,该状态下不使用缓存,当cacheMode设置为其他状态时,从内存中读取资源。
属性设置如下:
public void setFeathue(){
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//cacheMode可以设置其他属性,除了LOAD_NO_CACHE之外
.
.
.
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAppCacheEnabled(true);
settings.setAppCachePath(WEB_APP_CACHE_PATH);
settings.setDatabasePath(WEB_DATA_CACHE_PATH);
}
清除缓存代码如下:
public void clearWebViewCache(){
//清理Webview缓存数据库
deleteDatabase("webview.db");
deleteDatabase("webviewCache.db");
File cacheFile = new File(getFilesDir().getAbsolutePath()+WEB_APP_CACHE_PATH);
File dataFile = new File(getCacheDir().getAbsolutePath()+WEB_DATA_CACHE_PATH);
if(cacheFile.exists()){
deleteFile(cacheFile);
}
if(dataFile.exists()){
deleteFile(dataFile);
}
}
/**
* 删除文件或文件夹
* @param file
*/
public void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
}
}
以上为webview清除缓存方法,若有不足之处欢迎指正,也欢迎大家给我留言,共同探讨问题。