android WebView兑现java与javascript的交互

android WebView实现java与javascript的交互
最近在学习html5,网上有很多文章都在分析预测移动互联的未来,很多人的观点是html5会是移动互联的未来,但是不可能完全取代app应用。未来很多的应用将会是html5+native来架构。所以自己想写一个类似的demo,在网上找了好久也没找到一个比较好的文章。为此自己写了一个,主要就是用了WebView类,在此贴出来与大家分享。

1,demo的结构图

android  WebView兑现java与javascript的交互

2,main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/webview"/>

</LinearLayout>


3,index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>webview</title>
<script type="text/javascript">
	function show(jsondata) {
	alert("运行" + jsondata);
		var jsonobjs = eval(jsondata);
		var table = document.getElementById("personTable");
		for(var y=0; y<jsonobjs.length; y++){
			var tr = table.insertRow(table.rows.length);
			var td1 = tr.insertCell(0);
			var td2 = tr.insertCell(1);
			td2.align = "center";
			var td3 = tr.insertCell(2);
			td3.align = "center";
			alert(jsonobjs[y].id);
			td1.innerHTML = jsonobjs[y].id;
			td2.innerHTML = jsonobjs[y].name;
			//td3.innerHTML = jsonobjs[y].mobile;
			td3.innerHTML = "<a href='javascript:contact.call(\""+jsonobjs[y].mobile+"\")'>" + jsonobjs[y].mobile;
		}
	}
	
	
</script>
</head>

<body onload="javascript:contact.getContacts()">
	<table border="0" width="100%" id="personTable" cellpadding="0">
    	<tr>
        	<td width="15%">编号</td>
            <td width="20%" align="center">姓名</td>
            <td aligh="center">电话</td>
        </tr>
    </table>
    [url=javascript:window.location.reload()]刷新[/url]
</body>
</html>


4,Contact.java
package org.sunday.demain;
/**
 * 实体类
 * @author sunday
 *
 */
public class Contact {
	private Integer id;
	private String name;
	private String mobile;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public Contact(Integer id, String name, String mobile) {
		super();
		this.id = id;
		this.name = name;
		this.mobile = mobile;
	}
}

5,ContactService.java
package org.sunday.service;

import java.util.ArrayList;
import java.util.List;

import org.sunday.demain.Contact;
/**
 * 业务逻辑  模拟从服务端获取数据
 * @author sunday
 *
 */
public class ContactService {
	public List<Contact> getContacts() {
		List<Contact> contacts = new ArrayList<Contact>();
		contacts.add(new Contact(34, "张三", "15170013856"));
		contacts.add(new Contact(39, "李四", "15170013856"));
		contacts.add(new Contact(67, "王五", "15170013856"));
		return contacts;
	}
}

6,MyWebViewActivity.java
package org.sunday.main;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.sunday.demain.Contact;
import org.sunday.service.ContactService;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
/**
 * 
 * @author sunday
 *
 */
public class MyWebViewActivity extends Activity {
    /** Called when the activity is first created. */
	private static final String TAG = "MyWebViewActivity";
	private ContactService contactService;
	private WebView webView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        contactService = new ContactService();
        
        webView = (WebView) findViewById(R.id.webview);
        //设置webView可以使用Javascript
        webView.getSettings().setJavaScriptEnabled(true);
        //将插件类实例绑定到javascript中
        webView.addJavascriptInterface(new ContactPlugin(), "contact");
        //加载html,如果有必要此页面可以放在服务器端
        webView.loadUrl("file:///android_asset/index.html");
    }
    
    //插件类
    private final class ContactPlugin {
    	//获取联系人
    	public void getContacts() {
    		List<Contact> contacts = contactService.getContacts();
    		try {
    			JSONArray array = new JSONArray();
    			for(Contact contact : contacts) {
    				JSONObject item = new JSONObject();
    				item.put("id", contact.getId());
    				item.put("name", contact.getName());
    				item.put("mobile", contact.getMobile());
    				array.put(item);
    			}
    			String json = array.toString();
    			Log.e(TAG, "json = " + json);
    			webView.loadUrl("javascript:show('"+json+"')");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	//调用拨号器
    	public void call(String phoneNum) {
    		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum));
    		startActivity(intent);
    	}
    }
    
}


需要源码的留邮箱!