Android Learning WebView Usage Summary

Source: Internet
Author: User
Tags ssl certificate

This period of time based on the project needs in the development of webview contact with more, the previous time about the HTML5 specification dust settled news out of the big 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 also saves development resources and costs to a significant number of enterprises, increasing webview utilization and status 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 display the Web page control, before using the Android Manifest file to configure Internet access permissions, otherwise the prompt page can not be interviewed.

<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 it is sufficient for file operation, cache settings, whether the page supports zooming in and out, whether to agree to use database APIs, font and text encoding settings, whether to agree to JS script execution, whether to agree to the image itself to load, Do you agree to data and password preservation, etc.
The demo 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: Adaptive screen screen, the content will be self-scaling */websettings.setlayoutalgorithm (WebSettings.LayoutAlgorithm.NARROW_COLUMNS); Websettings.setusewideviewport (TRUE); Mwebview.setscrollbarstyle (Webview.scrollbars_outside_overlay); Mwebview.sethorizontalscrollbaroverlay (true); Mwebview.sethorizontalscrollbarenabled (True); Mwebview.requestfocus (); 
2, set webchromeclient sub-class
Webchromeclient will be called when there are some effects on browser UI interaction, such as webview Close and hide, page loading progress, JS confirmation box and warning box, JS loading before, JS operation timeout, WebView gain focus, etc.

Mwebview.setwebchromeclient (New Mywebchromeclient ());
3, set webviewclient sub-class
Webviewclient will be called when some actions affecting content rendering occur, for example, the error submission of the form needs to be submitted again, the page starts loading and loading, the resource is loaded, the HTTPS authentication needs to be processed, the page keyboard responds, the URL opens 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 ability to annotate Java functions through @javascriptinterface when using the Android API version number above 17 is recognized to be invoked 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, override the Shouldoverrideurlloading function code such as the following:

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, giving the current application a processing opportunity, assuming that the function is not overridden, WebView requests Activitymanage to choose the right way to process requests, just like popping up UC and the Internet to let users choose a browser. After overriding, return true means that the current program is processed, and return false means that the current webview processing

Iv. Settings Start loading Web pages, loading complete, loading errors when handling
In the Webviewclient subclass, override for example the following parent-class function code such as the following:

webView.setWebViewClie        NT (new Webviewclient () {@Override public void onpagestarted (WebView view, String URL, Bitmap favicon) {        super.onpagestarted (view, URL, favicon);    When you start loading a Web page, the Load dialog box Dialogmanager.showloadingdialog (this) displays the load prompt.        } @Override public void onpagefinished (WebView view, String URL) {super.onpagefinished (view, URL);    When the page is loaded, 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); Handling when loading a webpage fails such as: View.loaddatawithbaseurl (null, "<span style=\" color: #FF0000 \ "> page loading failed </span    > "," text/html "," Utf-8 ", null); }  });
V. Handling HTTPS requests, processing SSL certificate settings for WebView
WebView default is not to handle HTTPS requests, the page display blank, need to do such as the following settings
In the Webviewclient subclass, override the Onreceivedsslerror function code for the parent class such as the following:
Webview.setwebviewclient (New Webviewclient () {        @Override public    void Onreceivedsslerror (WebView view, Sslerrorhandler handler, sslerror error) {        handler.proceed ();  Accept the certificate of Trust all sites        //Handler.cancel ();   The default action does not process        //handler.handlemessage (null);  can do other processing    

vi. Display Page load progress
In the Webchromeclient subclass, override the Onprogresschanged function code for the parent class such as the following:
Webview.setwebchromeclient (New Webchromeclient () {public        void onprogresschanged (WebView view, int progress) {          settitle ("page loading, please wait ..." + progress + "%");          Setprogress (Progress *);            if (progress = =) {              settitle (r.string.app_name);          }      }  );
Onprogresschanged notifies the application of the current page loading progress
Progress indicates the current page loading progress of 1 to 100 integers

Seven, Back button to control the page backward
Activity the default back key processing to end the current Activity,webview view a very many 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, such as the following:

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);  }
which Webview.cangoback () returns True when WebView contains a fallback browsing record
Webview.goback (); Indicates the last access page returned to WebView

Eight, the use of addjavascriptinterface completed 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 native Java code such as the following:

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 run 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 such as the following:

<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 there are JS functions such as the following

<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 HTML pages using WebView, the database and cache two directories are generated under our data/application package:
The URL record we requested is saved in webviewcache.db, and the content of the URL is stored in the Webviewcache directory.

The five cache mode settings Setcachemode:
Load_cache_only: Do not use the network, just read the local cache data.
Load_default: Depending on the Cache-control, decide whether to fetch data from the network.
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 only locally, regardless of expiration, or No-cache.

As shown in 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 shown in 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 folder  Websettings.setappcachepath (Cachedirpath);

10, speed up the HTML page loading completed
By default, when the HTML code is downloaded to WebView, WebKit starts parsing the Web page nodes, discovers an external style file or an external script file, asynchronously initiates a network request download file, but assumes that before this also resolves to the image node, 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 loading time, resulting in page blank loading too long. The solution is to tell WebView not to take the initiative to load the image, and so on the page after the start of the image loading.
The following code is set for example 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, for example:

@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 is more than 19 version number is compatible. As more than 4.4 of the system in the onpagefinished when the image is loaded, assuming that there are multiple images referenced by the same SRC, there will only be an image tag is loaded, so for this system we first directly loaded.


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, add the following configuration in Androidmanifest, for example

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

<activity android:hardwareaccelerated= "true" ...>
3. Window level: Note: Turning off hardware acceleration at the window level is not supported at this moment

GetWindow (). SetFlags (    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,    WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
4. View level: Single View hardware acceleration at execution time, Android does not yet support hardware acceleration code at the view level such as the following:

Mview.setlayertype (view.layer_type_software, NULL);

[//todo about the Android hardware acceleration small Lu You time will be more specific 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 one side effect is that easy will appear when the page loads the white block at the same time the interface flicker phenomenon. The workaround is to set WebView to temporarily turn off hardware acceleration code such as the following:

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


12, webview loading local HTML file garbled problem resolution method
Analysis one, to ensure that the HTML page has set the encoding format such as:

<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>

Analysis Two, for WebView specify the encoding to display, WebView set encoding is set in settings, such as:

Mwebview.getsettings (). Setdefaulttextencodingname ("Utf-8");
Analysis Three, assume that you are using the LoadData () to load the Display Web page. Chinese garbled is changed to Loaddatawithbaseurl
Reason: Webview.loaddata method does not support Chinese parsing, often use Webview.loaddatawithbaseurl to solve. Such as:
Webview.loaddata (data, "text/html", "Utf-8");  Webview.loaddatawithbaseurl (BASEURL, data, "text/html", "Utf-8", Failurl);


13, 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 Web page will be easy to error







Android Learning WebView Usage 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.