1、要实现JS代码与Java代码互相通信,需要通过Android的WebView控件,在视图布局界面引入该控件,代码如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" /> </RelativeLayout>
2、准备html界面:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function show(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); td1.align="center"; var td2=tr.insertCell(1); td2.align="center"; td1.innerHTML=jsonobjs[y].name; td2.innerHTML="<a href='javascript:contact.call(\""+jsonobjs[y].phone+"\")'>"+jsonobjs[y].phone+"</a>"; } } </script> </head> <body onload="javascript:contact.showContacts()"> <table border="0" cellspacing="0" id="personTable" width="100%"> <tr> <td width="35%" align="right">姓名</td><td align="center">电话</td> </tr> </table> <a href="javascript:window.location.reload()">刷新</a> </body> </html>
在上述代码中类似"javascript:contact.showContacts()"这样的写法,它代表的意思是调用javascript对象contact的showContacts方法。而对象contact就要从后台java代码中获取。
3、在java代码中创建javascript对象:
package com.example.html; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import com.example.service.ContactService; import android.net.Uri; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.webkit.WebView; public class MainActivity extends Activity { private WebView webView; private ContactService contactService; @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" }) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) this.findViewById(R.id.webView); webView.loadUrl("file:///android_asset/contact.html");// 加载html文件 webView.getSettings().setJavaScriptEnabled(true);// 启用javascript // 第一个参数在javascript中的一个对象,第二个参数在javascript中当前对象的变量 webView.addJavascriptInterface(new JSObject(), "contact"); contactService = new ContactService(); } private final class JSObject { // 显示联系人列表 @SuppressWarnings("unused") public void showContacts() { try { List<ContactService.Contact> contacts = contactService.getContacts(); JSONArray jsonArray = new JSONArray(); for (ContactService.Contact contact : contacts) { JSONObject object = new JSONObject(); object.put("name", contact.getUsername()); object.put("phone", contact.getPhone()); jsonArray.put(object); } String json = jsonArray.toString(); // 后台调用前台html文件中javascript的方法show webView.loadUrl("javascript:show('" + json + "')"); } catch (Exception e) { e.printStackTrace(); } } // 打电话 @SuppressWarnings("unused") public void call(String phone) { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
3.1 javascript调用java方法:
上面的内部类JSObject 可以看成是javascript的对象,而contact可以看成是该对象的名称,内部的方法showContacts可以看成javascript对象的方法。因此对于在上述代码中"javascript:contact.showContacts()"的写法表示,执行内部类JSObject
中的方法showContacts。
3.2 java调用javascript方法:
可以通过WebView控件调用,例如:webView.loadUrl("javascript:show('" + json + "')")则表示,调用javascript中的show方法。