webView本身自带了缓存机制。
具体缓存机制是什么,请看
Android WebView缓存机制详解
了解后知道webView的缓存(图片,URL等)都是在data目录下的,大家都明白手机内部存储是有限的,这时就需要进行缓存清除。
/**
* 清除WebView缓存
*/
public void clearWebViewCache(){
//清理Webview缓存数据库
try {
deleteDatabase("webview.db");
deleteDatabase("webviewCache.db");
} catch (Exception e) {
e.printStackTrace();
}
//WebView 缓存文件
File appCacheDir = new File(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);
File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");
//删除webview 缓存目录
if(webviewCacheDir.exists()){
deleteFile(webviewCacheDir);
}
//删除webview 缓存 缓存目录
if(appCacheDir.exists()){
deleteFile(appCacheDir);
}
}
/**
* 递归删除 文件/文件夹
*
* @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();
} else {
}
}
再者,如果想要改webView的缓存机制,将webView的缓存存储到sd卡上怎么办呢?
查看文档我们会发现有个public abstract File getCacheDir();抽象方法。很显然只需要重写getCacheDir()就行了。
public File getCacheDir() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File externalStorageDir = Environment.getExternalStorageDirectory();
if (externalStorageDir != null){
// SD卡上的位置
extStorageAppBasePath = new File(externalStorageDir.getAbsolutePath() +
File.separator +"Android" + File.separator + "data"+File.separator + getPackageName());
}
if (extStorageAppBasePath != null){
extStorageAppCachePath = new File(extStorageAppBasePath.getAbsolutePath()+File.separator + "webViewCache");
boolean isCachePathAvailable = true;
if (!extStorageAppCachePath.exists()){
isCachePathAvailable = extStorageAppCachePath.mkdirs();
if (!isCachePathAvailable){
extStorageAppCachePath = null;
}
}
}
}
if (extStorageAppCachePath != null){
return extStorageAppCachePath;
}else{
return super.getCacheDir();
}
}
Android WebView优化参考
http://www.pedant.cn/2014/09/10/webview-optimize-points/