Android Learning WebView Usage Summary

Source: Internet
Author: User
Tags ssl certificate

This period of time based on the project needs in the development and webview contact more, the previous time about the HTML5 specification dust settles the news appeared in the major IT community front page, more people say: HTML5 will subvert the native app development although I don't quite agree with this but about html5+js+ Css+native's cross-platform development model has also saved the development resources and cost for many enterprises, and improved the usage and status of webview to a certain extent.


An article on the internet about the finalization of the HTML5 specification:

Http://www.csdn.net/article/2014-11-06/2822513-how-html5-changes


This article is based on this period of time on the use of WebView experience and on-line learning to webview development to do a point summary:


First, WebView based on the WebKit engine to show the Web page of the control, before using the Android Manifest file to configure Internet access, otherwise the prompt page can not be accessed.

<manifest >    <uses-permission android:name= "Android.permission.INTERNET"/>    ... </ Manifest>


Second, the setting of the WebView property
1, set WebSettings class
WebSettings is used to configure and manage the WebView configuration, such as whether files can be manipulated, cached settings, whether the page supports zooming in and out, whether the database API is allowed, font and text encoding settings, whether the JS script is allowed to run, whether the picture is allowed to load automatically, Whether to allow data and password saving, etc.
The sample code is as follows:

WebSettings websettings = Mwebview.getsettings (); websettings.setjavascriptenabled (true); Websettings.setcachemode ( Websettings.load_default); Websettings.setdomstorageenabled (true);  Websettings.setdatabaseenabled (True); websettings.setappcacheenabled (true); Websettings.setallowfileaccess (True); Websettings.setsavepassword (true); Websettings.setsupportzoom (true); Websettings.setbuiltinzoomcontrols (true);  /**  * Display pictures with WebView, you can use this parameter to set the page layout type:  * 1, Layoutalgorithm.narrow_columns: Fit content Size  * 2, Layoutalgorithm.single_column: Fit screen, content will be automatically scaled  
2, set webchromeclient sub-class
Webchromeclient will be called when the interactive action of the browser UI is affected, such as webview Close and hide, page loading progress, JS confirmation box and warning box, JS load before, JS operation timeout, WebView gain focus, etc.

Mwebview.setwebchromeclient (New Mywebchromeclient ());
3, set Webviewclient sub-class
Webviewclient will be called when a number of actions affecting content rendering occur, such as the need to resubmit the form's error submission, page loading and loading, resource loading, receiving HTTPS authentication processing, page keyboard response, URL opening in the page, etc.

Mwebview.setwebviewclient (New Mywebviewclient ());
4. Set Addjavascriptinterface method
Make JS call native local Java object, implement local Java code and HTML page to interact,
Note: Because of security concerns, Google's Java functions, which need to be annotated by @javascriptinterface when using the Android API version above 17, will be recognized as being called by JS.


Third, set the link of the current webpage still jump in webview, instead of jumping to display in the mobile browser,
In Webviewclient subclasses, rewrite the shouldoverrideurlloading function code as follows:

Webview.setwebviewclient (New Webviewclient () {        @Override public      boolean shouldoverrideurlloading (WebView View, String URL) {          view.loadurl (URL);          return true;      }  
Shouldoverrideurlloading indicates that a new URL in the current webview needs to be loaded, give the current application a processing opportunity, and if this function is not overridden, WebView request Activitymanage Choose the appropriate way to process the request. Just like the pop-up UC and the Internet let the user choose a browser. After overriding, return true means that the current program is processed, and return false means that the current webview processing

Iv. setting up to start loading Web pages, loading complete, loading errors when handling
In the Webviewclient subclass, rewrite the following parent-class function code as follows:

Webview.setwebviewclient (New Webviewclient () {        @Override public    void onpagestarted (webView view, String URL, Bitmap favicon) {        super.onpagestarted (view, URL, favicon);        When you start loading a webpage, such as the Load dialog box that displays the load prompt        Dialogmanager.showloadingdialog (this);    }    @Override public    void onpagefinished (WebView view, String URL) {        super.onpagefinished (view, URL);        The Web page loads when finished processing  such as: Let the Load dialog box disappear        dialogmanager.dismissloadingdialog ();    }    @Override public    void Onreceivederror (WebView view, int errorCode, string description, String failingurl) {        Super.onreceivederror (view, ErrorCode, description, failingurl);        When loading a webpage fails  to process such as:        View.loaddatawithbaseurl (null,                "<span style=\" color: #FF0000 \ "> page load failed </ Span> ",                " text/html ",                " Utf-8 ",                null);    }  );

V. Handling HTTPS requests, processing SSL certificate settings for WebView
WebView The default is not to handle HTTPS requests, the page display blank, you need to set the following
The Onreceivedsslerror function code for overriding the parent class in the Webviewclient subclass is as follows:
Webview.setwebviewclient (New Webviewclient () {        @Override public    void Onreceivedsslerror (WebView view, Sslerrorhandler handler, sslerror error) {        handler.proceed ();  Accept the certificate of trust for all websites        //Handler.cancel ();   The default action does not process        //handler.handlemessage (null);  can do other processing    

VI. Display Page Load progress
The Onprogresschanged function code for overriding the parent class in the Webchromeclient subclass is as follows:
Webview.setwebchromeclient (New Webchromeclient () {public        void onprogresschanged (WebView view, int progress) {          settitle ("page load, please wait ..." + progress + "%");          Setprogress (Progress *);            if (progress = =) {              settitle (r.string.app_name);          }      }  );
Onprogresschanged notifies the application of the current page load progress
Progress represents the current page load progress, from 1 to 100 integers

Seven, Back button to control the page backward
Activity the default back key processing for the end of the current Activity,webview view a lot of pages, you want to press the back key to return to the last browsed page, this time we need to overwrite WebView activity onkeydown function, Tell him how to handle the code as follows:

public boolean onKeyDown (int keycode, keyevent event) {      if (Webview.cangoback () && event.getkeycode () = = Keye Vent. Keycode_back && event.getrepeatcount () = = 0) {          webview.goback ();          return true;      }      Return Super.onkeydown (KeyCode, event);  }
where Webview.cangoback () returns True when WebView contains a fallback browsing record
Webview.goback (); Indicates the last visited page returned to WebView

Viii. using Addjavascriptinterface to complete and JS interaction
1. JS Native Local Java method
Set the Addjavascriptinterface method of WebView, the method has two parameters, the first parameter is bound to the class instance in JS, the second parameter is the category name exposed in JS, the reference Java object in JS is the name
In the native Java code is as follows:

Mwebview.getsettings (). Setjavascriptenabled (True); Mwebview.addjavascriptinterface (new Javascriptinterface (this) , "Android"); class javascriptinterface{    Context mcontext;    /** instantiate the interface and set the context *    /javascriptinterface (context c) {        mcontext = c;    }    /** Show A toast from the Web page       * Called by JS to execute native native Java method      */@JavascriptInterface public    void Showtoast (String Toast) {        log.d ("TAG", "Js Invoker Native Function");        Toast.maketext (Mcontext, Toast, Toast.length_short). Show ();    }}
In HTML, JS calls the native method code as follows:

