1,EventBus 主要功能是代替 intent、handler、broadcast实现在activity、fragment、service、线程之间的消息传递,将发送者和接受者解耦。
使用方法:
1,定义要传递的消息类:
public class Data {
public String name;
public int age;
public Data(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
2,注册接受消息的页面
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
}
3,发送消息:
EventBus.getDefault().post(new Data("tzw", 25));
4,接收消息:
public void onEventMainThread(Data event){
System.out.println("onEventMainThread"+event.name+": "+event.age);
System.out.println(Thread.currentThread().getName());
textView.setText(event.age+"");
showToast(context, event.name);
}
public void onEventBackgroundThread(Data event){
System.out.println("onEventBackgroundThread"+event.name+": "+event.age);
System.out.println(Thread.currentThread().getName());
textView.setText(event.age+"");
showToast(context, event.name);
}
public void onEventAsync(Data event){
System.out.println("onEventAsync"+event.name+": "+event.age);
System.out.println(Thread.currentThread().getName());
textView.setText(event.age+"");
showToast(context, event.name);
}
public void onEvent(Data event){
System.out.println("onEvent"+event.name+": "+event.age);
System.out.println(Thread.currentThread().getName());
textView.setText(event.age+"");
showToast(context, event.name);
}
onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在 onEventMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
5,解除注册
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
运行结果:
10-31 14:52:26.086: I/System.out(6802): onEventtzw: 25
10-31 14:52:26.086: I/System.out(6802): main
10-31 14:52:26.096: I/System.out(6802): onEventAsynctzw: 25
10-31 14:52:26.096: I/System.out(6802): pool-1-thread-1
10-31 14:52:26.096: I/System.out(6802): onEventMainThreadtzw: 25
10-31 14:52:26.096: I/System.out(6802): main
10-31 14:52:26.096: I/System.out(6802): onEventBackgroundThreadtzw: 25
10-31 14:52:26.096: I/System.out(6802): pool-1-thread-2
evenBus中还有一种Sticky模式:意思就是 发送事件之后 再订阅该事件 也能收到该事件
http://blog.csdn.net/bboyfeiyu/article/details/46116357
eventBus源码分析:
http://blog.csdn.net/yuanzeyao/article/details/38174537