Data interaction between WebView and native JS in Android development

Source: Internet
Author: User
Tags error handling eval html page json touch xmlns

About WebView

We know that some of the apps in the Android Market are developed in roughly three ways: Native app, Web app, Hybrid app. This paper is mainly implemented in hybrid app, the main technology native component and JS data interaction understanding and implementation.

The Android API provides a WebView component to render HTML. The so-called Hybridapp development method is the collection of HTML5, CSS3, JS related development technology, and data Interchange Format Json/xml. This is clearly the skill of a web development engineer. Because of this, many small and medium-sized enterprises have chosen this kind of development way to reduce to the Android development Engineer's excessive dependence, as to these three kinds of development method comparison and the pros and cons are not considered in this article.

With the WebView component, the Android application development technology is passed on to HTML and Java data interaction. Frankly speaking is JS and webview data interaction, this is the article to discuss.




WebView data interaction with JS





1. Load static page in WebView








Add WebView to the application. As with native controls, the WebView control is introduced in layout. The code snippet is as follows:





<?xml version= "1.0" encoding= "Utf-8"?>


<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"


Android:id= "@+id/linearlayout"


Android:layout_width= "Match_parent"


android:layout_height= "Match_parent"


Android:background= "#000"


android:orientation= "Horizontal" >


<webview


Android:id= "@+id/webview"


Android:layout_width= "Match_parent"


android:layout_height= "Match_parent"


/>


</LinearLayout>





Load page:











WebView = (webview) Findviewbyid (R.id.webview);


Webview.loadurl ("file:///file:///android_asset/page.html");





The page.html is stored in the assets root directory of the engineering files.





2. Introduction of jquery Mobile





The introduction of the JS framework allows us to write HTML pages more closely to the native control display effect. The current mainstream mobile application JS Framework is: jquery Mobile and Sencha Touch (jquery Mobile and Sencha touch selection is not covered in this article). This article chooses to use jquery mobile.











First, add the support for JS in WebView:





WebSettings setting = Webview.getsettings ();


Setting.setjavascriptenabled (TRUE);//Support JS





Increase support for Chinese:





WebSettings setting = Webview.getsettings ();


Setting.setdefaulttextencodingname ("GBK");//Set character encoding





To set the page scroll bar style:





Webview.setscrollbarstyle (0);//scroll bar style, 0 refers to the scroll bar does not occupy space, directly covered on the Web page





The standard page template templateforjquery.html provided by jquery Mobile:





<! DOCTYPE html>


<html>


<head>


<title>page title</title>





<meta name= "viewport" content= "Width=device-width, initial-scale=1" >





<link rel= "stylesheet" href= "Css/jquery.mobile-1.1.1.min.css"/>


<script src= "Js/jquery.js" ></script>


<script src= "Js/jquery.mobile-1.1.1.min.js" ></script>


</head>


<body>





<div data-role= "Page" >





<div data-role= "Header" >


<h1>page title</h1>


</div><!--/header-->





<div data-role= "Content" >


<p>page content goes here.</p>


</div><!--/content-->





<div data-role= "Footer" >


<h4>page footer</h4>


</div><!--/footer-->


</div><!--/page-->





</body>


</html>





Page-dependent JS library, CSS, etc. are placed in the assets directory, the directory organization structure is as follows:



To run the screenshot after the application:


The following is a screenshot of the button, no obvious difference from the native control, a kind of genuine feeling:




3. A good user experience





Running our application found that a page with a lot of JS is loaded and waiting, which is a bad user experience. Can be added to the progress bar to resolve. Note the two methods offered by WebView: Setwebviewclient and Setwebchromeclient. One of the setwebchromeclient methods is to handle the loading of progress, in addition, can also handle the JS dialog box, in the WebView Display icon icons and so on. The code snippet for processing progress is as follows:





Webview.setwebchromeclient (New Webchromeclient () {


public void onprogresschanged (WebView view, int progress) {//Load progress change triggers


if (progress = = 100) {


Handler.sendemptymessage (1);//If all loads, Hide progress dialog box


}


Super.onprogresschanged (view, progress);


}


});





The update of the UI thread is handled through the handler message mechanism:











Handler = new Handler () {


public void Handlemessage (message msg) {//define a handler that handles the communication between the download thread and the UI


if (! Thread.CurrentThread (). isinterrupted ()) {


Switch (msg.what) {


Case 0:


Pd.show ()//Show Progress dialog box


Break


Case 1:


Pd.hide ()//Hide Progress dialog box, do not use dismiss (), cancel (), otherwise call show (), the Display of the dialog box Small circle does not move.


Break


}


}


Super.handlemessage (msg);


}


};





For the Setwebviewclient method, it is generally used to handle the loading of HTML (the need to overload onpagestarted (WebView view, String URL, Bitmap favicon)), Close (Requires overloaded onpagefinished (webviewview, String URL) methods).











The role of Setwebviewclient and Setwebchromeclient: The former is mainly used to deal with the control problems of webview, such as loading, closing, error handling, etc., the latter mainly deal with JS dialog boxes, icons, page titles and so on.





4. Get the data in Java





Building a separate interface, as a bridge to handle the data interaction between JS and Java, this article encapsulates the code Androidtoastforjs.java as follows:





public class Androidtoastforjs {





Private context Mcontext;





Public Androidtoastforjs {


This.mcontext = context;


}





Toast native components are invoked in WebView


public void Showtoast (String toast) {


Toast.maketext (Mcontext, Toast, Toast.length_short). Show ();


}





Sum in WebView


public int sum (int a,int b) {


return a+b;


}





The data interaction between WebView and JS is realized with JSON


Public String jsontohtml () {


Jsonobject map;


Jsonarray array = new Jsonarray ();


try {


Map = new Jsonobject ();


Map.put ("name", "Aaron");


Map.put ("Age", 25);


Map.put ("Address", "Shanghai, China");


Array.put (map);





Map = new Jsonobject ();


Map.put ("name", "Jacky");


Map.put ("Age", 22);


Map.put ("Address", "Beijing, China");


Array.put (map);





Map = new Jsonobject ();


Map.put ("name", "Vans");


Map.put ("Age", 26);


Map.put ("Address", "Shenzhen, China");


Map.put ("Phone", "13888888888");


Array.put (map);


catch (Jsonexception e) {


E.printstacktrace ();


}


return array.tostring ();


}


}














WebView provides a way to pass in JS:





Webview.addjavascriptinterface (New Androidtoastforjs (Mcontext), "Javascriptinterface");





Part of the code for the HTML page jsondata.html design is as follows:





<script type= "Text/javascript" >


var result = javascriptinterface.jsontohtml ();


var obj = eval ("(+result+)");//Parse JSON string


function Showandroidtoast (toast)


{


Javascriptinterface.showtoast (toast);


}


function Getjsondata () {


var result = javascriptinterface.jsontohtml ();


var obj = eval ("(+result+)");//Parse JSON string


for (i=0;i<obj.length;i++) {


var user=obj[i];


document.write ("<p> Name:" +user.name+ "</p>");


document.write ("<p> Age:" +user.age+ "</p>");


document.write ("<p> Address:" +user.address+ "</p>");


if (user.phone!=null) {


document.write ("<p> Mobile Number:" +user.address+ "</p>");


}


}


}


Function List () {


document.write ("<div data-role= ' header ' ><p>another</p></div>");


}


</script>


</head>


<body>


<div data-role= "Page" >


<div data-role= "header" Data-theme= "C" >


<h1>android via interface</h1>


</div><!--/header-->


<div data-role= "Content" >


<button value= "Say hello" onclick= showandroidtoast (' hello,android! ') "Data-theme=" E "></button>


<button value= "Get JSON data" onclick= "Getjsondata ()" Data-theme= "E" ></button>


</div><!--/content-->


<div data-role= "Collapsible" data-theme= "C" data-content-theme= "F" >


<h3>i ' m <script>document.write (obj[0].name); </script>,click to I info</h3>


<p><script>document.write ("<p> Name:" +obj[0].name+ "</p>");</script></p>


<p><script>document.write ("<p> Age:" +obj[0].age+ "</p>");</script></p>


<p><script>document.write ("<p> Address:" +obj[0].address+ "</p>");</script></p>


</div>


<div data-role= "Footer" data-theme= "C" >


<h4>page footer</h4>


</div><!--/footer-->


</div><!--/page-->


</body>





Click on the Say hello button to run the screenshot below:














another article about WebView and JS interaction





For Android beginners should know webview this component. I also had some simple understanding of it before, but in a project had to use WebView time, found the strong place of WebView, today to share some experience of using WebView.








1, first understand WebView.





WebView introduced the original text as follows: A View that displays Web pages. This class is the basis upon which can roll your own web browser or simply display some online content within your ACT Ivity. It uses the WebKit rendering engine to display Web pages and includes methods to navigate forward and backward through a h istory, zoom, perform text searches and more.





From the above you should know the basic function, that is, display the Web page. The reason I said webview powerful is because it and JS interaction is very convenient, very simple can be achieved.











2. What can webview do?





①webview can use HTML to do interface layout, although currently less people so use, but I believe that when some clients need complex graphics and text (graphics and text are dynamically generated) mixed row when it must be a good choice.





② directly display the Web page, this function is of course its most basic function.





③ and JS interaction. (If your JS base is better than the Java base, it's a good choice to do some complex processing in this way.)











3. How to use WebView?





Here directly with an SVN take off the demo, first on the demo after the explanation. The chart of the demo is as follows:








Webviewdemo.java





Package Com.google.android.webviewdemo;





Import android.app.Activity;


Import Android.os.Bundle;


Import Android.os.Handler;


Import Android.util.Log;


Import Android.webkit.JsResult;


Import android.webkit.WebChromeClient;


Import android.webkit.WebSettings;


Import Android.webkit.WebView;





/**


* Demonstrates and embed a webview in your activity. Also demonstrates how


* To have JavaScript in the "WebView call into" activity


* can invoke JavaScript.


* <p>


* In this example, clicking on the android in the WebView'll result


* The activities code in {@link demojavascriptinterface#clickonandroid ()}. This Code


* Would turn around and invoke JavaScript using the {@link Webview#loadurl (String)}


* method.


* <p>


* Obviously all of this could have been accomplished without to the activity


* And then back into JavaScript, but this code is intended the


* Code paths for this sort of communication.


*


*/


public class Webviewdemo extends activity {





private static final String Log_tag = "Webviewdemo";





Private WebView Mwebview;





Private Handler Mhandler = new Handler ();





@Override


public void OnCreate (Bundle icicle) {


Super.oncreate (Icicle);


Setcontentview (R.layout.main);


Mwebview = (webview) Findviewbyid (R.id.webview);





WebSettings websettings = Mwebview.getsettings ();


Websettings.setsavepassword (FALSE);


Websettings.setsaveformdata (FALSE);


Websettings.setjavascriptenabled (TRUE);


Websettings.setsupportzoom (FALSE);





Mwebview.setwebchromeclient (New Mywebchromeclient ());





Mwebview.addjavascriptinterface (New Demojavascriptinterface (), "demo");





Mwebview.loadurl ("file:///android_asset/demo.html");


}





Final class Demojavascriptinterface {





Demojavascriptinterface () {


}





/**


* This isn't called on the UI thread. Post a runnable to invoke


* Loadurl on the UI thread.


*/


public void Clickonandroid () {


Mhandler.post (New Runnable () {


public void Run () {


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


}


});





}


}





/**


* Provides a hook for calling ' alert ' from JavaScript. Useful for


* Debugging your JavaScript.


*/


Final class Mywebchromeclient extends Webchromeclient {


@Override


public boolean Onjsalert (WebView view, string URL, string message, jsresult result) {


LOG.D (log_tag, message);


Result.confirm ();


return true;


}


}


}











Demo.html





<html>


<script language= "JavaScript" >


/* This function are invoked by the activity * *


Function Wave () {


Alert ("1");


document.getElementById ("Droid"). src= "Android_waving.png";


Alert ("2");


}


</script>


<body>


<!--Calls into the JavaScript interface for the-->


<a onclick= "window.demo.clickOnAndroid ()" ><div style= "width:80px;


margin:0px Auto;


padding:10px;


Text-align:center;


border:2px solid #202020; ">


<img id= "Droid" src= "Android_normal.png"/><br>


Click me!


</div></a>


</body>


</html>











Main.xml





<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"


android:orientation= "Vertical"


Android:layout_width= "Fill_parent"


android:layout_height= "Fill_parent"


>





<textview


Android:layout_width= "Fill_parent"


android:layout_height= "Wrap_content"


android:text= "@string/intro"


Android:padding= "4dip"


Android:textsize= "16SP"


/>





<webview


Android:id= "@+id/webview"


Android:layout_width= "Fill_parent"


android:layout_height= "0dip"


android:layout_weight= "1"


/>





</LinearLayout>











4, how to interact?





①android how to call JS.





Call form:





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





where Wave () is a method in JS, of course, you can change this method to other methods, that is, Android calls other methods.





②js how to invoke Android.





Call form:





<a onclick= "window.demo.clickOnAndroid ()" >





The "demo" in code is the name of the invocation specified in Android, which is





Mwebview.addjavascriptinterface (New Demojavascriptinterface (), "demo");





The Clickonandroid () in the code is the object of "demo": A Method in New Demojavascriptinterface ().





③ bidirectional Interaction.





Of course, it is possible to combine the two previous ways.











5, explain the demo.





Now you must know the interaction between Android and JS. It is time to analyze some demo, according to the above you should also be more clear. The specific interaction process is as follows:





① Click on the picture, then in the JS-side directly invoke the method of Android Clickonandroid ();





②clickonandroid () method (using threads) to invoke the JS method.





③ is ② called JS to directly control HTML.











Personal Summary: The use of webview this way in some cases, the UI layout can be translated into the corresponding HTML code written, and HTML layout style such as the DW such a powerful tool, and the Internet a lot of source code, a lot of coding. The UI and visual effects save a lot of time, and it doesn't make any sense to reinvent the wheel.

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.