Android WebView development issues and optimization summary

Source: Internet
Author: User

Transferred from: http://www.pedant.cn/2014/09/10/webview-optimize-points/

In the process of combining native and webpage, we will inevitably encounter some common problems about webview. The problems I have encountered in the development process and the final optimization plan are listed here. Some are cliché, and others are a way of finding solutions. Here are some of the dry goods that have been sorted out.

1. Speed up the completion of HTML page loading

By default, when the HTML code is downloaded to WebView, WebKit begins to parse each node of the Web page, discovers an external style file or an external script file, asynchronously initiates a network request download file, but if there is a resolution to the image node before that, it is bound to initiate a network request to download the corresponding image. In the case of poor network conditions, excessive network requests will cause bandwidth tension, affecting the CSS or JS file load completed time, resulting in blank loading page too long. The solution is to tell WebView not to automatically load the picture, and so on after the page finishes and then launches the picture loading.

Therefore, the following code is set when WebView is initialized:

public void Int () {    if (Build.VERSION.SDK_INT >=) {        webview.getsettings (). setloadsimagesautomatically ( true);    } else {        webview.getsettings (). setloadsimagesautomatically (false);}    }

  

Add the following code to the Onpagefinished () method in the Webviewclient instance of WebView:

@Overridepublic void onpagefinished (WebView view, String URL) {    if (!webview.getsettings (). Getloadsimagesautomatically ()) {        webview.getsettings (). Setloadsimagesautomatically (True);}    }

  

From the above code, we can see that the system API in more than 19 version is compatible. Because more than 4.4 of the system in the onpagefinished when the image is loaded, if there are multiple images referenced by the same SRC, there will be only one image tag to get loaded, so for such a system we will first load directly.

2. Custom Error interface

When WebView load page error (generally 404 Not FOUND), Android WebView will default to display an error screen selling. But how can we let users find that I am using the Web application, we expect that the user on the Web page is like a native application experience, then the first to kill this default error page start. When the WebView loading error occurs, we receive an error in the Onreceivederror () method in the Webviewclient instance, and we do this here:

@Overridepublic void Onreceivederror (WebView view, int errorCode, string description, String failingurl) {    Super.onr Eceivederror (view, ErrorCode, description, failingurl);    Loaddatawithbaseurl (NULL, "", "text/html", "Utf-8", null);    Merrorframe.setvisibility (view.visible);}

  

As can be seen from the above, we first use Loaddatawithbaseurl to clear out the default error page content, and then let our custom view be displayed (merrorframe is a linearlayout layout above the WebView, Default is View.gone).

3. Is there a scroll bar

When we do something like pull-up to load the next page, the page initially needs to know whether the current WebView has a vertical scroll bar, if any, the next page is not loaded, and if not, load the next page until it appears with a vertical scroll bar. First inherit the WebView class and add the following code to the subclass:

public Boolean Existverticalscrollbar () {    return Computeverticalscrollrange () > Computeverticalscrollextent () ;}

  

The computeverticalscrollrange gets the maximum sliding height, and the computeverticalscrollextent gets the height of the scroll handle itself, and the values are equal when there is no scroll bar. When there is a scrollbar, the former must be greater than the latter.

4. Have you scrolled to the bottom of the page

We also need to know the state of the current page scroll bar when we do the pull-up load on the next page, and if it is fast to the bottom, we will initiate a Web request data Update webpage. Likewise inherit the WebView class, overriding the Onscrollchanged method in subclasses, as follows:

