您的位置:首页 > 移动开发 > Android开发

Android WenView中JS代码与JAVA本地代码之间交互 并传递参数

2013-07-03 18:46 447 查看
今天做项目用到了JS与本地JAVA代码交互的方法,写到这里以备后用。

先贴上代码,JAVA代码:

public void initWebView() {//初始化WebView
//初始化一个JavaScriptInterface 此接口用于 HTML中JS代码调用本地代码时使用 必须传入Context
final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(MaxAtExamActivity.this);
v_Web = (WebView) findViewById(R.id.webview);
v_Web.getSettings().setJavaScriptEnabled(true);// 允许JS执行

//加入JavaScriptInterface接口对象 AndroidFunction 为myJavaScriptInterface 对象名称
v_Web.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
v_Web.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);// 点击超链接的时候重新在原来进程上加载URL
return true;
}
});
}

public void loadWebUrl(String url) {
v_Web.loadUrl(url);
}

class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
public void doWork(String webMessage) {//JS代码中调用该方法 webMessage为传入参数
final String msge = webMessage;
runOnUiThread(new Runnable() {
@Override
public void run() {
//得到参数需执行的操作
isAuthAnswer(msge);
}
});
}
}HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>

<script type="text/javascript">
function toJavaCord()
{
var asnwerText = document.getElementById('asnwerText').value;
AndroidFunction.doWork(asnwerText);
}
</script>

</head>

<body>
<form id="form1" name="form1" method="post" action="">
<label>答 案:
<input type="text" name="textfield" id="asnwerText"/>
</label>
<label>
<input name="Submit" type="submit" value="确定" onclick="javascript:return toJavaCord();" />
</label>
</form>
</body>
</html>

其中



红色框中“AndroidFunction”为java代码中的myJavaScriptInterface接口对象的索引名称,doWork()就不用说啦。asnwerText即为JS向JAVA代码所传递的参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: