The Android mobile phone has a built-in high-performance WebKit kernel, which is perfectly encapsulated into the webview component, the direct call of the Java method in JS and direct call of the js method in Java show us the strength of webview. The following small example shows how to call two-way methods in JS and Java.
1. The layout file main. xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><WebViewandroid:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/webView"/></LinearLayout>
2.create an index.html file under the assetsdirectory
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML>
3. The next step is activity.
Package COM. lamp. activity; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. webKit. webview; public class htmlactivity extends activity {private webview = NULL; Public handler = new handler (); @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); webview = (webview) This. findviewbyid (R. id. webview); // sets the character set encoding webview. getsettings (). setdefaulttextencodingname ("UTF-8"); // enable Javascript to support webview. getsettings (). setjavascriptenabled (true); webview. addjavascriptinterface (New myobject (this, Handler), "myobject"); // load the file string URL under the Assets Directory = "file: // android_asset/index.html"; webview. loadurl (URL );}}
4. Then, bind the JS class myobject.
Package COM. lamp. activity; import Org. JSON. jsonarray; import Org. JSON. jsonexception; import Org. JSON. jsonobject; import android. OS. handler; import android. webKit. webview; public class myobject {private handler = NULL; private webview = NULL; Public myobject (htmlactivity, Handler handler) {This. webview = (webview) htmlactivity. findviewbyid (R. id. webview); this. handler = handler;} public void Init () {// use handler to ensure that the init method is executed in the main thread. post (New runnable () {public void run () {// call the client setcontactinfo method webview. loadurl ("javascript: setcontactinfo ('" + getjsonstr () + "')") ;});} public static string getjsonstr () {try {jsonobject object1 = new jsonobject (); object1.put ("ID", 1); object1.put ("name", "Zhang San"); object1.put ("phone ", "123456"); jsonobject object2 = new jsonobject (); object2.put ("ID", 2); object2.put ("name", "Li Si"); object2.put ("phone ", "456789"); jsonarray = new jsonarray (); jsonarray. put (object1); jsonarray. put (object2); Return jsonarray. tostring ();} catch (jsonexception e) {e. printstacktrace ();} return NULL ;}}
Run the project. We can see that the information of the two contacts is displayed on the screen.