定义事件
public static class MessageEvent { /* Additional fields if needed */ }
(声明和注解事件接收方法)Declare and annotate your subscribing method,注意方法的名称和event名称要对应。
MessageEvent-->onMessageEvent()
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
注册和取消注册
@Override
public void onStart() { super.onStart();
EventBus.getDefault().register(this);
} @Override
public void onStop() { super.onStop();
EventBus.getDefault().unregister(this);
}
发送事件
EventBus.getDefault().post(new MessageEvent()); EventBus.getDefault().post(new MessageEvent(“要传送的内容”));
粘性事件(Sticky Events):就是在发送事件之后再订阅该事件也能收到该事件
EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)// sticky =true,可以接收粘性事件。public void onEvent(MessageEvent event) {
textField.setText(event.message);
}
网友评论