EventBus是一個針對Android優化的發布/訂閱事件總線的框架。意思就是無論你是Activity間通信,fragment間通信,activity與fragment間通信都可以使用EventBus.
1.在項目中添加EventBus
Gradle:
compile 'org.greenrobot:eventbus:3.0.0'
Maven:
<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.0.0</version>
</dependency>
2.自定義一個事件類
public class AnyEventType{
public AnyEventType(){}
}
3.在接收消息的頁面注冊
EventBus.getDefault().register(this);
4.接收消息的方法
@Subscrible
public void onEvent(AnyEventType event){
/*do something */
}
- 發送消息
EventBus.getDefault().post(event);
- 在接收消息的頁面取消注冊
EventBus.getDefault().unregister(this);
參考:https://github.com/greenrobot/EventBus
http://www.lxweimin.com/p/a040955194fc