1. Optimization for speeding up the loading of resources in webView (mainly for pictures)

** Cause: ** After the HTML code is downloaded to the WebView, WebKit starts to parse each node of the web page. When it finds an external style file or external script file, it will asynchronously send a network request to download the file. However, if the image node is also parsed before this, it will also send a network request to download the corresponding image. In the case of poor network conditions, too many network requests will cause bandwidth strain, which affects the loading time of CSS or JS files and causes blank loading of pages for too long.

** Solution: ** tell the WebView not to automatically load images until the page finishes.

// Set when initializing, In the WebView class, if(build.version.sdk_int >= KITKAT) {// set the page to be loaded temporarily without images webView.getSettings().setLoadsImagesAutomatically(true); } else { webView.getSettings().setLoadsImagesAutomatically(false); } @override public void onPageFinished(WebView view, @param url, @param url) String url) { super.onPageFinished(view, url); If (! webView.getSettings().getLoadsImagesAutomatically()) { webView.getSettings().setLoadsImagesAutomatically(true); }}Copy the code

2.WebView hardware acceleration causes page rendering flicker

** Reason: After hardware acceleration is enabled for **4.0 + systems, WebView renders pages more quickly and drags more smoothly. As a side effect, when the WebView is completely covered and then suddenly restored (such as when SlideMenu slides the WebView out of the side), the transition will be white and the screen will flicker.

** Solution: ** Is to temporarily close WebView hardware acceleration before the transition period, and then open after the transition period.

// Disable hardware acceleration if (build.version.sdk_int >= build.version_codes.honeycomb) {webview.setlayerType (view.layer_type_software, null); } // Enable hardware acceleration if (build.version.sdk_int >= build.version_codes.honeycomb) {webview.setlayerType (view.layer_type_hardware, null); }Copy the code

3. The loading progress bar is displayed in advance

* * reason: ** webView.loadURL (” URL “) does not immediately call onPageStarted or onProgressChanged because during this time, the WebView may be initializing the kernel or establishing a connection to the server, This period is prone to blank screen, blank screen user experience is very bad.

** Showing the progress bar ahead of time is not a performance boost, but it is an important part of the user experience.

/ / pb right. SetVisibility (the VISIBLE); mWebView.loadUrl("https://github.com/"); @override public void onPageStarted(WebView WebView, String s, Bitmap Bitmap) {super.onPagestarted (WebView, s, Bitmap) bitmap); Pb.setvisibility (view.visible); } / / this is to monitor the progress bar. The logic of change mWebView getWebChromeClient () setWebListener (interWebListener); mWebView.getWebViewClient().setWebListener(interWebListener); private InterWebListener interWebListener = new InterWebListener() { @Override public void hindProgressBar() { pb.setVisibility(View.GONE); } @Override public void showErrorView() { } @Override public void startProgress(int newProgress) { pb.setProgress(newProgress); } @Override public void showTitle(String title) { } };Copy the code

4.WebView password plaintext storage vulnerability optimization

* * reason: **WebView enables the password saving function by default. Mwebview.setsavepassword (true). If this function is not disabled, a prompt box will pop up when the user enters the password, asking the user whether to save the password. Password will be definitely confirmed to/data/data/com. The package. The name/databases/webview. Db, so it is in danger of being stolen password.

Solution: * * * * through the WebSettings. SetSavePassword (false) to close the password reminder function.

SetSavePassword (false); webView.setSavepassWord (false);Copy the code

5. Customize the status page for loading the error exception. For example, error may occur in the following methods

** Android WebView displays an error screen by default when the WebView loads a page incorrectly (404 NOT FOUND). When a WebView load error occurs, the onReceivedError() in the WebViewClient instance and the onReceivedTitle method receive the error.

** Custom error page styles.

