Android十八章:EventBus3.0使用

EventBus是一个在Android优化很好的事件总线,他简化Android的activity,fragment,thread,Service之间通信,代码体积小,质量更高。

总之,他可以代替handler发送msg和Message接受msg,还可以代替intent在activity,fragment等传递msg。

如何使用EventBus

在app/build.gradle

compile 'org.greenrobot:eventbus:3.0.0'

然后在onCreate()注册eventbus,在onDestroy()取消注册。

protected void onCreate(Bundle savedInstanceState){
  EventBus.getDefault().register(MainActivity.this);//注册
}
protected void onDestory(){
  EventBus.getDefault().unregister(MainActivity.this);//取消注册

}

同时在注册的界面接受msg,这里的方法名可以自定义,只要方法前有@Subscribe的注解。

@Subscribe
public void getMessage(String msg){
    Log.i(TAG,msg);
}
  • 如果有方法注解了@Subscribe,而没先注册就会在日志打印
 No subscribers registered for event class com.ppjun.demo.MessageEvent
 No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent
  • 如果actiivty注册了eventbus,而没写一个方法被@Subscribe注解就会报异常
Subscriber class com.ppjun.amapmaster.BActivity and its super classes have no public methods with the @Subscribe annotation

其中@Subscribe注解可以有以下几种情况:

  • @Subscribe(sticky = true)

代表在activity用postSticky信息之后再注册evnetbus,要用这种sticky=true注解方法来接受msg,因为sticky默认为false的

  • @Subscribe(threadMode = ThreadMode.MAIN)

代表主线程或者子线程post信息的到activity的主线程。

  • @Subscribe(threadMode = ThreadMode.BACKGROUND)

如果发布线程是主线程,eventbus就会用一个后台子线程发送给主线程,如果发布线程是子线程,那么处理方法就在子线程执行。最后经过或者不经过线程切换都会原来的线程。

  • @Subscribe(threadMode = ThreadMode.POSTING)

不需要切换线程,发布线程和处理线程一样。简单来说在什么线程post就在什么线程处理。

  • @Subscribe(threadMode = ThreadMode.ASYNC)

处理方法在主线程和发布线程意外的线程执行,处理一些耗时的操作如网络请求。如果有必要还会开启线程池。

post和postSticky的区别

一般注册后,再post信息要用post,而在没注册前post信息,这时候还没有Subscriber,就要用postSticky。

Aactivity.java
protected void onCreate(Bundle savedInstanceState){
  EventBus.getDefault().postSticky("msg from A");
  startActivity(new Intent(Aactivity.this,Bactivity.class));

}

Bactivity.java
protected void onCreate(Bundle savedInstanceState){
  EventBus.getDefault().register(this);


}
@Subscribe(sticky = true)   
public void getMessage(String msg){
     Log.i(TAG,msg);//这里打印出 msg from A
}

protected void onDestory(){
  EventBus.getDefault.unregister(this);

}

Subscribers的优先级

要在同一中ThreadMode中 ,默认的priority是0,优先级更高的会被先执行。

@Subscribe(priority=1)
public void getMessage(String a){

}

取消订阅者Subscriber

通常由优先级更高的订阅者来取消低优先级的订阅者。

@Subscribe
public void onEvent(String msg){
  EventBus.getDefault().cancelEventDelivery(msg);
}

EventBus的混肴

-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}
点赞