Webview離線功能(優先cache緩存+cache緩存管理)


在做Webview顯示服務器的html功能時 需要加入離線功能。

開始思路很狹隘,以為一定應該是從服務器得到的html文件,下載到本地后加載~

但是這樣不能離線查看圖片,因為圖片數據並不再html中,只是連接地址。

后來,經過上網各種搜尋學習,發現原來Webview有自己的緩存,如圖:

在手機本地 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://blog.csdn.net/lamyuqingcsdn/article/details/44893071


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");   







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM