Android Webview 加载外部html时选择加载本地的js,css等资源文件_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:50:01
Original
1107 people have browsed it

在使用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;            }}
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!