什么是EventBus
EventBus是Android下高效的发布/订阅事件总线机制。作用是可以代替传统的Intent,Handler,Broadcast或接口函数在Fragment,Activity,Service,线程之间传递数据,执行方法。特点是代码简洁,是一种发布订阅设计模式(Publish/Subsribe),或称作观察者设计模式。
如何使用
使用EventBus不需要实现接口,不需要继承父类, 它可以发布Object类型的事件。
注册为订阅者
//注册EventBus
EventBus.getDefault().register(this);
EventBus.getDefault().post(new Object("PostEvent"));
//取消注册EventBus
EventBus.getDefault().unregister(this);
实现事件回调方法
/**
* 与发布者在同一个线程。
* 在子线程中post事件, 则onEvent在子线程中;反之如果在UI线程中post事件,onEvent就在UI线程中被调用
* @param msg 事件1
*/
public void onEvent(MsgEvent1 msg){
String content = msg.getMsg()
+ "\n ThreadName: " + Thread.currentThread().getName()
+ "\n ThreadId: " + Thread.currentThread().getId();
System.out.println("onEvent(MsgEvent1 msg)收到" + content);
}
/**
* 执行在主线程(无论是在UI线程还是子线程中post事件)。
* 非常实用,可以在这里将子线程加载到的数据直接设置到界面中。
* @param msg 事件1
*/
public void onEventMainThread(MsgEvent1 msg){
String content = msg.getMsg()
+ "\n ThreadName: " + Thread.currentThread().getName()
+ "\n ThreadId: " + Thread.currentThread().getId();
System.out.println("onEventMainThread(MsgEvent1 msg)收到" + content);
tv.setText(content);
}
/**
* 执行在子线程,如果发布者是子线程则直接执行,如果发布者不是子线程,则创建一个再执行
* 此处可能会有线程阻塞问题。
* @param msg 事件1
*/
public void onEventBackgroundThread(MsgEvent1 msg){
String content = msg.getMsg()
+ "\n ThreadName: " + Thread.currentThread().getName()
+ "\n ThreadId: " + Thread.currentThread().getId();
System.out.println("onEventBackgroundThread(MsgEvent1 msg)收到" + content);
}
/**
* 无论在哪个线程中post,总是执行在在一个新的子线程
* 适用于多个线程任务处理, 内部有线程池管理。
* @param msg 事件1
*/
public void onEventAsync(MsgEvent1 msg){
String content = msg.getMsg()
+ "\n ThreadName: " + Thread.currentThread().getName()
+ "\n ThreadId: " + Thread.currentThread().getId();
System.out.println("onEventAsync(MsgEvent1 msg)收到" + content);
}
ps: 如果需要接收多个Event,可以把每个Event都按需要选择实现以上四个方法