下面這一節來介紹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"/>
代碼比較簡單並附有注釋,這裡就不做過多解釋,下面運行一下項目:
html介面沒做美化,所以看起來有點醜,相信美工人員會做的更好,哈哈! 下面我們點擊調用javascript按鈕:
我們已經看到activity調用javascript方法並傳遞參數在html介面做了顯示,下面我們在點擊小明後面的電話號碼看又什麼反應:
OK! 我們已經通過html調用activity的方法並啟動的系統的撥打到電話。