当前位置: 代码迷 >> Web前端 >> android WebView组合javascript相互调用
  详细解决方案

android WebView组合javascript相互调用

热度:333   发布时间:2012-07-26 12:01:08.0
android WebView结合javascript相互调用
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;

public class FirstActivity extends Activity{
	
	private WebView web;
	//模拟号码簿
	private ArrayList<Contact> contacts = new ArrayList<Contact>();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initContacts();
        web = (WebView)this.findViewById(R.id.webView);
        
        web.getSettings().setJavaScriptEnabled(true);//开启javascript设置,否则WebView不执行js脚本

        web.addJavascriptInterface(this,"phonebook"); //处理window.phonebook.xxx()的标志
        
        web.loadUrl("file:///android_asset/phonebook.html");
    }
    
    /**
     * 该方法将在js脚本中,通过window.phonebook.getContacts()进行调用
     * 返回的ArrayList对象可以使得在js中访问Java集合
     * @return
     */
    public ArrayList<Contact> getContacts(){
    	return contacts;
    
    }
    
    /**
     * 初始化电话号码簿
     */
    public void initContacts(){
    	Contact instance = new Contact();
    	instance.name = "Benny";
    	instance.phone = "13700000";
    	contacts.add(instance);
    	instance = new Contact();
    	instance.name = "Tommy";
    	instance.phone = "15800000";
    	contacts.add(instance);
    }
    
    /**
     * 通过window.phonebook.log来输出js调试信息。
     * @param info
     */
    public void log(String info){
    	Log.i("tag",info);
    }
    
    public void startActivity(){
    	Intent intent = new Intent(this,SecondActivity.class);
    	startActivity(intent);
    } 
}


assets/phonebook.html:
<html> 
<head> 
<title>js交互android</title> 
<script type="text/javascript">
window.onload = function(){
	var persons = window.phonebook.getContacts();//调用FirstActivity.getContacts()
	if(persons){//persons是ArrayList对象
		window.phonebook.log("共有"+persons.size()+"个联系人");
		var contactsE = document.getElementById("contacts");
		var i = 0; 
		while(i < persons.size()){//persons是ArrayList对象
			pnode = document.createElement("p");
			tnode = document.createTextNode("name: " + persons.get(i).getName() + " number: " + persons.get(i).getPhone());
			pnode.appendChild(tnode);
			contactsE.appendChild(pnode);
			i ++;
		}
	}else{
		window.phonebook.log("persons is null.");
	}
	
};
</script> 
</head> 
<body> 
<input type="button" onclick="window.phonebook.startActivity()" value="Goto next" />
<div id = "contacts">
	<p> this is a JS_Android demo </p>
</div>
</body> 
</html> 

  相关解决方案