[WebView learning 4]: migrate to the WebView of Android4.4

Source: Internet
Author: User

[WebView learning 4]: migrate to the WebView of Android4.4

 

 

Android4.4 (API version 19) provides a new version of WebView Based on Chromium. This change improves the performance of WebView and supports the latest HTML5, CSS3 styles, and Javascript standards with the latest Web browsers. When running in Android4.4 or a later version, any application that uses WebView will inherit to use these features. This article describes the new features of WebView. If you set targetSdkVersion to 19 or higher, you need to pay special attention.

[Note]: When you set targetSdkVersion to 18 or lower, WebView runs quirks mode to avoid the following problems (when optimization improves App performance and updates Web standards ). In particular, single and narrow column layouts (single row fence layout) and defalut zoom levels (default scaling ratio) are not supported in Android4.4, and there may be other uncertain differences. Therefore, if you set targetSdkVersion to 18 or earlier, you must test the application in Android4.4 or later versions.

You can set setWebContentsDebuggingEnabled () to perform remote debugging on Chrome desktop. In this way, when we migrate the app to Android4.4 WebView, some problems can be solved. The new WebView feature helps us check and analyze Web content, scripts, and network activities. For more debugging information, see the next article remote debugging for Android.

 

(1): UseerAgent Changes)

If your WebView content is based on the user agent, you should find that the content of the user code has changed slightly. The current version already contains the Chrome version:

Mozilla/5.0 (Linux; Android 4.4; Nexus 4 Build/KRT16H) AppleWebKit/537.36
(KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36

If you need to retrieve and query the user proxy, but do not need to store or do not want to instantiate WebView, you should use the static method, getdefauseruseragent (). However, if you need to modify the WebView user proxy, you should use the getUserAgentString () method.

 

(2) Multi-Thread and Thread Blocking)

If you call WebView methods in other threads instead of App UI threads, unexpected errors may occur. If your App uses multithreading, you can use the runOnUiThread () method to determine whether your code is executed in the UI thread.

 

runOnUiThread(new Runnable() {    @Override    public void run() {        // Code for WebView goes here    }});

 

At the same time, we should ensure that we never block the UI thread. Sometimes, when we are waiting for javascript callback, this error may occur in some apps. For example, do not write the following code.

// This code is BAD and will block the UI threadwebView.loadUrl(javascript:fn());while(result == null) {  Thread.sleep(100);}

You can use evaluateJavascript () to run Javascript asynchronously.

 

(3) Custom URL Processing (Custom URL Handing)

When we request resources and process custom URL structure links, the new WebView also provides additional restrictions. For example, if we implement the shouldOverrideUrlLoading () and shouldInterceptRequest () callback methods, we can ensure that WebView only calls back valid URLs. If you are using a custom URL structure or based on a URL, sometimes loading data in Android4.4 fails. Make sure that the URL complies with the RFC 3986 encoding.

For example, in the following example, the new version of WebView may not call the shouldOverrideUrlLoading () method. The following links may vary with user clicks:

1. If you call loadData () or loadDataWithBaseURL () by using an invalid or empty URL, the link type on the page may not callback the shouldOverrideUrlLoading () method.

[Note]: If you use loadDataWithBaseURL (), where the base URL is invalid or empty, all link addresses must be absolute addresses.

2. If you call loadDataBaseURL () to load the page by calling loadUrl () or providing a valid base URL. In this case, the shouldOverrideUrlLoading () method is called back for the page address, but the absolute address is returned. For example, you can obtain http://www.example.com/showprofile, but not showprofile.

In addition to the link address type used above, you can also use the following custom URL:

Show Profile

You can process this URL in the shouldOverrideUrlLoading () method:

// The URL scheme should be non-hierarchical (no trailing slashes)private static final String APP_SCHEME = example-app:;@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {    if (url.startsWith(APP_SCHEME)) {        urlData = URLDecoder.decode(url.substring(APP_SCHEME.length()), UTF-8);        respondToData(urlData);        return true;    }    return false;}

If you cannot change the HTML, you can call loadDataWithBaseURL () and set a base URL. The custom type and a valid host name are used for composition. For example:

Example-app :// . For example:

 

webView.loadDataWithBaseURL(example-app://example.co.uk/, HTML_DATA,        null, UTF-8, null);

 

The host name must comply with RFC3986 specifications and end with a slash. Otherwise, any page loading request will be terminated unexpectedly.

 

(4) ViewPortChanges)

1. view form target screen density is not supported (Viewprot target-desitydpi no longersupported)

Previously, WebView supports specifying the target-desitydpi attribute to set the screen density for webpages. This attribute is no longer supported. Now you should solve the problem by using image resources and CSS styles.

2. when the screen is small, the view form is automatically scaled (Viewport zoomsin when small)

If your viewport width is less than or equal to 320, it is set to device-width. If the viewport height is less than or equal to the WebView height. this will be set to device-height. Now, when we run a new WebView, the width and height of the WebView are automatically scaled to fill the whole screen.

3. multi-view form labels are not supported (Multiple vieport tags not supported)

In the past, if multiple viewport labels were contained on a Web page, WebView merges these attribute labels. In the new WebView, only the last viewport label is used, and others are ignored.

4. Default zoom is deprecated)

The getDefaultZoom () and setdefazoom zoom () Methods on the interface are not supported to set and obtain the page zoom ratio. You should define the appropriate viewport on the Web page.

[Note]: In Android4.4 or later versions, these APIs will not be supported. If you set targetSdkVersion to 18 or lower, it will not work.

For details about how to define the viewport attribute of HTML, see Pixel-PerfectUI in the WebView.

If you cannot set the width of the HTML view form, you should call setUserWideViewPort () to ensure that the page can be properly displayed. For example:

WebSettings settings = webView.getSettings();settings.setUseWideViewPort(true);settings.setLoadWithOverviewMode(true);

 

5) Styling Changes)

