前面的博客中获取EventBus,都是使用EventBus.getDefault(),而如果需要对EventBus进行配置,那么需要使用EventBus.Builder进行设置。
EventBus eventBus = EventBus.builder()
.logNoSubscriberMessages(false)
.sendNoSubscriberEvent(false)
.build();
public void downloadPage(View view) {
EventBus.getDefault().postSticky(new DownloadEvent());
startActivity(new Intent(this,SecondActivity.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
EventBus.getDefault().register(this);
}
@Subscribe(sticky = true)
public void download(DownloadEvent downloadEvent) {
Toast.makeText(this,"Receive Sticik Event",Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
当Activity A跳转到Activity B时将会有Toast提示;当把Activity B中download方法的注解stick修改为false后,将不再有Toast提示,从而可以看到粘性事件是如何作用的。
DownloadEvent stickyEvent = EventBus.getDefault().getStickyEvent(DownloadEvent.class);
if(stickyEvent!=null){
EventBus.getDefault().removeStickyEvent(stickyEvent);
}
DownloadEvent previousEvent = EventBus.getDefault().removeStickyEvent(DownloadEvent.class);
if(previousEvent!=null){
EventBus.getDefault().removeStickyEvent(previousEvent);
}
@Subscribe
public void onEvent(MessageEvent event){
EventBus.getDefault().cancelEventDelivery(event) ;
}