Android 与 Js 较互
html:
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML5 测试</title>
<style type="text/css">
.input{
width:98%;
height:38px;
}
.button{
width:60%;
height:20px;
background:#fffeff;
}
</style>
<script type="text/javascript">
//js调用as
function getParameter(){
var name = document.getElementById("textName").value;
app.getParameter(name);
}
//as调用js
function onResp(name){
document.getElementById("textName").value = name;
}
</script>
</head>
<body>
<input id="textName" class="input" style="width:200px;height:180px;">
<br/>
<hr>
<button class="button" onclick="getParameter()" style="width:200px;height:180px;" >Pay</button>
</body>
</html>
Android端:
WebView初始化:
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JsToJava(), "app");//js 调用android
webView.loadUrl("file:///android_asset/test.html");>
JsToJava.java 作用:接受As 传给Android的参数:
private class JsToJava {
@JavascriptInterface
public void getParameter(String string) {
Snackbar.make(webView, "返回结果:" + string, Snackbar.LENGTH_SHORT).show();
Log.e("info", string);
}
Android传给Js参数,客户端主动调用
public void AndroidToJs() {
webView.post(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:onResp('" + hello js + "')");
//多个参数
webView.loadUrl("javascript:sendVoiceMessage('" + str + "','" + duration + "')");
}
});
}