天天看点

(broadcast,intent,intentfilter消息广播)(interface接口,回调函数)(eventBus)区别,适用场合

项目中需要把activity里的状态传递到子fragment里面,可以用回调函数,可以用消息广播,调查了一番得出以下总结,三个方法:

1 broadcast发送广播消息,消息用intent包装,接收者注册 intentfilter接收

         适用于系统相关消息,一般用在接收系统消息,网络变化,电量变化;可以传递context, intent参数

2 编写interface,制作回调函数

    一般使用步骤:消息发送者定义 interface接口

                                消息接收者注册Listener,注册回调函数

                                消息发送者通过注册进来的Listener调用回调函数,实现数据传递,可以传递context,等任意参数

   由于使用了回调函数原理:因此数据传递实时性非常高,相当于直接调用,一般用在功能模块上:

   比如:开发了一个蓝牙数据收发模块,就可以给这个模块定义interface接口,数据接收者只要注册回调函数即可收的数据,

   同理,Android的按键点击事件就是通过回调函数来响应的,回调函数可以实时响应,可以在Android中遇到很多回调函数传递界面元素状态的示例

3 使用eventBus开源事件发布/订阅框架

关于 eventBus 一共有两个分别是:

1 .hehonghui/AndroidEventBus

这里讲hehonghui的 eventBus,其介绍说明原文为:

“这是一个Android平台的事件总线框架, 它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,

使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。”

(broadcast,intent,intentfilter消息广播)(interface接口,回调函数)(eventBus)区别,适用场合

应用官方文档的插图:官方地址为:

https://github.com/hehonghui/AndroidEventBus/blob/master/README-ch.md

2. greenrobot / EventBus

最后:greenrobot的eventbus现在出了3.0 版本了,使用效果也是相当不错的,官方网站有详细的文档说明:

http://greenrobot.org/eventbus/documentation/

https://github.com/greenrobot/EventBus

(broadcast,intent,intentfilter消息广播)(interface接口,回调函数)(eventBus)区别,适用场合

EventBus...

  • simplifies the communication between components
    • decouples event senders and receivers
    • performs well with Activities, Fragments, and background threads
    • avoids complex and error-prone dependencies and life cycle issues
  • makes your code simpler
  • is fast
  • is tiny (~50k jar)
  • is proven in practice by apps with 100,000,000+ installs
  • has advanced features like delivery threads, subscriber priorities, etc.

通过阅读文档,可以知道eventBus适用于Activity,Fragment,等之间的通信。至于其他优势可以阅读官方文档。

总结来说,eventbus适用于消息传递,毕竟是消息总线,官方文档并未提及,数据传输效率,但肯定的是对于一般消息传递是没有问题的。

由以上分析,我的项目中适合使用EventBus类型的消息传递机制,可以从以上两个框架选择一个来使用。

最后决定使用greenrobot 的 eventBus, 在Android studio 里面 加入,

compile 'org.greenrobot:eventbus:3.0.0'      

没有效果,添加依赖失败,没有一点反应,后来看stackoverflow 说,在allprojects的repositories下面加入 “mavenCentral()”

先开始也是没有效果,后来,重启了Android,然后就可以了,之前好多遍rebuild都不管用