When using WebView to load a web page, there are some fixed resource files such as js's jquery package, css, pictures and other resources that will be relatively large. If they are loaded directly from the network, the page will load slower and will Consumes more traffic. So these files should be placed 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 11 (HONEYCOMB) to load local resources. In API 21, this method was deprecated and a new shouldInterceptRequest was overloaded. The required parameters replaced url with request.
For example, if there is an image icon.png, which has been placed in assets, and now an external HTML is loaded, the image in assets needs to be directly taken out and loaded without re-obtaining it from the network. Of course, you can change the image link in html to file:///android_asset/icon.png, but then this html cannot be shared in android, ios, and WAP.
Implementation code:
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; }}