1. The backgroundCSS shorthand overrides background-size

2. Use pixels in the CSS style instead of the screen pixel size (Sizes are in CSS pixels instead ofscreen pixels)

For example, for window. outerWidth and window. outerHeighet, the returned width and height attribute is the screen pixel size value. In the new WebView, the returned value is the pixel value defined in the CSS style.

Generally, a bad design is to try and calculate the physical size. However, if you set the original zoom value to 1.0 and disable zoom, you can use window. devicePixelRatio to get the zoom ratio and multiply it by the pixel size defined by CSS. On the contrary, you can bind javascript to obtain the WebView size.

 

(6) narrow columns and single columns not supported (NARROW_COLUMNS and SINGLE_COLUMN nolonger supported)

In the new WebView, The NARROW_COLUMNS value of WebSettings. LayoutAlgorithm will no longer be supported.

[Note]: In Android4.4 or later versions, these APIs will not be supported. If you set targetSdkVersion to 18 or lower, it will not work.

You can handle this change in the following ways:

1. Alter the styles of your application)

If you control the compilation of HTML and CSS style files on the page, changing the design content may be the most effective method. For example:

   
 

This setting is particularly useful if you have not defined the viewport attribute for your page.

2. Use the new Text Auto-resize Layout Algorithm: (Using the new TEXT_AUTOSIZING layoutalgorithm)

If you use narrow columns to make a desktop webpage more readable on mobile devices and cannot change HTML content, the TEXT_AUTOSIZING algorithm method may be more suitable than the narrow columns method.

In addition, the discarded SINGLE_COLUMNS is not supported in the new version of WebView.

 

(7) Handing touch Events in Javascript)

If your webpage processes touch events directly in WebView and is sure to process the touchcancel event as well. However, some touchcance calls may have some problems in some scenarios.

1. When the control element is touched (touchstart and touchmove are called) or the page is rolled, touchcancel may throw an exception.

2. When the control element is touched (touchstart is called) But event. preventDefault () is not called, touchcancel may throw an exception (WebView may think you do not want to use the touch event ).

 

A series of knowledge points in the subsequent articles will encapsulate a WebView component, which is more convenient to use. Please wait...


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.