下面提供一个android与js互调的简单示例
(1) android 中 通过该方法调用执行Js中的jsGetTextValue()方法: webview.loadUrl("javascript:jsGetTextValue()");
(2) js中通过addJavascriptInterface设置接口名为jsIntr,然后js中即可直接引用该对象,通过该对象调用java的方法javaSetText();
注意:android4.4以上的版本在addJavascriptInterface中添加的接口方法都必须加上这个前缀 "@android.webkit.JavascriptInterface" ,否则js无法调用java。
1、测试html文件,存放位置 assets / html / test.html
<html>
<body>
<form action="#" method="get">
<p>1 name: <input id="text1" type="text" name="text1" value="1"/></p>
<input type="button" value="button1_value" name="button1_name" onclick="jsGetTextValue()"/>
</form>
<script type="text/javascript">
function jsGetTextValue() {
//js调用java
window.jsIntr.javaSetText(document.getElementById("text1").value);
}
</script>
</body>
</html>
2、android代码,WebActivity.java
public class WebActivity extends Activity {
private WebView webview;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webview = (WebView) findViewById(R.id.webview);
button = (Button) findViewById(R.id.button);
//允许html执行JS脚本,如果不进行设置的话,JS函数无法生效
webview.getSettings().setJavaScriptEnabled(true); //在设置JS调用java方法的接口对象,在JS中可以直接访问该对象,然后调用该对象的方法间接地执行java代码
webview.addJavascriptInterface(new Object() {
@android.webkit.JavascriptInterface
public void javaSetText(String text) {
Log.e("text value", text);
}
//jsIntr是接口名,使用在js中,为调用的java方法的对象
}, "jsIntr");
webview.loadUrl("file:///android_asset/html/test.html");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//java调用js
webview.loadUrl("javascript:jsGetTextValue()");
}
);
}
}
3、布局文件 activity_web.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Get Value" />
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/button" />
</RelativeLayout>