下面提供一個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.JavascriptInterfacepublic 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() {@Overridepublic void onClick(View v) {//java調用jswebview.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>