一、基础用法:
1、onCreate()注册eventbus,在onDestroy()取消注册。
protected void onCreate(Bundle savedInstanceState){
EventBus.getDefault().register(MainActivity.this);//注册
}
protected void onDestory(){
EventBus.getDefault().unregister(MainActivity.this);//取消注册
}
2、订阅消息
这里的方法名可以自定义,只要方法前有@Subscribe的注解。主要以方法参数类型区别。
@Subscribe
public void onMessageEvent(MyMsg msg){
}
3、发布消息
EventBus.getDefault().post(new MyMsg());
二、注意事项
1、如果有方法注解了@Subscribe,而没先注册就会在日志打印
No subscribers registered for event class com.ppjun.demo.MessageEvent
No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
2、如果actiivty注册了eventbus,而没写一个方法被@Subscribe注解就会报异常
Subscriber class com.ppjun.amapmaster.BActivity and its super classes have no public methods with the @Subscribe annotation
这一点确实很麻烦,为了解决这个问题,可以在BaseActivity随便写一个带@Subscribe注解的方法通过编译。
3、fragment也要有注册和取消注册,