当一个Android应用功能越来越多的时候,保证应用的各个部分之间高效的通信将变得越来越困难。如何优雅地解决这个问题?这时候,就需要使用到EventBus。
EventBus是GreenRobot出品的Android系统的一个Event Bus类库,使用起来和之前我们所介绍的Square的Otto差不多,都是用来简化应用组件之间的通信。
1、下载EventBus的类库
https://github.com/greenrobot/EventBus
2、基本使用
- Implement any number of event handling methods in the subscriber:接受发送的消息
public void onEvent(AnyEventType event) {}
- Register subscribers:注册
eventBus.register(this);
- Post events to the bus:发送消息
eventBus.post(event);
- Unregister subscriber:解除注册
eventBus.unregister(this);
1、在你要接受消息的组件中,例如Activity中,注册EventBus
@Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } public void onEvent(PhotoSelectionRemovedEvent event) { // refreshSelectedPhotosTitle(); // refreshUploadActionBarView(); Log.i("LogUtil", "LogUtil....onEvent"); }
2、在其他的组件中,你需要通知注册了的Activity时,只需要EventBus.getDefault().post(new PhotoSelectionRemovedEvent());上面的Activity中onEvent方法中就可以接受到消息了,去处理一些事情