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

来源:互联网 发布:阿里云服务器克隆 编辑:程序博客网 时间:2024/05/16 04:51

今天做项目用到了JS与本地JAVA代码交互的方法,写到这里以备后用。

先贴上代码,JAVA代码:

public void initWebView() {//初始化WebView//初始化一个JavaScriptInterface  此接口用于  HTML中JS代码调用本地代码时使用   必须传入Contextfinal 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);// 点击超链接的时候重新在原来进程上加载URLreturn 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() {@Overridepublic 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代码所传递的参数。