Android使用EventBus传递事件

【Android使用EventBus传递事件】EventBus使用过程很简单
EventBus官网
1.引入

// module.app build.gradle dependencies { //... implementation 'org.greenrobot:eventbus:3.2.0' }

2.创建Event
public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } }

3.设置监听和声明周期,以MainActivity的片段为例
@Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { Toast.makeText(getBaseContext(), event.message, Toast.LENGTH_LONG).show(); }@Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); }@Override protected void onStop() { EventBus.getDefault().unregister(this); super.onStop(); }

4.发送Event,这里在Application中模拟了一个异步任务
new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); EventBus.getDefault().post(new MessageEvent("Hello bro")); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); `

    推荐阅读