- 添加依賴implementation 'org.greenrobot:eventbus:3.1.1'
1. 注冊(cè)
- 注冊(cè)事件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
}
- 解除注冊(cè)
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
2. 事件
- 發(fā)送事件
EventBus.getDefault().post("發(fā)送事件");
- 處理事件
//權(quán)限修飾符必須為public
@Subscribe(threadMode = ThreadMode.MAIN)
public void XXX(MessageEvent messageEvent) {
...
}
3. 粘性事件
- 粘性事件的發(fā)布:
EventBus.getDefault().postSticky("粘性事件");
- 粘性事件的接收
//權(quán)限修飾符必須為public
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void receiveSoundRecongnizedmsg(String insType) {
}
4. 總結(jié)
EventBus能夠簡(jiǎn)化各組件間的通信,讓我們的代碼書寫變得簡(jiǎn)單,能有效的分離事件發(fā)送方和接收方(也就是解耦的意思),能避免復(fù)雜和容易出錯(cuò)的依賴性和生命周期問題。