android---EventBus的简单使用(一)
是什么:
就是用来发消息通信的
怎么用:
-
定义事件:(消息体)
public class MessageEvent { /* Additional fields if needed */ }
-
准备订阅者:声明并注释您的订阅方法,可选择指定一个线程模式
@Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) {/* Do something */}; //粘性事件 @Subscribe (threadMode = ThreadMode.ASYNC,sticky = true) public void myEventBusMessageASYNC(MyMessageEvent myMessageEvent){ Log.e("EventBus","MyEventBusActivity2 ThreadMode.ASYNC 执行Thread = "+Thread.currentThread().getName()+"------------"+myMessageEvent.name); }
- 线程模式选择:
- ThreadMode:POSTING 订阅者将在发布事件的同一线程中调用。这是默认值
- ThreadMode:MAIN 订阅者在主线程中执行
- ThreadMode:MAIN_ORDERED 按照发布顺序执行
- ThreadMode: BACKGROUND 如果发布在主线程,则新开一个线程,
- ThreadMode: ASYNC 新的独立线程中执行
- 注册和注销您的订阅者。例如,在Android上,活动和片段通常应根据其生命周期进行注册
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); }
- 发布活动:
EventBus.getDefault().post(myMessageEvent);
EventBus.getDefault().postSticky(myMessageEvent);
举例:
- 添加依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
- 创建一个事件,(消息体)
public class MyMessageEvent { public String name = ""; public MyMessageEvent(String name) { this.name = name; } }
- 注册,注销订阅者,按照生命周期来
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_event_bus); EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }
- 准备订阅者
@Subscribe (threadMode = ThreadMode.MAIN) public void myEventBusMessage(MyMessageEvent myMessageEvent){ Log.e("EventBus","name = "+myMessageEvent.name); }
//粘性事件@Subscribe (threadMode = ThreadMode.ASYNC,sticky = true)
public void myEventBusMessageASYNC(MyMessageEvent myMessageEvent){
Log.e("EventBus","MyEventBusActivity2 ThreadMode.ASYNC 执行Thread = "+Thread.currentThread().getName()+"------------"+myMessageEvent.name);
} - 发布活动
MyMessageEvent myMessageEvent = new MyMessageEvent("1"); EventBus.getDefault().post(myMessageEvent);
//粘性事件
EventBus.getDefault().postSticky(myMessageEvent);
参考:
http://greenrobot.org/eventbus/documentation/
每天多知道一丢丢