基本步骤:
1)定义一个类,将数据暴露出来,JS通过该类暴露的public方法来调用Android!
2)在WebView所在页面的Activity中,使用下述代码:
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(object,"name");
然后在js或者html中通过name.xxx调用对象里暴露的相应方法:
比如:
< input type="button" value="Toast提示" οnclick="name.showToast('Hello, world!');"/>
注意事项:
setJavaScriptEnabled在Android 4.4以前的系统才有效!
例子:
demo.html
<html>
<head>
<title>Js调用Android</title>
</head>
<body>
<input type="button" value="Toast提示" οnclick="Demo.showToast('Hello, world!');"/>
<input type="button" value="列表对话框" οnclick="Demo.showDialog();"/>
</body>
</html>
package com.example.hello;
import android.app.AlertDialog;
import android.content.Context;
import android.widget.Toast;
public class Demo {
private Context context;
public Demo(Context context) {
this.context = context;
}
//将显示Toast和对话框的方法暴露给JS脚本调用
public void showToast(String name) {
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
public void showDialog() {
new AlertDialog.Builder(context)
.setTitle("联系人列表")
.setItems(new String[]{"aaa", "bbb", "ccc", "ddd", "eee"}, null)
.setPositiveButton("确定", null).create().show();
}
}
package com.example.hello;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView webView;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView)findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/demo.html");
WebSettings webSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName("UTF-8");
webView.addJavascriptInterface(new Demo(MainActivity.this), "Demo");
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" />
</RelativeLayout>