当我们加载Html时候,会在我们data/应用package下生成database与cache两个文件夹:
我们请求的Url记录是保存在webviewCache.db里,而url的内容是保存在webviewCache文件夹下.
WebView中存在着两种缓存:网页数据缓存(存储打开过的页面及资源)、H5缓存(即AppCache)。
一、网页缓存
1、缓存构成
/data/data/package_name/cache/
/data/data/package_name/database/webview.db
/data/data/package_name/database/webviewCache.db
WebView缓存文件结构如下图所示
再看一下webviewCache 数据库结构
综合可以得知 webview 会将我们浏览过的网页url已经网页文件(css、图片、js等)保存到数据库表中
缓存模式(5种)
LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据
LOAD_DEFAULT: 根据cache-control决定是否从网络上取数据。
LOAD_CACHE_NORMAL: API level 17中已经废弃, 从API level 11开始作用同LOAD_DEFAULT模式
LOAD_NO_CACHE: 不使用缓存,只从网络获取数据.
LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据。
如:的cache-control为no-cache,在模式LOAD_DEFAULT下,无论如何都会从网络上取数据,如果没有网络,就会出现错误页面;在LOAD_CACHE_ELSE_NETWORK模式下,无论是否有网络,只要本地有缓存,都使用缓存。本地没有缓存时才从网络上获取。
的cache-control为max-age=60,在两种模式下都使用本地缓存数据。
总结:根据以上两种模式,建议缓存策略为,判断是否有网络,有的话,使用LOAD_DEFAULT,无网络时,使用LOAD_CACHE_ELSE_NETWORK。
设置WebView 缓存模式
[java]view plain copyprivatevoidinitWebView(){mWebView.getSettings().setJavaScriptEnabled(true);mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存模式//开启DOMstorageAPI功能mWebView.getSettings().setDomStorageEnabled(true);//开启databasestorageAPI功能mWebView.getSettings().setDatabaseEnabled(true);StringcacheDirPath=getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;//StringcacheDirPath=getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;Log.i(TAG,"cacheDirPath="+cacheDirPath);//设置数据库缓存路径mWebView.getSettings().setDatabasePath(cacheDirPath);//设置ApplicationCaches缓存目录mWebView.getSettings().setAppCachePath(cacheDirPath);//开启ApplicationCaches功能mWebView.getSettings().setAppCacheEnabled(true);}
清除缓存
[java]view plain copy/***清除WebView缓存*/publicvoidclearWebViewCache(){//清理Webview缓存数据库try{deleteDatabase("webview.db");deleteDatabase("webviewCache.db");}catch(Exceptione){e.printStackTrace();}//WebView缓存文件FileappCacheDir=newFile(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);Log.e(TAG,"appCacheDirpath="+appCacheDir.getAbsolutePath());FilewebviewCacheDir=newFile(getCacheDir().getAbsolutePath()+"/webviewCache");Log.e(TAG,"webviewCacheDirpath="+webviewCacheDir.getAbsolutePath());//删除webview缓存目录if(webviewCacheDir.exists()){deleteFile(webviewCacheDir);}//删除webview缓存缓存目录if(appCacheDir.exists()){deleteFile(appCacheDir);}}
完整代码
[java]view plain copypackagecom.example.webviewtest;importjava.io.File;importandroid.app.Activity;importandroid.graphics.Bitmap;importandroid.os.Bundle;importandroid.util.Log;importandroid.view.View;importandroid.webkit.JsPromptResult;importandroid.webkit.JsResult;importandroid.webkit.WebChromeClient;importandroid.webkit.WebSettings;importandroid.webkit.WebSettings.RenderPriority;importandroid.webkit.WebView;importandroid.webkit.WebViewClient;importandroid.widget.RelativeLayout;importandroid.widget.TextView;importandroid.widget.Toast;publicclassMainActivityextendsActivity{privatestaticfinalStringTAG=MainActivity.class.getSimpleName();privatestaticfinalStringAPP_CACAHE_DIRNAME="/webcache";privateTextViewtv_topbar_title;privateRelativeLayoutrl_loading;privateWebViewmWebView;privateStringurl;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//url:/detail/31ccb426119d3c9eaa794df686c58636121d38bc?apikey=jFaWGVHdFVhekZYWTBWV1ZHSkZOVlJWY&app=com.yulore.yellowsdk_ios&uid=355136051337627url="/detail/31ccb426119d3c9eaa794df686c58636121d38bc?apikey=jFaWGVHdFVhekZYWTBWV1ZHSkZOVlJWY&app=com.yulore.yellowsdk_ios&uid=355136051337627";findView();}privatevoidfindView(){tv_topbar_title=(TextView)findViewById(R.id.tv_topbar_title);rl_loading=(RelativeLayout)findViewById(R.id.rl_loading);mWebView=(WebView)findViewById(R.id.mWebView);initWebView();mWebView.setWebViewClient(newWebViewClient(){@OverridepublicvoidonLoadResource(WebViewview,Stringurl){Log.i(TAG,"onLoadResourceurl="+url);super.onLoadResource(view,url);}@OverridepublicbooleanshouldOverrideUrlLoading(WebViewwebview,Stringurl){Log.i(TAG,"intercepturl="+url);webview.loadUrl(url);returntrue;}@OverridepublicvoidonPageStarted(WebViewview,Stringurl,Bitmapfavicon){Log.e(TAG,"onPageStarted");rl_loading.setVisibility(View.VISIBLE);//显示加载界面}@OverridepublicvoidonPageFinished(WebViewview,Stringurl){Stringtitle=view.getTitle();Log.e(TAG,"onPageFinishedWebViewtitle="+title);tv_topbar_title.setText(title);tv_topbar_title.setVisibility(View.VISIBLE);rl_loading.setVisibility(View.GONE);//隐藏加载界面}@OverridepublicvoidonReceivedError(WebViewview,interrorCode,Stringdescription,StringfailingUrl){rl_loading.setVisibility(View.GONE);//隐藏加载界面Toast.makeText(getApplicationContext(),"",Toast.LENGTH_LONG).show();}});mWebView.setWebChromeClient(newWebChromeClient(){@OverridepublicbooleanonJsAlert(WebViewview,Stringurl,Stringmessage,JsResultresult){Log.e(TAG,"onJsAlert"+message);Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();result.confirm();returntrue;}@OverridepublicbooleanonJsConfirm(WebViewview,Stringurl,Stringmessage,JsResultresult){Log.e(TAG,"onJsConfirm"+message);returnsuper.onJsConfirm(view,url,message,result);}@OverridepublicbooleanonJsPrompt(WebViewview,Stringurl,Stringmessage,StringdefaultValue,JsPromptResultresult){Log.e(TAG,"onJsPrompt"+url);returnsuper.onJsPrompt(view,url,message,defaultValue,result);}});mWebView.loadUrl(url);}privatevoidinitWebView(){mWebView.getSettings().setJavaScriptEnabled(true);mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存模式//开启DOMstorageAPI功能mWebView.getSettings().setDomStorageEnabled(true);//开启databasestorageAPI功能mWebView.getSettings().setDatabaseEnabled(true);StringcacheDirPath=getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;//StringcacheDirPath=getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;Log.i(TAG,"cacheDirPath="+cacheDirPath);//设置数据库缓存路径mWebView.getSettings().setDatabasePath(cacheDirPath);//设置ApplicationCaches缓存目录mWebView.getSettings().setAppCachePath(cacheDirPath);//开启ApplicationCaches功能mWebView.getSettings().setAppCacheEnabled(true);}/***清除WebView缓存*/publicvoidclearWebViewCache(){//清理Webview缓存数据库try{deleteDatabase("webview.db");deleteDatabase("webviewCache.db");}catch(Exceptione){e.printStackTrace();}//WebView缓存文件FileappCacheDir=newFile(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);Log.e(TAG,"appCacheDirpath="+appCacheDir.getAbsolutePath());FilewebviewCacheDir=newFile(getCacheDir().getAbsolutePath()+"/webviewCache");Log.e(TAG,"webviewCacheDirpath="+webviewCacheDir.getAbsolutePath());//删除webview缓存目录if(webviewCacheDir.exists()){deleteFile(webviewCacheDir);}//删除webview缓存缓存目录if(appCacheDir.exists()){deleteFile(appCacheDir);}}/***递归删除文件/文件夹**@paramfile*/publicvoiddeleteFile(Filefile){Log.i(TAG,"deletefilepath="+file.getAbsolutePath());if(file.exists()){if(file.isFile()){file.delete();}elseif(file.isDirectory()){Filefiles[]=file.listFiles();for(inti=0;i<files.length;i++){deleteFile(files[i]);}}file.delete();}else{Log.e(TAG,"deletefilenoexists"+file.getAbsolutePath());}}}
简洁版代码:
[html]view plain copy System.out.println("getCacheDir:"+WebViewActivity.this.getCacheDir());System.out.println("PackageResourcePath():"+WebViewActivity.this.getPackageCodePath());System.out.println("getCacheDir:"+WebViewActivity.this.getPackageResourcePath());System.out.println("FilesDir:"+WebViewActivity.this.getDatabasePath("webview.db").getPath());System.out.println("FilesDir:"+WebViewActivity.this.getFilesDir().getPath())[html]view plain copy[html]view plain copy 03-3111:54:52.094:I/System.out(22224):getCacheDir:/data/data/com.liao.webview/cache03-3111:54:52.094:I/System.out(22224):PackageResourcePath():/data/app/com.liao.webview-1.apk03-3111:54:52.115:I/System.out(22224):getCacheDir:/data/app/com.liao.webview-1.apk03-3111:54:52.115:I/System.out(22224):FilesDir:/data/data/com.liao.webview/databases/webview.db03-3111:54:52.154:I/System.out(22224):FilesDir:/data/data/com.liao.webview/files03-3111:54:52.265:I/ActivityManager(59):Displayedactivitycom.liao.webview/.WebViewActivity:418ms(total418ms)[html]view plain copy[html]view plain copy //clearthecachebeforetimenumDaysprivateintclearCacheFolder(Filedir,longnumDays){intdeletedFiles=0;if(dir!=null&&dir.isDirectory()){try{for(Filechild:dir.listFiles()){if(child.isDirectory()){deletedFiles+=clearCacheFolder(child,numDays);}if(child.lastModified()<numDays){if(child.delete()){deletedFiles++;}}}}catch(Exceptione){e.printStackTrace();}}returndeletedFiles;}[html]view plain copy //优先使用缓存:WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);[html]view plain copy <p>//不使用缓存:WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);</p>[html]view plain copy[html]view plain copy 退出的时候加上下面代码[html]view plain copy Filefile=CacheManager.getCacheFileBaseDir();if(file!=null&&file.exists()&&file.isDirectory()){for(Fileitem:file.listFiles()){item.delete();}file.delete();}context.deleteDatabase("webview.db");context.deleteDatabase("webviewCache.db");
如果觉得《WebView Cache 缓存清除》对你有帮助,请点赞、收藏,并留下你的观点哦!