轉:Android Webview 載入外部html時選擇載入本地的js,css等資源檔

來源:互聯網
上載者:User

標籤:

原文地址: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;            }}

轉:Android Webview 載入外部html時選擇載入本地的js,css等資源檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.