当一个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);
@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方法中就可以接受到消息了,去处理一些事情
本文介绍了EventBus在Android开发中的使用方法。EventBus能够简化组件间的通信,提高应用程序的效率。文章详细解释了如何下载并引入EventBus库,以及如何通过注册、发送和接收事件来实现组件间的通信。

13万+

被折叠的 条评论
为什么被折叠?



