When using WebView to load Web pages, there are some fixed resource files such as JS jquery package, CSS, pictures and other resources will be relatively large, if directly from the network loading will cause the page to load relatively slow, and will consume more traffic. So these files should be in assets and packaged with the app.
To solve this problem, you need to use the Shouldinterceptrequest (WebView view, String URL) function provided by API one (honeycomb) to load the local resource. In API 21, this method is deprecated, is overloaded with a new shouldinterceptrequest, the required parameters to replace the URL into a request.
For example, there is a picture icon.png, this image has been placed in the assets, now loaded with an external HTML, you need to directly put the assets inside the picture to load without needing to get back from the network. Of course, you can change the image link in HTML to file:///android_asset/icon.png, but this HTML will not be in Android, Ios,wap public.
Implementation code:
Webview.setwebviewclient (New Webviewclient () {@Override public webresourceresponse shouldinterceptr Equest (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, Webresourcereque St request) { Webresourceresponse response = null; Response = Super.shouldinterceptrequest (view, request); if (Url.contains ("Icon.png")) {try {response = new Webresourceresponse ("image/p Ng "," UTF-8 ", Getassets (). Open (" Icon.png ")); } catch (IOException e) {e.printstacktrace (); }} return response; }}
Android Webview Load External HTML when choosing to load local js,css and other resource files