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();
} }

  

Android WebView 缓存的更多相关文章

  1. Android WebView 缓存机制和模式详解

    当我们加载Html时候,会在我们data/应用package下生成database与cache两个文件夹: 我们请求的Url记录是保存在webviewCache.db里,而url的内容是保存在webv ...

  2. Android WebView缓存分析

    http://blog.csdn.net/a345017062/article/details/8703221   WebView的缓存可以分为页面缓存和数据缓存. 页面缓存是指加载一个网页时的htm ...

  3. Android webView 缓存 Cache + HTML5离线功能 解决

    时间 -- :: CSDN博客 原文 http://blog.csdn.net/moubenmao/article/details/9076917 主题 Android HTML5 WebView的缓 ...

  4. 【android】WebView缓存数据收集

    Android WebView 缓存 Android高手进阶教程(二十四)之---Android WebView的缓存!!! Android webView 缓存 Cache + HTML5离线功能 ...

  5. H5 和移动端 WebView 缓存机制解析与实战

    本文来自于腾讯Bugly公众号(weixinBugly),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/qHm_dJBhVbv0pJs8Crp77w 作者:叶 ...

  6. Android WebView 优化页面加载效果

    目前带有Web功能的APP越来越多,为了能够更好的使用WebView展示页面,可以考虑做相关的优化:WebView 缓存,资源文件本地存储,客户端UI优化. 可能有些人会说,为什么不做Native的, ...

  7. Android——WebView

    WebView用途 通过Intent调用系统浏览器: 引言: Uri uri = Uri.parse(url);//url为你要链接的地址 Intent intent = new Intent(Int ...

  8. Android webview通过http get下载文件下载两次的问题及解决方法

    一.现象 一般通过Android webview进行下载文件的方法是 1.重写DownloadListener的onDownloadStart方法,在onDownloadStart方法中弹出对话框提示 ...

  9. Android WebView 开发详解(一)

    转载请注明出处  http://blog.csdn.net/typename/article/details/39030091 powered by meichal zhao 概览: Android ...

随机推荐

  1. Python_NAT

    sockMiddle_server.py import sys import socket import threading #回复消息,原样返回 def replyMessage(conn): wh ...

  2. Windows 安装 Vue

    引言 在公司 linux 环境下安装不顺利,回家在 windows 下操作感觉到一种幸福 nginx 先安装了 nginx,其实跟 vue 没关系,只是打算用它做 web 服务,此处略过 nginx ...

  3. nexus私服搭建及maven生命周期

    一.maven找库流程 从流程上看创建nexus私服,能够优化流程,而且更加快速 二.nexus下载.安装 1.nexus下载地址 https://sonatype-download.global.s ...

  4. 在webpack里使用jquery.mCustomScrollbar插件

    malihu-custom-scrollbar-plugin是一个依赖jquery的自定义网页滚动条样式插件 网站:http://manos.malihu.gr/jquery-custom-conte ...

  5. awk高级玩法

    1. 程序元素 一个awk 程序是一对以模式(pattern) 与大括号框起来的操作(action) 组合而成的,或许,还会加上实现操作细节的函数(function ) .针对每个匹配于输人数据的模式 ...

  6. maven入门 (二)_私服安装与上传下载

    本篇文章主要介绍maven的私服安装和 jar包的上传与下载.毕竟大家还是在公司需要上传jar包到自己公司私服的. 1.安装私服 下载链接: https://pan.baidu.com/s/17dbQ ...

  7. VS2012中出现“无法启动程序...debug\abc.exe,系统找不到指定文件”的问题!

    VS 2005在生成可执行文件时使用了一种新的技术,该技术生成的可执行文件会伴随生成一个清单文件(manifest file)(.manifest后缀文件)(其本质上是XML文档,你可以用文本编辑器打 ...

  8. UnicodeEncodeError: 'ascii' codec can't encode character...的解决方法

    在python2.7下,因为想从数据库中读出来分类名进行写入到文件,提示 Traceback (most recent call last): File "test.py", li ...

  9. Python json & pickle, shelve 模块

    json 用于字符串和python的数据类型间的转换 四个功能 dumps dump loads load pickle 用于python特有的类型和python的数据类型进行转换 四个功能 dump ...

  10. 打开office时提示错误窗口“向程序发送命令时出现问题”的解决方案

    今天同事问了我一件很怪异的事情,说她的office打不开了,如打开word或excel时,突然出现错误提示错误窗口"向程序发送命令时出现问题",分析原因才知道她安装了 AVG pc ...