MessageBus能在任何地方发送消息,在任何地方接受消息。
在接受消息的地方必须注册MessageBus,不需要接受消息的时候反注册,否则会导致内存泄漏。
需要接收消息的地方注册MessageBus。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
MessageBus.getBus().register(this);
...
}
不需要接收消息的时候反注册MessageBus。
@Override
protected void onDestroy() {
MessageBus.getBus().unregister(this);
super.onDestroy();
}
在任意地方发送消息
MessageBus.getBus().send(Test test);//Object can be a class that carries message
根据参数类型接收消息
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
MessageBus.getBus().register(this);
...
}
//ThreadMode用来设置此方法运行的线程
@Subscribe(ThreadMode.MAINTHREAD)
public void recived(Test test) {
String id = test.getId();
String name = test.getUsername();
}
@Override
protected void onDestroy() {
MessageBus.getBus().unregister(this);
super.onDestroy();
}
合并以下代码到需要使用Module的dependencies中
dependencies {
...
compile 'com.hacknife:messagebus:1.0.8'
}