EventBus使用详情
EventBus
概述:
EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
2.4版本
初步使用EventBus (—):
http://blog.csdn.net/harvic880925/article/details/40660137
EventBus使用进阶 (—):
http://blog.csdn.net/harvic880925/article/details/40787203
3.0版本
http://www.jianshu.com/p/073309e1d0b2
步骤:
1.导入线上包
//eventbus compile ‘de.greenrobot:eventbus:2.4.0’
2.自定义一个类,可以是空类
3.在要接收消息的页面注册
/**
- 在要接收消息的页面,注册EventBus
/ public void registerEventBus() { //先解绑,再注册EventBus,不能重复注册
EventBus.getDefault().unregister(this);
EventBus.getDefault().register(this);
}
4.发送消息
//发送消息(eventBus) this -> DeviceEditActivity
EventBus.getDefault().post(new EditDeviceNameEventbusBean(et_device_name.getText().toString().trim()));
5.接受消息的页面实现方法(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个)
/* - 接受消息(eventBus) DialogUtils -> this
*/
public void onEventMainThread(EditDeviceNameEventbusBean event) {
Log.e(TAG, event.toString()); }
6.在要接收消息的页面,解除注册
/**
- 在要接收消息页面的onDestroy方法中,反注册EventBus
*/
public void unRegisterEventBus(){
EventBus.getDefault().unregister(this);
}
注:
1.EventBus就是一种发送广播。必须保证接受方在堆栈中,才能接受到post的参数。
2.EventBus在一个布局中不能重复注册,所以注册的时候:先解绑、再注册。特别在Fragement中,如下:
//先解绑,再注册EventBus,不能重复注册 EventBus.getDefault().unregister(this); EventBus.getDefault().register(this);
http://note.youdao.com/share/?id=ab8891baa3f842ab356862c4b00cb135&type=note