1.)build.gradle添加引用
compile 'org.greenrobot:eventbus:3.0.0'
2.)定义一个事件类型
public class FirstEvent { private String mMsg; public FirstEvent(String msg) { mMsg = msg; } public String getMsg() { return mMsg; } }
3.)订阅/解除订阅
订阅
在onCreate中订阅:EventBus.getDefault().register(this);//订阅
解除订阅
@Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }//解除订阅
4.)发布事件
EventBus.getDefault().post(new FirstEvent("1"));
5.)订阅事件处理
//在ui线程执行@Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(FirstEvent event) { if (event.getMsg().equals("1")) { //事件处理 } }