<input type= "button" value= "Say Hello" onclick= "showandroidtoast (' Hello android! ')"/><script type= "text/ JavaScript >    function showandroidtoast (toast) {        android.showtoast (toast);    } </script>
2. Java Tune JS method
For example, in HTML has the following JS function

<script type= "Text/javascript" >      function Showalert () {        alert ("Be executed by Native");    } </script>
In native the JS method is as follows:

Mwebview.loadurl ("Javascript:showalert ()");

Ix. setting of WebView cache mode
1. Web Data cache
When loading an HTML page using WebView, the database and cache two folders are generated under our data/app package:
The URL record we requested is saved in webviewcache.db, and the content of the URL is saved in the Webviewcache folder.

The five cache mode settings Setcachemode:
Load_cache_only: Does not use the network, only the local cache data is read.
Load_default: Decide whether to fetch data from the network according to Cache-control.
Load_cache_normal:api level 17 has been deprecated, starting with the API level 11 with Load_default mode.
Load_no_cache: Do not use caching, only get data from the network.
Load_cache_else_network, the data in the cache is used whenever there is a local, regardless of whether it expires, or No-cache.

As the sample code:

WebSettings websettings = Mwebview.getsettings (); Websettings.setcachemode (Websettings.load_default);  Set cache mode  //Turn on DOM storage API function  websettings.setdomstorageenabled (true);  Open Database storage API function  websettings.setdatabaseenabled (TRUE);  

2. H5 Cache
Sets whether the H5 cache is turned on by setappcacheenabled (Boolean flag) and is turned off by default.
Based on the path provided by Setappcachepath (String Appcachepath), the cache file generated during the H5 using the cache process.
The maximum capacity of the cache is set by setappcachemaxsize (long appcachemaxsize).

As the sample code:

String Cachedirpath = Getcachedir (). GetAbsolutePath () + "/webviewcache"; WebSettings websettings = mwebview.getsettings ();//Open Database storage API function  websettings.setdatabaseenabled (true );    Set Database Cache path  Websettings.setdatabasepath (Cachedirpath);//Turn on application H5 Caches function  Websettings.setappcacheenabled (TRUE); Set application Caches Cache directory  Websettings.setappcachepath (Cachedirpath);

Ten, speed up the HTML page loading completed
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);}    }
At the same time, rewrite the onpagefinished () method in the Webviewclient subclass of WebView to add the following code:

@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.


Xi. WebView Hardware acceleration causes page rendering Flicker problem Solving method
About Android hardware acceleration starts at Android 3.0 (API level 11) and turns hardware acceleration on/off at four levels
1. Application level: Turn on hardware acceleration for the entire application, and add the following configuration to the Androidmanifest

<application android:hardwareaccelerated= "true" ...>
2. Activity level: To control whether each activity turns on hardware acceleration, simply add the android:hardwareaccelerated attribute to the activity element

<activity android:hardwareaccelerated= "true" ...>
3. Window level: Note: It is not supported to turn off hardware acceleration at the window level

GetWindow (). SetFlags (    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
4, view level: Runtime single View hardware acceleration, currently Android does not support the view level to enable the hardware acceleration code as follows:

Mview.setlayertype (view.layer_type_software, NULL);

[//todo about Android hardware acceleration small Lu You Time will be more detailed separately organized into an article to do the introduction
Learning address first: http://android.toolib.net/guide/topics/graphics/hardware-accel.html]

After we turn on hardware acceleration, the WebView renders the page faster, and the drag is smoother. But there is a side effect is easy to appear page loading white block simultaneous interface flicker phenomenon. The workaround for this problem is to set WebView to temporarily turn off the hardware acceleration code as follows:

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

12. Other matters needing attention:
1> the process of downloading HTML pages from the network should be placed in a worker thread (background thread)
2> HTML Download After the success of the process of rendering HTML should be placed in the main UI thread, or WebView loading the page will be prone to error












Android Learning WebView Usage Summary

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.