Android JS双向调用

Android手机中内置了一款高性能webkit内核,该内核完美封装到了WebView组件中,而从js中直接调用java方法和在java中直接调用js方法更是让我们看到了WebView的强大,下面这个小例子介绍了怎样在js和java中双向调用方法

1.首先是布局文件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"
    >
<WebView
	android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/webView"
	/>
</LinearLayout>



2.在assets目录下新建一个index.html文件
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title></title>
    <script type="text/javascript">
    	//data数据类型为字符串,字符串里面是数组,每一个数组元素为一个json对象,例如"[{id:1,name:'张三',phone:'135656461'},{id:2,name:'李四',phone:'1896561'}]"
        function setContactInfo(data)
        {
            var tableObj = document.getElementById("contact");
            var jsonObjects = eval(data);	//通过eval方法处理得到json对象数组
            for(var i=0; i<jsonObjects.length; i++)
            {
                   var jsonObj = jsonObjects[i];	//获取json对象
                   var tr = tableObj.insertRow(tableObj.rows.length);	//添加一行
                   //添加三列
                   var td1 = tr.insertCell(0);
                   var td2 = tr.insertCell(1);
                   var td3 = tr.insertCell(2);
                   
                   td1.innerHTML = jsonObj.id;
                   td2.innerHTML = jsonObj.name;
                   td3.innerHTML = jsonObj.phone;
            }
        }

    </script>
</head>
<!--onload="javascript:myObject.init()调用服务器端init方法-->
<body onload="javascript:myObject.init()">
      <table id="contact">
          <tr>
              <td>编号</td>
              <td>姓名</td>
              <td>电话</td>
          </tr>
      </table>
</body>
</html>


3.接着是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 webView = null;
	public Handler handler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        webView = (WebView)this.findViewById(R.id.webView);
        //设置字符集编码
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        //开启JavaScript支持
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new MyObject(this,handler), "myObject");
        //加载assets目录下的文件
        String url = "file:///android_asset/index.html";
        webView.loadUrl(url);
    }
}


4.然后是绑定js的类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 handler = null;
	private WebView webView = null;

	public MyObject(HTMLActivity htmlActivity, Handler handler) {
		this.webView = (WebView)htmlActivity.findViewById(R.id.webView);
		this.handler = handler;
	}
	
	public void init(){
		//通过handler来确保init方法的执行在主线程中
		handler.post(new Runnable() {
			
			public void run() {
				//调用客户端setContactInfo方法
				webView.loadUrl("javascript:setContactInfo('" + getJsonStr() + "')");
			}
		});
	}
	
	public static String getJsonStr(){
		try {
			JSONObject object1 = new JSONObject();
			object1.put("id", 1);
			object1.put("name", "张三");
			object1.put("phone", "123456");
			
			JSONObject object2 = new JSONObject();
			object2.put("id", 2);
			object2.put("name", "李四");
			object2.put("phone", "456789");
			
			JSONArray jsonArray = new JSONArray();
			jsonArray.put(object1);
			jsonArray.put(object2);
			return jsonArray.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
}



运行项目,我们可以看到两位联系人的信息显示在了屏幕上

你可能感兴趣的:(JavaScript,json,android,webView)