基本介绍
- EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
源码
基本使用
- 自定义一个类,用于发送和接收信息。构造时传入要发送的信息,然后get方法返回信息。(也可以是空类).
例如:
public class FirstEvent {
private String mMsg;
public FirstEvent(String msg) {
// TODO Auto-generated constructor stub
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
- 在要接收信息的地方注册EventBus
- 例如:在要接收信息的activity中的onCreate()中注册
EventBus.getDefault().register(this);
//使用默认方式注册
- 在注册的页面中注销EventBus
- 例如:在activity中的onDestroy中注销:
EventBus.getDefault().unregister(this); //反注册EventBus
- 发送消息,使用EnventBus的post方法
- 发送消息是使用EventBus中的Post方法来实现发送的,发送过去的是我们新建的类的实例!
EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
- 接收消息,在要接收消息的地方重写EnventBus的接收信息的函数
public void onEventMainThread(FirstEvent event) {
Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());
}
EventBus的接收函数
- EventBus的接收函数有以下4种:onEvent、onEventMainThread、onEventBackgroundThread、onEventAsync
- onEvent: 如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行</