• Stars
    star
    1,910
  • Rank 24,271 (Top 0.5 %)
  • Language
    Java
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Custom implement Android WebView cache, offline website, let cahe config more simple and flexible

CacheWebView

English

CacheWebView通过拦截资源实现自定义缓存静态资源。突破WebView缓存空间限制,让缓存更简单。让网站离线也能正常访问。

为什么要用CacheWebView

  • 让WebView缓存空间更大
  • 强制缓存静态资源,这样会更快
  • 想方便的拿到web缓存资源,比如说从缓存中拿页面已经加载过的图片

使用方式

引入库

注意2.x.x 不兼容 1.x.x

implementation 'ren.yale.android:cachewebviewlib:2.2.1'

修改代码

Application 里初始化


    WebViewCacheInterceptorInst.getInstance().
                init(new WebViewCacheInterceptor.Builder(this));

给WebView添加拦截

  • 如果你的项目minSdkVersion>=21
    mWebView.setWebViewClient(new WebViewClient(){

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return  WebViewCacheInterceptorInst.getInstance().interceptRequest(request);
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return  WebViewCacheInterceptorInst.getInstance().interceptRequest(url);
            }
     });

  • 如果你的项目minSdkVersion<21

将调用 mWebView.loadUrl(url) 的地方替换为:WebViewCacheInterceptorInst.getInstance().loadUrl(mWebView,url)


    mWebView.setWebViewClient(new WebViewClient(){


            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                WebViewCacheInterceptorInst.getInstance().loadUrl(mWebView,request.getUrl().toString());
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebViewCacheInterceptorInst.getInstance().loadUrl(mWebView,url);
                return true;
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return  WebViewCacheInterceptorInst.getInstance().interceptRequest(request);
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return  WebViewCacheInterceptorInst.getInstance().interceptRequest(url);
            }
    });

以上就配置完毕,其他代码不用改,这样拥有默认100M缓存空间;如果你需要更详细的配置,可以看看下面的进阶设置;


  • 腾讯X5内核WebView兼容处理
     mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {
                return WebResourceResponseAdapter.adapter(WebViewCacheInterceptorInst.getInstance().
                        interceptRequest(s));
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {

                return WebResourceResponseAdapter.adapter(WebViewCacheInterceptorInst.getInstance().
                        interceptRequest(WebResourceRequestAdapter.adapter(webResourceRequest)));
            }
        });

下面是兼容代码,可以参考:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class WebResourceRequestAdapter implements android.webkit.WebResourceRequest {

    private com.tencent.smtt.export.external.interfaces.WebResourceRequest mWebResourceRequest;

    private WebResourceRequestAdapter(com.tencent.smtt.export.external.interfaces.WebResourceRequest x5Request){
        mWebResourceRequest = x5Request;
    }

    public static WebResourceRequestAdapter adapter(com.tencent.smtt.export.external.interfaces.WebResourceRequest x5Request){
        return new WebResourceRequestAdapter(x5Request);
    }

    @Override
    public Uri getUrl() {
        return mWebResourceRequest.getUrl();
    }

    @Override
    public boolean isForMainFrame() {
        return mWebResourceRequest.isForMainFrame();
    }

    @Override
    public boolean isRedirect() {
        return mWebResourceRequest.isRedirect();
    }

    @Override
    public boolean hasGesture() {
        return mWebResourceRequest.hasGesture();
    }

    @Override
    public String getMethod() {
        return mWebResourceRequest.getMethod();
    }

    @Override
    public Map<String, String> getRequestHeaders() {
        return mWebResourceRequest.getRequestHeaders();
    }
}

public class WebResourceResponseAdapter extends com.tencent.smtt.export.external.interfaces.WebResourceResponse {

    private android.webkit.WebResourceResponse mWebResourceResponse;

    private WebResourceResponseAdapter(android.webkit.WebResourceResponse webResourceResponse){
        mWebResourceResponse = webResourceResponse;
    }

    public static WebResourceResponseAdapter adapter(android.webkit.WebResourceResponse webResourceResponse){
        if (webResourceResponse == null){
            return null;
        }
        return new WebResourceResponseAdapter(webResourceResponse);

    }

    @Override
    public String getMimeType() {
        return mWebResourceResponse.getMimeType();
    }

