Android Webview H5 秒开方案实现,爆赞

本文介绍了如何实现Android WebView的H5秒开方案,通过重写`shouldInterceptRequest`方法,结合DataHelper工具类,将网络资源替换为本地缓存,减少网络请求。此外,探讨了WebView的缓存机制,包括Cache-Control、Expires、Last-Modified和Etag等字段的作用,以及如何利用缓存协议提高加载速度。
摘要由CSDN通过智能技术生成

}

@TargetApi(VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
String url = request.getUrl().toString();
if (mDataHelper.hasLocalResource(url)) {
WebResourceResponse response =
mDataHelper.getReplacedWebResourceResponse(getApplicationContext(),
url);
if (response != null) {
return response;
}
}
return super.shouldInterceptRequest(view, request);
}

});

DataHelper是一个工具类, 代码如下:

public class DataHelper {

private Map<String, String> mMap;

public DataHelper() {
mMap = new HashMap<>();
initData();
}

private void initData() {
String imageDir = “images/”;
String pngSuffix = “.png”;
mMap.put(“http://renyugang.io/wp-content/themes/twentyseventeen/style.css?ver=4.9.8”,
“css/style.css”);
mMap.put(“http://renyugang.io/wp-content/uploads/2018/06/cropped-ryg.png”,
imageDir + “cropped-ryg.png”);

}

public boolean hasLocalResource(String url) {
return mMap.containsKey(url);
}

public WebResourceResponse getReplacedWebResourceResponse(Context context, String url) {
String localResourcePath = mMap.get(url);
if (TextUtils.isEmpty(localResourcePath)) {
return null;
}
InputStream is = null;
try {
is = context.getApplicationContext().getAsse

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值