模块间通信EventBus
2016-04-01 10:34
417 查看
模块间通信EventBus
1、简述在真实项目中,模块之间需要通信的业务场景非常常见。比如:个人中心页面显示头像,但是在更改头像的页面更改头像之后,个人中心页面的头像要同步更新。
模块之间的通信可以通过:接口回调、广播、第三方框架EventBus。
接口回调:耦合性高,如果接口多了,不利于后期的维护,可能过几个月之后代码连自己都不想看了,回调地狱。
广播:广播是系统内置的组件,消息型组件,可以通过发送接收消息的形式实现通信,但太麻烦。
EventBus:底层采用反射的机制,使用简单,相比上面两种,代码可读性较高
项目地址:EventBus
2、代码示例
①、在gradle中配置引用:
compile 'org.greenrobot:eventbus:3.0.0'②、单例封装EventBus,方便协调整个系统
public class EventBusManager { private static EventBusManager busManager; private EventBus globalEventBus; private EventBusManager() { } public EventBus getGlobaEventBus() { if (globalEventBus == null) { globalEventBus = new EventBus(); } return globalEventBus; } public static EventBusManager getInstance() { if (busManager == null) { synchronized (EventBusManager.class) { if (busManager == null) { busManager = new EventBusManager(); } } } return busManager; } }③、在更新完头像之后post事件
EventInformationUpadate event = new EventInformationUpadate(); EventBusManager.getInstance().getGlobaEventBus().post(event);④、在个人中心页面注册EventBus监听
//在页面可视状态下注册监听 EventBusManager.getInstance().getGlobaEventBus().register(this);
//在页面不可视状态下取消注册监听 EventBusManager.getInstance().getGlobaEventBus().unregister(this);
/** * EventBus的同步 * * @param event 约定的event */ public void onEventMainThread(EventInformationUpadate event) { //更新用户头像的逻辑 }
相关文章推荐
- Android 中 EventBus 的使用之多线程事件处理
- Spring4 版 eventbus 事件通信 事件驱动 介绍
- EventBus
- android EventBus
- EventBus 学习
- EventBus 学习进阶
- eventbus简单使用
- Android EventBus实战 没听过你就out了
- 都在说EventBus,我也来一波EventBus
- EventBus的使用及 解决异常Subscriber ****has no public methods called **
- Android之数据传输利器和低耦合器EventBus解析
- EventBus使用详解(一)——初步使用EventBus
- EventBus使用详解(二)——EventBus使用进阶
- 使用EventBus实现页面间数据的传递
- EventBus的初级使用技巧
- Event Bus在安卓开发中的使用场景和技巧
- EventBus学习笔记
- eventbus使用
- EventBus的总结
- Android 中 EventBus 的使用(3):多线程事件处理