• 转:Android Webview 加载外部html时选择加载本地的js,css等资源文件


    原文地址:http://m.blog.csdn.net/blog/qduningning/43196819

    在使用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;
                }
    }
  • 相关阅读:
    Codeforces Round #649 (Div. 2) D. Ehab's Last Corollary
    Educational Codeforces Round 89 (Rated for Div. 2) E. Two Arrays
    Educational Codeforces Round 89 (Rated for Div. 2) D. Two Divisors
    Codeforces Round #647 (Div. 2) E. Johnny and Grandmaster
    Codeforces Round #647 (Div. 2) F. Johnny and Megan's Necklace
    Codeforces Round #648 (Div. 2) G. Secure Password
    Codeforces Round #646 (Div. 2) F. Rotating Substrings
    C++STL常见用法
    各类学习慕课(不定期更新
    高阶等差数列
  • 原文地址:https://www.cnblogs.com/Cavalry/p/4654880.html
Copyright © 2020-2023  润新知