现在的位置: 首页 > 综合 > 正文

EventBus的使用初试

2017年11月20日 ⁄ 综合 ⁄ 共 981字 ⁄ 字号 评论关闭

当一个Android应用功能越来越多的时候,保证应用的各个部分之间高效的通信将变得越来越困难。如何优雅地解决这个问题?这时候,就需要使用到EventBus。

EventBus是GreenRobot出品的Android系统的一个Event Bus类库,使用起来和之前我们所介绍的Square的Otto差不多,都是用来简化应用组件之间的通信。

1、下载EventBus的类库

https://github.com/greenrobot/EventBus

2、基本使用

  1. Implement any number of event handling methods in the subscriber:接受发送的消息
    public void onEvent(AnyEventType event) {}
  2. Register subscribers:注册
    eventBus.register(this);
  3. Post events to the bus:发送消息
    eventBus.post(event);
  4. 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方法中就可以接受到消息了,去处理一些事情

抱歉!评论已关闭.