---
title: "【so easy~】 Webview离线功能（优先cache缓存+cache缓存管理）！"
author: "libo19881179"
date: "2011-11-28T17:05:16Z"
tags: ["WebView", "cache缓存", "加载本地", "离线图片"]
categories: ["移动开发"]
slug: "so-easy-webview-cache-cache"
draft: false
lastmod: "2012-03-15T14:24:51Z"
id: 1280946
url: "https://androiddada.iteye.com/blog/1280946"
---

在做Webview显示服务器的html功能时 需要加入离线功能。

[http://androiddada.iteye.com/](http://androiddada.iteye.com/)

开始思路很狭隘，以为一定应该是从服务器得到的html文件，下载到本地后加载~

但是这样不能离线查看图片，因为图片数据并不再html中，只是连接地址。

后来，经过上网各种搜寻学习，发现原来Webview有自己的缓存，如图：

 

![](http://dl.iteye.com/upload/attachment/596668/38e4e8a2-662c-3ed4-bd65-160db21b8c97.jpg)  
 在手机本地 data/data/包名/cache/webviewCache 中放的是Webview显示过的图片。我们可以把它导出，后缀改成对应图片的格式 打开看看~

 

而databases中的webviewCache.db 中放的就是图片地址和图片名字对应等信息 的表~ 导出后也可用SQLite Database Browser 等工具查看

 

1.优先缓存 

好了，这里你是不是想问：既然这些图片已经存在手机缓存里面了，为什么Webview不能再把它显示出来呢？

这里我们需要设置下：

 

 

WebSettings webSettings= webView.getSettings();

webSettings.setCacheMode(WebSettings.LOAD\_CACHE\_ELSE\_NETWORK);

//WebView.getSettings().setCacheMode(WebSettings.LOAD\_NO\_CACHE); 默认不使用缓存！

 

LOAD\_CACHE\_ELSE\_NETWORK的意思是:

 

Use cache if content is there, even if expired (eg, history nav) If it is not in the cache, load from network. Use with `setCacheMode(int)`.

如果内容已经存在cache 则使用cache，即使是过去的历史记录。如果cache中不存在，从网络中获取！

 

所以加上这句，不仅可以使用cache离线显示用户浏览过的内容，还可以在有网络的情况下优先调用缓存，为用户减少流量！~

 

我有些费解的是，这个设置在我看来是很有利于用户体验的 为什么google不把它设置成默认的呢？ 还需要开发者手动打开。猜想可能是因为相同页面可能会更新的原因！

 

如果离线加载出现乱码 可参考： [http://androidturing.iteye.com/blog/1280656](/blog/1280656)

 

[http://androiddada.iteye.com/](http://androiddada.iteye.com/)

2.缓存管理：

（1）clearCacheFolder（Activity.getCacheDir（）， System.currentTimeMillis（））；//删除此时之前的缓存.

 

 

```
// clear the cache before time numDays  
private int clearCacheFolder（File dir， long numDays） {   
int deletedFiles = 0；   
if （dir！= null && dir.isDirectory（）） {   
try {   
for （File child：dir.listFiles（）） {   
if （child.isDirectory（）） {   
deletedFiles += clearCacheFolder（child， numDays）；  
}  
  
if （child.lastModified（） < numDays） {   
if （child.delete（）） {   
deletedFiles++；  
}  
}  
}  
} catch（Exception e） {   
e.printStackTrace（）；  
}  
}  
return deletedFiles；   
}  
```

 

（2） 退出应用前删除缓存的方法！

 

 

```
File file = CacheManager.getCacheFileBaseDir（）；  
　　if （file ！= null && file.exists（） && file.isDirectory（）） { for （File item ： file.listFiles（）） { item.delete（）；  
　　}  
　　file.delete（）；  
　　}  
　　context.deleteDatabase（"webview.db"）；  
　　context.deleteDatabase（"webviewCache.db"）；  
```