    @Override
    public InputStream getData() {
        return mWebResourceResponse.getData();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public int getStatusCode() {
        return mWebResourceResponse.getStatusCode();
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public Map<String, String> getResponseHeaders() {
        return mWebResourceResponse.getResponseHeaders();
    }

    @Override
    public String getEncoding() {
        return mWebResourceResponse.getEncoding();
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public String getReasonPhrase() {
        return mWebResourceResponse.getReasonPhrase();
    }
}


如果你的项目minSdkVersion<21, 在 mWebView.loadUrl(url) 之后调用 WebViewCacheInterceptorInst.getInstance().loadUrl(url,mWebView.getSettings().getUserAgentString());


进阶设置

  • 基本设置
   WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);

    builder.setCachePath(new File(this.getCacheDir(),"cache_path_name"))//设置缓存路径,默认getCacheDir,名称CacheWebViewCache
                       .setDynamicCachePath(new File(this.getCacheDir(),"dynamic_webview_cache"))
                       .setCacheSize(1024*1024*100)//设置缓存大小,默认100M
                       .setConnectTimeoutSecond(20)//设置http请求链接超时,默认20秒
                       .setReadTimeoutSecond(20)//设置http请求链接读取超时,默认20秒
                       .setCacheType(CacheType.NORMAL);//设置缓存为正常模式,默认模式为强制缓存静态资源

    WebViewCacheInterceptorInst.getInstance().init(builder);
  • 设置缓存后缀

CacheWebview通过后缀判断来缓存静态文件,可以添加删除

    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);

    CacheExtensionConfig extension = new CacheExtensionConfig();
    extension.addExtension("json").removeExtension("swf");//添加删除缓存后缀

    builder.setCacheExtensionConfig(extension);

    WebViewCacheInterceptorInst.getInstance().init(builder);

默认有以下后缀缓存

    private static HashSet STATIC = new HashSet() {
        {
            add("html");
            add("htm");
            add("js");
            add("ico");
            add("css");
            add("png");
            add("jpg");
            add("jpeg");
            add("gif");
            add("bmp");
            add("ttf");
            add("woff");
            add("woff2");
            add("otf");
            add("eot");
            add("svg");
            add("xml");
            add("swf");
            add("txt");
            add("text");
            add("conf");
            add("webp");
        }
    };

默认有以下后缀不缓存

    private static HashSet NO_CACH = new HashSet() {
        {
            add("mp4");
            add("mp3");
            add("ogg");
            add("avi");
            add("wmv");
            add("flv");
            add("rmvb");
            add("3gp");
        }
    };
  • 设置Assets路径

CacheWebview可以从Assets路径加载静态资源,只要设置了Assets路径就是开启此功能,默认未开启;


  
    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);
    //默认精确匹配地址规则
    builder.setAssetsDir("static");
    
    //后缀匹配规则
    //builder.isAssetsSuffixMod(true);
    //WebViewCacheInterceptorInst.getInstance().initAssetsData(); //后台线程获取Assets文件资源
    
    WebViewCacheInterceptorInst.getInstance().init(builder);

builder.setAssetsDir("static")后匹配规则:

assets 结构如下:

(1)默认精确匹配规则:那么只有满足这种结构的url:http://xxx.com/scripts/jquery.min.js 都会从assets获取资源

(2)后缀匹配规则:那么只要满足这种结构的url:http://xxx.com/x/xx/scripts/jquery.min.js 都会从assets获取资源

  • 自定义拦截规则
    builder.setResourceInterceptor(new ResourceInterceptor() {
            @Override
            public boolean interceptor(String url) {
                return true;//按照默认规则,false 不拦截资源
            }
        });
  • 获取缓存文件

    String url = "http://m.mm131.com/css/at.js";
    InputStream inputStream =  WebViewCacheInterceptorInst.getInstance().getCacheFile(url);
    if (inputStream!=null){

    }

  • 清除缓存文件
    WebViewCacheInterceptorInst.getInstance().clearCache();
  • 强制缓存失效

    强制缓存失效后,由WebView正常加载资源

    WebViewCacheInterceptorInst.getInstance().enableForce(false);
  • HostnameVerifier设置

builder.setTrustAllHostname();不安全

    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);
    builder.setTrustAllHostname();//HostnameVerifier不验证,HostnameVerifier.verify()返回true,默认正常验证
    WebViewCacheInterceptorInst.getInstance().init(builder);

  • SSLSocketFactory 设置
    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);
    builder.setSSLSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager);//自定义SSLSocketFactory和X509TrustManager
    WebViewCacheInterceptorInst.getInstance().init(builder);

  • Debug log

