码迷,mamicode.com
首页 > 移动开发 > 详细

JS与IOS、Android的交互

时间:2017-07-07 20:10:23      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:java   js代码   http   ebs   span   github   方法   override   总结   

一、JS与Android

放在了assets文件夹下了(注意若使用的是AS这个IDE,assets文件夹应放在src/main目录下)

<!DOCTYPE html>
<html>

   <head>
      <meta charset="utf-8">
      <title>葛夫锋</title>
      
      <script>
         function callAndroid(){
            test.hello("js调用了android中的hello方法");
         }
      </script>
   </head>

   <body>
      <button type="button" id="button1" onclick="callAndroid()">js调用android中的代码</button>
   </body>

</html>

代码非常简单,页面中就一个按钮,点击这个按钮调用callAndroid函数,这里需注意callAndroid函数中的语句是android中对外的的一个函数,在android中的代码:

{
    ...   
    webSettings.setJavaScriptEnabled(true);
    webView.addJavascriptInterface(this, "test");//对应js中的test.xxx
    webView.loadUrl("file:///android_asset/js_web.html");
}
@JavascriptInterface
public void hello(String msg){//对应js中xxx.hello("")
    Log.e("webview","hello");
    Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}

这里需注意的是hello函数加上注解@javascriptInterface,这样点击html中的按钮就会调用android中的hello方法了。

二、Android调用JS代码

js代码如下:

<script>
   function callJS(){
      alert("android调用了js中的callJS方法");
   }
</script>

android代码如下:

public void click(View view){
    webView.post(new Runnable() {
        @Override
        public void run() {
            webView.loadUrl("javascript:callJS()");
        }
    });
}

当android中的按钮被点击时会触发click方法,然后执行webview.loadUrl("javascript:callJS()"),然后js中正好有callJS这个方法,然后alert()就会被执行。

这个总结很好:

https://github.com/shaojiankui/iOS-WebView-JavaScript

JS与IOS、Android的交互

标签:java   js代码   http   ebs   span   github   方法   override   总结   

原文地址:http://www.cnblogs.com/shoestrong/p/7133642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!