android与javascript相互调用

下面这一节来介绍android和javascript是怎么相互调用的,这样我们的UI界面设计起来就简单多了,而且UI设计起来也可以跨平台。现在有好多web app前台框架了,比如sencha和jquery mobile等。相信未来随着web app的发展我们同样可以使用html设计出和本地应用一样漂亮的界面。这些虽然很美好,但是现在还有很多弊端,比如比本地框架调用慢的多,因为手机是受限的设备,所以处理起来和反应都是比较慢的,期望未来会有较大的发展。哈哈!

废话不多说,下面来写一个WebViewDemo实现android与javascript相互调用。

先看一下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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <WebView android:id="@+id/webView" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="调用javascript" /> </LinearLayout>

然后给出我们的demo.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(content){ document.getElementById("countent").innerHTML= "这是我的javascript调用. 这是:"+content; } </script> </head> <body> <table align="center"> <tr><td>姓名</td><td>电话</td></tr> <tr><td>小明</td><td><a href="javascript:demo.startPhone(123)">123</a></td></tr> <tr><td>小王</td><td><a href="javascript:demo.startPhone(456)">456</a></td></tr> </table> <p id="countent">html原始数据</p> </body> </html> 最后附上我们的核心代码:

public class WebViewDemoActivity extends Activity { /** Called when the activity is first created. */ private WebView webView; private Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); webView=(WebView) this.findViewById(R.id.webView); button=(Button) this.findViewById(R.id.button); WebSettings setting=webView.getSettings(); //设置支持javascript setting.setJavaScriptEnabled(true); //增加接口方法,让html页面调用 webView.addJavascriptInterface(new Object(){ //这里我定义了一个拨打的方法 public void startPhone(String num){ Intent intent=new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:"+num)); startActivity(intent); } }, "demo"); //加载页面 webView.loadUrl("file:///android_asset/demo.html"); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub webView.loadUrl("javascript:show('activity传过来的数据')"); } }); } } 这个项目里用到了拨打电话,所以不要忘记这句代码:
<uses-permission android:name="android.permission.CALL_PHONE"/>

代码比较简单并附有注释,这里就不做过多解释,下面运行一下项目:

android与javascript相互调用

html界面没做美化,所以看起来有点丑,相信美工人员会做的更好,哈哈! 下面我们点击调用javascript按钮:

android与javascript相互调用

我们已经看到activity调用javascript方法并传递参数在html界面做了显示,下面我们在点击小明后面的电话号码看又什么反应:

android与javascript相互调用

OK! 我们已经通过html调用activity的方法并启动的系统的拨打电话。