Android WebView 缓存
android很多情况是使用webView用来显示界面,但是webview的加载速度略慢,想让这个webview更快一些所以需要使用缓存,在没有更新的时候使用缓存技术来提高速度。总体来讲有两个方案可以实现这个内容。1.用本地文件js,css,png替换网络请求下来的文件,2.直接使用webview的缓存。
第一种方法用本地文件js,css,png替换网络请求下来的文件是在webview的setWebViewClient里面的shouldInterceptRequest方法用本地文件进行替换。
mWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView webView, String s) { super.onPageFinished(webView, s); mWebView.getSettings().setBlockNetworkImage(false); //加载完成时调用 } //新加载WebView的方法 @Override public boolean shouldOverrideUrlLoading(final WebView webView, final String url) { Log.e("sys","url="+url); //判断url if (!(url.startsWith("http") || url.startsWith("https"))) { return true; } /** * 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次 */ final PayTask task = new PayTask(BaseWebActivity.this); boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() { @Override public void onPayResult(final H5PayResultModel result) { final String url=result.getReturnUrl(); Log.e("sys","url="+ url); switch (result.getResultCode()) { /* 9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错 */ case "4000": webView.loadUrl("javascript:appCallJsShowOrder()"); Log.e("sys","4000"); break; case "6001": webView.loadUrl("javascript:appCallJsShowOrder()"); Log.e("sys","6001"); break; case "6002": webView.loadUrl("javascript:appCallJsShowOrder()"); Log.e("sys","6002"); break; case "9000": break; } } } }); /** * 判断是否成功拦截 * 若成功拦截,则无需继续加载该URL;否则继续加载 */ if(!isIntercepted) { Log.e("is","update"); webView.loadUrl(url); } return true; } //获得下载列表 @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { WebResourceResponse response = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ response = super.shouldInterceptRequest(view,url); if (url.contains(".js")||url.contains(".png")||url.contains(".css")){ Log.e("fileUrl",url); String[] arr = StrUtil.getStrArr(url,"/"); String jsFileName = arr[arr.length-1]; String[] arrEnd = StrUtil.getStrArr(jsFileName,"\\."); if (arr.length!=0){ if(arrEnd.length != 0) { Log.e("arr",jsFileName); if(jsFileName.equals("fastclick.min.js")){ Log.e("fastclick","fastclick"); try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("fastclick.min.js")); } catch (IOException e) { e.printStackTrace(); } } if(jsFileName.equals("geolocation.min.js")){ Log.e("geolocation","geolocation"); try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("geolocation.min.js")); } catch (IOException e) { e.printStackTrace(); } } if(jsFileName.equals("g2.min.js")){ try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("g2.min.js")); } catch (IOException e) { e.printStackTrace(); } } if(jsFileName.equals("login_bg.5563a40.png")){ try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("login_bg.5563a40.png")); } catch (IOException e) { e.printStackTrace(); } } if(jsFileName.equals("favicon-16x16.png")){ try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("favicon-16x16.png")); } catch (IOException e) { e.printStackTrace(); } } if(jsFileName.equals("favicon-32x32.png")){ try { return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("favicon-32x32.png")); } catch (IOException e) { e.printStackTrace(); } } } } } return response; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { WebResourceResponse response = null; response = super.shouldInterceptRequest(view, request); return response; } @Override public void onReceivedError(final WebView webView, int i, String s, String s1) { super.onReceivedError(webView, i, s, s1); } @Override public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) { super.onReceivedError(webView, webResourceRequest, webResourceError); Log.e("sys","onReceivedError webResourceError"); } });
2.首先设置webSetting设置成使用LOAD_DEFAULT这种缓存方式,数据从缓存中获取还是从网络中获取根据H5页面的参数判断,这样做的好处是可以动态的处理更新内容。再判断版本是否清理缓存。
//设置webview属性 private void initWebViewSettings() { WebSettings webSetting = webView.getSettings(); webSetting.setJavaScriptEnabled(true); webSetting.setJavaScriptCanOpenWindowsAutomatically(true); webSetting.setAllowFileAccess(true); webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); webSetting.setSupportZoom(true); webSetting.setBuiltInZoomControls(true); webSetting.setUseWideViewPort(true); webSetting.setSupportMultipleWindows(true); // webSetting.setLoadWithOverviewMode(true); webSetting.setAppCacheEnabled(true); // webSetting.setDatabaseEnabled(true); webSetting.setDomStorageEnabled(true); webSetting.setGeolocationEnabled(true); webSetting.setDatabaseEnabled(true); webSetting.setAppCacheMaxSize(Long.MAX_VALUE); webSetting.setTextZoom(100); webSetting.setBlockNetworkImage(true); // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY); webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND); webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH); webSetting.setCacheMode(WebSettings.LOAD_DEFAULT); String userAgent = webSetting.getUserAgentString().replace("Mobile","Snail"); webSetting.setUserAgentString(userAgent); // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension // settings 的设计 } @Override protected void onDestroy() { // TODO Auto-generated method stub if (this.mWebView != null) { try { //在这里获得版本号 清除缓存 if(version!=lastVersion){ mWebView.clearCache(true); context.deleteDatabase("webview.db");//删除数据库缓存 context.deleteDatabase("webviewCache.db"); } } catch (Exception e) { } mWebView.destroy(); } }