Weex+Android

Weex和Android之间交互传递

2017-01-17  本文已影响5863人  圈圈猫

最近阿里的weex又发布了,于是去看了下weex文档,然后开始撸码,但是本人不会js,踩了居多的坑。下面来撸下weex和nativie之间的数据交换。

据小白我的了解,weex和native交互有二种方式。1、用本地module的方式,让weex调用本地的代码。2、还是用本地的module的方法,利用JScallback的方式,将native的数据传给weex。下面就通过简单的撸一把demo

方式一:js调Native

通过weex的调用本地的module中的方法,并且利用本地的Toast显示数据。可以在文本框中输入数据,在native中得到数据。

test1.we的代码如下:
<template>
    <div>
        <text onclick="handler">hello world</text>
    </div>
</template>
<script>
    module.exports = {
        data: {  
        },
        methods: {
            handler:function() {
              require('@weex-module/testmodule').printLog("hello weex");
            }
        }
    }
</script>
<style>
native代码:
1、本地需要新建一个类,名字叫LogModule继承WXModule
2、在LogModule的方法必须是public,方法头部加上 @@JSMethod注解。
3、在Application中注册module,或者在初始化的时候注册。
WXSDKEngine.registerModule("testmodule", TestModule.class);

注意:这里的注册名字,也就是"testmodule"和test1.we的 require('@weex-module/testmodule').printLog("hello weex");
中的testmodule需要一直,否则虽然js不会报错,但是却得不到效果。
public class TestModule extends WXModule {
    @JSMethod
    public void printLog(String str){
        Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
    }
}

最后得到结果,在Android手机上回吐司得到hello weex.

方法二:JSCallBack

利用JSCallBack的方式,将native的数据传给Weex。然后在weex做处理。

test2.we:
<template>
    <div>
        <text style="font-size: 50px; color: chocolate" onclick="callme">baidu</text>
    </div>
</template>
<script>
    module.exports = {
        data: {},
        methods: {
            callme:function() {
                
                var mode=require('@weex-module/testmodule');
                mode.printLogs("weex is beach",function (map){
        //modal.toast({title:"wori",duration:2})
                //console.log(map);
              //调用nativie中的方法打日志,得出回调成功了
                require('@weex-module/testmodule').log(map);
                })
            }
        }
    }
</script>
<style>
</style>
native中的代码:

和之前一个一样,我是吧三个方法写在一个module中了。

public class TestModule extends WXModule {
    @JSMethod
    public void printLog(String str){
        Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
    }

    /*****jscallback*****/
    @JSMethod
    public void printLogs(String str, JSCallback callback){
        Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
        Map<String, Object> map = new HashMap<>();
        map.put("caicai", "my");
        callback.invokeAndKeepAlive(map);
      //callback.invoke(map);
    }

    @JSMethod
    public void log(String str){
        Log.e("123", str);
    }
}

1、callback.invokeAndKeepAlive(map);该方法可以调用多次
callback.invoke(map);该方法只会调用一次。

最终结果:
Paste_Image.png
上一篇下一篇

猜你喜欢

热点阅读