在使用WebView加载网页的时候,有一些固定的资源文件如js的jQuery包,css,图片等资源会比较大,如果直接从网络加载会导致页面加载的比较慢,而且会消耗比较多的流量。所以这些文件应该放在assets里面同app打包。
要解决这个问题需要用到API 11(HONEYCOMB)提供的shouldInterceptRequest(WebView view, String url) 函数来加载本地资源。在API 21又将这个方法弃用了,是重载一个新的shouldInterceptRequest,需要的参数中将url替换成了成了request。
比如有一个图片icon.png,这个图片已经放在了assets中,现在加载了一个外部html,就需要直接把assets里面的图片拿出来加载而不需要重新从网络获取。当然可以在html里面将图片链接换成file:///android_asset/icon.png,但是这样这个html就不能在Android ,iOS,WAP中公用了。
实现代码:
- webView.setWebViewClient(new WebViewClient() {
- @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(“icon.png”)){
- try {
- response = new WebResourceResponse(“image/png”,“UTF-8”,getAssets().open(“icon.png”));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // return super.shouldInterceptRequest(view, url);
- return response;
- }
- @TargetApi(Build.VERSION_CODES.LOLLIPOP)
- @Override
- public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
- WebResourceResponse response = null;
- response = super.shouldInterceptRequest(view, request);
- if (url.contains(“icon.png”)){
- try {
- response = new WebResourceResponse(“image/png”,“UTF-8”,getAssets().open(“icon.png”));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return response;
- }
- }
webView.setWebViewClient(new WebViewClient() {
@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("icon.png")){
try {
response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return super.shouldInterceptRequest(view, url);
return response;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse response = null;
response = super.shouldInterceptRequest(view, request);
if (url.contains("icon.png")){
try {
response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
}