Android Html用js实现互通传递数据(Android和html数据传递)

来源:互联网 发布:金蝶k3软件 编辑:程序博客网 时间:2024/06/07 13:43

html和Android之间的数据传递离不开Js

Android端

1.Android端必须支持Js

webView.getSettings().setJavaScriptEnabled(true);

2.Android端定义 @JavascriptInterface

webView.addJavascriptInterface(new WebHost(this), "js");

以及

public class WebHost {        public Context context;        public WebHost(Context context){            this.context = context;        }        @JavascriptInterface        public void acllJs(String url){            Toast.makeText(context, url+"", Toast.LENGTH_SHORT).show();            LogUtils.LogUtils(url+"............................");            handler.obtainMessage(1,"ok").sendToTarget();        }    }

Html端

1.定义JS

<!DOCTYPE HTML><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>文本输入框、密码输入框</title>    <script type="text/javascript">  function rec(){   js.acllJs(111);<!--js与前面映射的参数相同,acllJs()与映射类中的方法相同-->  }</script></head><body><form id="test" name="test" action="">    <p>姓名:<input type="text" name="name"></p>    <p>密码:<input type="text" name="password"></p>    <button name="go" type="button" onclick="rec()" value="GO"/></form></body></html>

2.参数的添加

js.acllJs(111);

里面的111为参数,注意Android端的类型。

注意:js方法名与Android端一致,不然没作用。

1 0