@Overrideprotected void onscrollchanged (int newx, int newy, int oldx, int oldY) {    super.onscrollchanged (newx, Newy, OL DX, OldY);    if (newy! = OldY) {        float contentheight = getcontentheight () * Getscale ();        The current content level has never been triggered, the browser has scroll bars and slides to the bottom position        if (mcurrcontentheight! = contentheight && newy > 0 && Content Height <= Newy + getheight () + mthreshold) {            //TODO Something ...            Mcurrcontentheight = Contentheight;}}    }

  

The above mcurrcontentheight is used to record the height of the Web page when it was last triggered, to prevent multiple triggers when the total height of the Web page does not change and the target area is continuously scrolled when the todo,mthreshold is a threshold value, when the bottom of the page Todo is triggered when the height difference from the bottom of the scrollbar <= this value.

5. Remote Web pages need access to local resources

When we load content from a Web server in WebView, we cannot access local resources, such as picture resources under the assets directory, because such behavior is cross-domain (Cross-domain) and WebView is forbidden. The solution to this problem is to download the HTML content to local and then load the HTML using Loaddatawithbaseurl. This allows you to use file:///android_asset/xxx.png links in HTML to refer to the resources under assets in the package. Examples are as follows:

private void Loadwithaccesslocal (final String htmlurl) {new Thread (new Runnable () {public void run () {                try {final String htmlstr = netservice.fetchhtml (Htmlurl);                         if (htmlstr! = null) {Taskexecutor.runtaskonuithread (new Runnable () {@Override public void Run () {Loaddatawithbaseurl (Htmlurl, Htmlstr, "text/html",                        "UTF-8", "" ");                    }                    });                Return            }} catch (Exception e) {log.e ("Exception:" + e.getmessage ());                    } taskexecutor.runtaskonuithread (New Runnable () {@Override public void run () {                Onpageloadederror ( -1, "Fetch HTML failed");        }            }); }}). Start ();}


Loaddatawithbaseurl is WebView's own method, Netservice is the network request tool, used to initiate HTTP requests to get HTML content, and Taskexecutor is a thread management tool class, Used to execute runnable in UI or worker threads

  

Here are a few things to note:

    • The process of downloading HTML from the network should be placed in a worker thread
    • The process of rendering HTML after the HTML download succeeds should be placed in the main UI thread, or WebView will error
    • HTML download Failure You can use the method we described earlier to display the custom error interface

      The complete demo Project code I have put to: Http://yunpan.cn/cgQPvJQxxkCBj (extract code: 6712).
6.ViewPager non-first screen WebView Click event Not responding

If you have multiple webview that are loaded in Viewpager, you will encounter this problem. Viewpager first screen WebView is created in the foreground, no problem when clicked, while the other non-first screen webview is created in the background, swipe to it after clicking on the page will appear the following error log:

20955-20968/xx.xxx.xxx E/webcoregl

  

The solution to this problem is to inherit the WebView class, overriding the Ontouchevent method in the subclass, filling in the following code:

@Overridepublic boolean ontouchevent (motionevent ev) {    if (ev.getaction () = = Motionevent.action_down) {        Onscrollchanged (Getscrollx (), getscrolly (), Getscrollx (), getscrolly ());    }    return super.ontouchevent (EV);}

  

The method was first proposed in the WebView in Viewpager not receive user inputs.

7.WebView hardware acceleration causes page rendering Flicker

More than 4.0 of the system when we turn on hardware acceleration, WebView renders the page faster, and the drag is smoother. However, a side effect is that when the WebView view is obscured by a block, and then suddenly recovers (for example, by using Slidemenu to slide the webview from the side), the transition period is white and the interface flashes. The solution to this problem is to temporarily close the hardware acceleration of the webview before the transition period, and then open it after the transition period, with the following code:

if (Build.VERSION.SDK_INT >= build.version_codes. Honeycomb) {    webview.setlayertype (view.layer_type_software, null);}

  

8. Avoid security problems caused by addjavascriptinterface

Using the open source project, safe Java-js WebView Bridge, can be a good alternative to the addjavascriptinterface approach, with support for asynchronous callbacks, and no security risk.

9.WebView touchmove event conflict with Upper parent element

You may encounter such a situation during the development process. The end uses Viewpager to nest multiple webview pages, while the page elements in one webview need to respond to touchmove events. For detailed solutions, please visit: http://www.pedant.cn/2014/09/23/webview-touch-conflict

Android WebView development issues and optimization summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.