默认开启debug log , TAG="CacheWebView",可以关闭log

    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);
    builder.setDebug(false);
    WebViewCacheInterceptorInst.getInstance().init(builder);

  • 非单例模式

调用方法和单例一样

    WebViewCacheInterceptor.Builder builder =  new WebViewCacheInterceptor.Builder(this);
    WebViewRequestInterceptor webViewRequestInterceptor = builder.build();
    webViewRequestInterceptor.getCacheFile("");

混淆

#CacheWebview
-dontwarn ren.yale.android.cachewebviewlib.**
-keep class ren.yale.android.cachewebviewlib.**{*;}

#okhttp
-dontwarn okhttp3.**
-keep class okhttp3.**{*;}

#okio
-dontwarn okio.**
-keep class okio.**{*;}

贡献

如何贡献代码

博客

如何让Android WebView访问更快

More Repositories

1

RetrofitCache

RetrofitCache让retrofit2+okhttp3+rxjava配置缓存如此简单。通过注解配置,可以针对每一个接口灵活配置缓存策略;同时让每一个接口方便支持数据模拟,可以代码减小侵入性,模拟数据可以从内存,Assets,url轻松获取。
Java
673
star
2

EasyIncrementalUpdate

Android差分补丁库,通过native层合并APK,实现增量更新升级,让你更新的APK更小。
C
238
star
3

Summer

Vertx router with JAX-RS
Java
64
star
4

quickapp-wechat

快应用实现的微信Demo
JavaScript
47
star
5

EasyJSBridge

让JS在Android/iOS WebView中反调接口统一,调用更容易
JavaScript
42
star
6

gorpool

Simple Goroutine pool
Go
35
star
7

stream

Golang stream lib is like Java 8 stream. Only handle slice or array.
Go
9
star
8

deploy

通过SSH连接,简单的配置文件,可以配置私钥,可以配置socks5,让部署更简单
Go
7
star
9

JavaAutoDeployClient

java auto deploy
Java
6
star
10

weixin-service

Golang微信,小程序后台接口
Go
5
star
11

gosocket

Simple Golang server socket long connection skeleton
Go
5
star
12

gank-uni-app

gank-uni-app 通过uni-app框架,调用gank.io接口写的干货集中营Demo,通过HBuilderX将项目打包为APP,包括iOS、Android、H5、微信小程序,支付宝小程序,百度小程序、头条小程序
CSS
5
star
13

VideoUtil

给视频添加关键帧工具
Go
4
star
14

doris-stream-loader

Apache Doris Stream Loader Golang API
Go
4
star
15

url-to-pdf-api-docker

url-to-pdf-api docker build
HTML
3
star
16

gffmpeg

golang ffmpeg wrapper
Go
3
star
17

ScrollViewSlipping

android ScrollViewSlipping
Java
3
star
18

nw-windows-easy-package

node-webkit windows easy package
HTML
2
star
19

PopList

Android poplist
Java
2
star
20

caddy-build

caddy build with some plugins
2
star
21

Roadmap

Go
1
star
22

Words

Words is for sentence util kit.
Java
1
star
23

go-commons

go-commons
Go
1
star
24

timer-message

Simple windows timer to show message box.
Go
1
star
25

vue-installer

vue component installer from github
JavaScript
1
star
26

xlsx2db

load xlsx file to db
Go
1
star
27

goutils

Go
1
star
28

ImageDeskew

ImageDeskew
Python
1
star
29

Axis1WebServiceClient

Axis1 WebService 客户端 例子,通过wsdl文件生成客户端代码并调用
Java
1
star
30

Axis1WebService

Axis1 WebService 例子,通过wsdl文件生成服务器端代码并部署
Java
1
star
31

deployx

Node deploy cli utils
JavaScript
1
star
32

wkvideoplayer

Java
1
star
33

ratelimiter

ratelimiter is wrapper token-bucket and count-limit by golang
Go
1
star
34

DataUpdater

Golang remote data update with timer lib. You can update config auto.
Go
1
star
35

vue-admin-frame

Simple vue admin frame demo, use vue2.0, element-ui
Vue
1
star