一、简介
EventBus: Events for Android
EventBus is an open-source library for Android using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.
为应用程序中的各个组件(Activity, Fragment, Service等)提供了一个共享消息总线。
它们都可以注册接入消息总线,从而接收广播的消息,也可以往总线发消息。
二、上手
1)Add EventBus as a dependency to your module.
compile 'org.greenrobot:eventbus:3.0.0'
2)Register Activity or Fragment to the event bus between onStart and onStop.
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
3)Define an Event class.
public class MessageEvent {
private final String message;
MessageEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
4)Add event listener functions with annotation @Subscribe .
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Log.d(TAG, "onMessageEvent " + event.getMessage());
textView.setText(TAG + " " + event.getMessage());
}
@Subscribe
public void onYAMessageEvent(MessageEvent event) {
Log.d(TAG, "onYAMessageEvent " + event.getMessage());
}
5)Post event from anywhere.
EventBus.getDefault().post(new MessageEvent(message));
详见官方文档。有问题欢迎回帖交流。