当加载一个h5页面时,对于页面中需要加载每一个资源文件,比如css,js,img等等,包括该页面本身,系统都会调用WebViewClient的方法shouldInterceptRequest进行拦截,这样我们就可以在该方法中进行分析所拦截到的资源url, 根据url找到sd卡上对应的离线应用包里的资源文件,如果没有找到,则使shouldInterceptRequest方法返回null,这样webview就会从网上加载资源;如果找到了sd卡上对应的缓存资源,则创建对应的WebResourceResponse对象并返回,这样webview就加载了sd卡上缓存资源。具体代码如下
/**
* 根据类型获得 WebResourceResponse
*
* @param path uri
* @param resourceFile 资源文件位置
* @return 该资源的WebResourceResponse
*/
public static WebResourceResponse getResponseByType(String path, File resourceFile, boolean encrypted, String aesKey) {
WebResourceResponse response = null;
InputStream localCopy = null;
try {
localCopy = new FileInputStream(resourceFile);
byte[] data = HFIOUtils.readAllBytesAndClose(localCopy);
if (encrypted) {
String decodeString = AESCoder.decryptBytes(data, aesKey);
data = decodeString.getBytes("UTF-8");
}
if (path.endsWith(".css")) {
response = new WebResourceResponse("text/css", "UTF-8", new ByteArrayInputStream(data));
} else if (path.endsWith(".js")) {
response = new WebResourceResponse("text/javascript", "UTF-8", new ByteArrayInputStream(data));
} else {
response = new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream(data));
}
Logger.i(TAG, "使用文件缓存:" + path);
}
catch (Throwable e)
{
Logger.e(TAG, "getResponseByType : 文件:" + path + "读取失败 : error = " + e);
}
finally {
HFIOUtils.safeClose(localCopy);
}
return response;
}
算法如以下显示
@@a59c0a93d8aa773086db55be5106a49c2f7d73fe71660a88518fe58d9447e7b257d14e97a328b1c85faac27d10a27c60@@