Error * @param view view * @param errorCode Error * @param description description * @param failingUrl failed link */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); If (errorCode == 404) {// Hide system-defined 404 Page information with javascript String data = "Page NO FOUND!" ; view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\""); } else { if (webListener! =null){ webListener.showErrorView(); }}} // Reports Web resource loading errors to the host application. These errors usually indicate an inability to connect to the server. // It is worth noting that the difference is the outdated version of the callback, the new version will be called any resource (iframe, image, etc.) // not just for the home page. Therefore, it is recommended to perform minimal work during callbacks. @Override public void onReceivedError(WebView view, WebResourceRequest Request, WebResourceError error) { super.onReceivedError(view, request, error); If (build.version.sdk_int >= build.version_codes.m) {x5webutils.log (" server exception "+error.getDescription().tostring ()); } // toastutils.showtoast (" after server exception 6.0 "); / / when the load error, let it load the local error page file / / mWebView loadUrl (" file:///android_asset/errorpage/error.html "); if (webListener! =null){ webListener.showErrorView(); @override public void onReceivedTitle(WebView view, WebView); String title) { super.onReceivedTitle(view, title); If (the title. The contains (" 404 ") | | the title. The contains (" unable to open the ")) {if (webListener! =null){ webListener.showErrorView(); }} else {// set title}}Copy the code

6. The WebView fails to load the certificate

** Cause: **webView load some other url, sometimes a certificate error occurs.

** To render the normal page to the user, we need to ignore the certificate error by calling the onReceivedSslError method of the WebViewClient class and calling handler.proceed() to ignore the certificate error.

/** * Notifies the host application of an SSL error while loading a resource * @param view view * @param handler Handler * @param error Error */ @override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); if (error! =null){ String url = error.getUrl(); } // HTTPS ignores the certificate problem if (handler! // proceed(); // handler.cancel(); // Handler. HandleMessage (null); // Can do other processing}}Copy the code

7.WebView audio playback still has sound after destruction

** Cause: ** Audio is playing in the WebView page, and the audio is still playing after exiting the Activity.

** Need to remove the WebView from the parent container in the Activity’s onDestory().

@override protected void onDestroy() {try {// If the Webview music or video is still playing when the Activity is turned off. You must destroy the Webview. When a webView calls deStory, the WebView is still attached to the Activity. This is because the Activity context was passed in when the custom WebView was built. if (webView ! = null) { ViewGroup parent = (ViewGroup) webView.getParent(); if (parent ! = null) { parent.removeView(webView); } webView.removeAllViews(); webView.destroy(); webView = null; } } catch (Exception e) { } super.onDestroy(); }Copy the code

8. How do I set whitelist operations

** Reason: ** WebViews in the client can be opened by a schema of the client, and the URL to open the page is not written in the client, but can be passed by the PARAMETERS in the URL. The risks of using Scheme have been illustrated in 4.0.5 above.

** Solution: ** Set up a whitelist for running access, or give users a strong and obvious prompt before opening external links. Set up the whitelist operation and filtering advertising is actually the same meaning, here you can put some legal sites to allow access.

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    String host = Uri.parse(url).getHost();
    if (!BuildConfig.IS_DEBUG) {
        if (Arrays.binarySearch(domainList, host) < 0) {
            //不在白名单内,非法网址,这个时候给用户强烈而明显的提示
        } else {
            //合法网址
        }
    }
}
Copy the code

9.Android background fails to release JS, resulting in heat and power consumption

Reason: On some phones, if you load HTML with webView, some JS is executing things like animation, if the webView is hanging in the background at the moment, these resources will not be released and the user will not be aware of them. The resulting constant CPU consumption is extremely fast.

While WebView is in the background, the onStop method will be used to close the JS interaction, and the onResume method will be used to open the JS interaction.

// Set setJavaScriptEnabled(true) in onResume. @Override protected void onResume() { super.onResume(); if (mWebView ! = null) { mWebView.getSettings().setJavaScriptEnabled(true); }} // Inside onStop set setJavaScriptEnabled(false); @Override protected void onStop() { super.onStop(); if (mWebView ! = null) { mWebView.getSettings().setJavaScriptEnabled(false) } }Copy the code

10.WebView does not display images when loading a web page

**WebView does not allow mixed mode by default since Lollipop(5.0). HTTP resources cannot be loaded in HTTPS, and the development may use HTTPS links, but the images in the links may be HTTP, so the display of images fails.

** Solution: ** needs to be set on.

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
mWebView.getSettings().setBlockNetworkImage(false);
Copy the code