在android通过webview可以加载html网页,同时也提供了java和js之间的交互功能。例如:可以在webvi加载的html页面中直接调用拨打电话或者发送短信的功能。这个例子只是简单的给出示范,实现android和js间的文字信息传递。
一、首先是android的布局文件,很简单就是一个edittext和button和webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_send"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webView_shownews"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
2、主activity类
public class TestJavacriptActivity extends Activity {
private Button bt;
private EditText et;
private WebView wv;
Handler handler = new Handler() {
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testjavascript);
et = (EditText) this.findViewById(R.id.et_content);
wv = (WebView) this.findViewById(R.id.webView_shownews);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new RunJavaScript(), "myjs");
wv.loadUrl("file:///android_asset/error.html");
bt = (Button) this.findViewById(R.id.bt_send);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
wv.loadUrl("javascript:get4Android('" + et.getText().toString()
+ "')");
}
});
}
class RunJavaScript {
public void runJs(final String str) {
handler.post(new Runnable() {
@Override
public void run() {
// 处理具体的业务逻辑,例如:跳转到新的activity中,或者启动拨号,发短信程序都,可以
et.setText("js-->" + str);
}
});
}
}
}
3、html页面的内容
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function get4Android(str){
document.getElementById("show").innerHTML="This is a message from android:"+str;
}
function send2Android(){
var str = document.getElementById("mess").value;
window.myjs.runJs(str);//调用android的函数
}
</script>
</head>
<body>
<input type="text" id="mess" />
<input type="button" value="Send To Android"onclick="send2Android()"/>
<div id="show"></div>
</body>
</html>