Android 与 js交互(二)

来源:互联网 发布:淘宝产品销量排行 编辑:程序博客网 时间:2024/05/25 19:58

上次说到基础的代码这次是使用框架来进行交互

github上有3000星的框架很好用,

下面是框架的传送门:

https://github.com/lzyzsd/JsBridge

先说安卓中调用js中的代码:

 
function connectWebViewJavascriptBridge(callback) {            if (window.WebViewJavascriptBridge) {                callback(WebViewJavascriptBridge)            } else {                document.addEventListener(                    'WebViewJavascriptBridgeReady'                    , function() {                        callback(WebViewJavascriptBridge)                    },                    false                );            }        }//这里会注入一个WebViewJavascriptBridge 到window对象中        connectWebViewJavascriptBridge(function(bridge) {            bridge.init(function(message, responseCallback) {                console.log('JS got a message', message);                var data = {                    'Javascript Responds': '测试中文!'                };                document.getElementById("show").innerHTML=message;                console.log('JS responding with', data);                responseCallback(data);            });//上面这个方法是注册一个默认的js与Android连接            bridge.registerHandler("functionInJs", function(data, responseCallback) {                document.getElementById("show").innerHTML = ("data from Java: = " + data);                var responseData = "成功调用js方法";                responseCallback(responseData);            });
//上面这个方法是注册一个特定的Android与js的连接functionInJs        })
那么Android中如何给js发送消息呢

首先得先获取webview 的对象

  web = ((BridgeWebView) findViewById(R.id.webview));
然后load网页:

  web.loadUrl("file:///android_asset/index.html");
然后就可以调用了

    public void click(View view) {        switch (view.getId()){            case R.id.bt1:
//这里调用了一个连接名字为functionInJs的注册方法                web.callHandler("functionInJs", "data from Java", new CallBackFunction() {                    @Override                    public void onCallBack(String data) {                        // TODO Auto-generated method stub                        Log.i(TAG, "reponse data from js " + data);//这里是调用完成后js返回给你的消息                    }                });                break;            case R.id.bt2:               // web.callHandler();                web.send("hello");//这里发送了消息没有指明对象于是默认的js连接会拦截这个消息执行处理并返回数据                break;        }    }
所有调用和被调用的方法都需要写在注册对象中,使用的时候不必写过多的注册对象可根据所传的参数来执行不同的方法
下面是一些log

05-16 00:18:04.950 10059-10059/com.example.administrator.webviewtest2 E/BRIDGE: handler: {"id":1,"content":"我正在调用Android方法"}05-16 00:18:04.985 10059-10059/com.example.administrator.webviewtest2 I/chromium: [INFO:CONSOLE(1)] "{"responseData":"成功调用默认方法","responseId":"cb_1_1494865084919"}", source:  (1)                                                                                                                                                                                                                                                      --------- beginning of system05-16 00:18:07.125 10059-10059/com.example.administrator.webviewtest2 I/chromium: [INFO:CONSOLE(1)] "{"data":"hello"}", source:  (1)05-16 00:18:07.130 10059-10059/com.example.administrator.webviewtest2 I/chromium: [INFO:CONSOLE(41)] "JS got a message", source: file:///android_asset/index.html (41)05-16 00:18:07.135 10059-10059/com.example.administrator.webviewtest2 I/chromium: [INFO:CONSOLE(46)] "JS responding with", source: file:///android_asset/index.html (46)05-16 00:18:07.155 10059-10059/com.example.administrator.webviewtest2 I/chromium: [INFO:CONSOLE(1)] "WebViewJavascriptBridge: WARNING: javascript handler threw.", source:  (1)

上面是方法中的log

接下来是js中调用Android的方法:

function jsfunc1(){
//这是调用安卓中注册的默认连接 var data = {id: 1, content: "我正在调用Android方法"};            window.WebViewJavascriptBridge.send(                data                , function(responseData) {                    document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData//这里是执行成功后Android返回的数据                }            );}function jsfunc2(){
//这里是调用了安卓中注册的submitFromWeb的连接注意到了吗?少了个参数            window.WebViewJavascriptBridge.callHandler(                'submitFromWeb'                , {'param': '中文测试'}                , function(responseData) {                    document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData//这里是执行成功后Android返回的数据                }            );}
上面两个方法是js中两个按钮点击后会执行的方法。

接下来是Android中的代码:

  web.setDefaultHandler(new DefaultHandler(){            @Override            public void handler(String data, CallBackFunction function) {               // super.handler(data, function);                Log.e(TAG, "handler: "+data );                function.onCallBack("成功调用默认方法");//回调发送回数据给js            }
}
注册的是默认连接

      web.registerHandler("submitFromWeb", new BridgeHandler() {            @Override            public void handler(String data, CallBackFunction function) {                Log.i(TAG, "web = " + data);                function.onCallBack("成功调用安卓方法");//回调发送回数据给js            }        });
注册的是带参数的连接


以上就是该框架的进行交互的方法:

我把布局文件粘贴一下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context="com.example.administrator.webviewtest2.MainActivity">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:orientation="vertical"        >        <Button            android:id="@+id/bt1"            android:onClick="click"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="调用js1"/>        <Button            android:id="@+id/bt2"            android:onClick="click"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="调用js2"/>    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        >        <com.github.lzyzsd.jsbridge.BridgeWebView            android:id="@+id/webview"            android:layout_width="match_parent"            android:layout_height="match_parent">        </com.github.lzyzsd.jsbridge.BridgeWebView>    </LinearLayout></LinearLayout>

虽然现在这些知识用不到,学习全凭兴趣,学无止境。

注意:通讯的时候不必写过多的注册,只需更改参数就可以进行不同操作了。


原创粉丝点击