目前項(xiàng)目中涉及到對(duì)公用的js,css,部分html代碼進(jìn)行本地保存,供服務(wù)端的h5頁(yè)面進(jìn)行調(diào)用(目的節(jié)省流量)
實(shí)現(xiàn)流程為:
- 對(duì)當(dāng)前資源文件進(jìn)行zip打包,然后從服務(wù)器端下載,下載完成后進(jìn)行解壓保存在應(yīng)用目錄下面
- 然后在WebView中對(duì)相關(guān)的資源進(jìn)行攔截,防止去加載服務(wù)端的資源,如果本地中沒有相關(guān)資源,就會(huì)默認(rèn)去加載服務(wù)端的資源。同時(shí)可以開啟線程將資源保存到本地。
解壓從網(wǎng)絡(luò)獲取的資源文件
public static void unzipFile(String zipName,String savePath) throws IOException{
ZipFile zipFile = new ZipFile(zipName);
Enumeration entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry zipEntry = (ZipEntry)entries.nextElement();
String filePath = savePath.endsWith(File.separator)?savePath+zipEntry.getName():savePath+File.separator+zipEntry.getName();
if(zipEntry.isDirectory()){
System.out.println(filePath);
(new File(filePath)).mkdirs();
}else{
System.out.println(filePath);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
byte buff[] = new byte[1024];
int length = -1;
while((length = bis.read(buff))!= -1){
bos.write(buff, 0, length);
bos.flush();
}
bos.close();
}
}
zipFile.close();
}
稍微提一下:
- zip文件在解壓的時(shí)候,如果zip文件中只有一個(gè)文件,那么在解壓的時(shí)候,直接會(huì)得到zip文件里面包裹的文件
patch.zip(css.css)只會(huì)得到css.css文件 - 如果zip文件里面有若干個(gè)文件(2個(gè)或者2個(gè)以上的文件),這個(gè)時(shí)候解壓的時(shí)候會(huì)有產(chǎn)生zip文件夾。
patch.zip(css.css css2.css)會(huì)得到patch文件夾和css.csscss2.css文件,這在后面測(cè)試數(shù)據(jù)的時(shí)候還是值得注意的。
在WebViewClient的shouldInterceptRequest中進(jìn)行攔截
示例代碼如下:
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
WebResourceResponse response = null;
if (url.endsWith("css.css")) {
try {
InputStream localCopy = new FileInputStream(getFilesDir()+"/css.css");///data/data/packagename/files/css.css
response = new WebResourceResponse("text/css", "UTF-8", localCopy);
} catch (IOException e) {
e.printStackTrace();
}
}
//如果response為空,會(huì)重新從服務(wù)器加載資源
return response;
}
網(wǎng)頁(yè)資源示例代碼:
<link href="css.css" rel="stylesheet">
經(jīng)過(guò)此步驟,你會(huì)發(fā)現(xiàn)如果攔截成功,會(huì)直接從本地獲取css文件,攔截失敗才會(huì)從服務(wù)端加載資源。