以前知道Android可以和js进行交互,但是一直没有用过,这一次项目中有和js进行交互的需求,所以就研究了一下,下面将会介绍Android程序调用js方法以及js调用Android程序方法。我们只需要几步就可以搞定了,废话不说,走起!!!
第一步:编写相关的html文件demo.html,其中updateHtml()方法是Android程序调用html中js的方法,startFunction()是js调用Android程序的方法,把这个html文件放在assets文件夹下
<html>
<head>
<script type="text/javascript">
function updateHtml(){
document.getElementById("content").innerHTML =
"你通过 android 中的控件调用了html 中js 的方法";
alert("dialog");
}
</script>
</head>
<body>
this is my html <a onClick="window.login.startFunction()" href="";>调用java中个的方法</a>
<span id="content"></span>
</body>
</html>
第二步:创建一个 接口,让 html 页面调用
public class HtmlCallJava {
public void startFunction() {
AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
ab.setTitle("提示");
ab.setMessage("通过 js 调用了 java 中的方法");
ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ab.create().show();
}
}
第三步:代码中对webview进行相应的配置,其中包括向webview注入一个接口,让js调用Android程序的方法
<span style="white-space:pre"> </span>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取webView 控件
final WebView webview = (WebView) findViewById(R.id.webview);
// 加上这句话才能使用javascript方法
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDefaultTextEncodingName("gbk");
// 加载assets目录下面的demo.html 界面
webview.loadUrl("file:///android_asset/demo.html");
Button button = (Button) findViewById(R.id.button); // 获取button控件
// 即"调用html中的js方法"
// 按钮
// 给button添加事件响应,执行JavaScript的fillContent()方法
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Log.d("MainActivity", "button OnClick");
webview.loadUrl("javascript:updateHtml()");
}
});
// 增加接口方法,让html页面调用
webview.addJavascriptInterface(new HtmlCallJava(), "login");
}
其中在向 addJavascriptInterface(Object object , String name )注入接口的时候,需要注意的是name,name应该是html中对应的name。例如:
打完收工!!!