-
Gradle:
compile 'org.greenrobot:eventbus:3.0.0'
2.先注册要使用的Activity
//注册EventBus
EventBus.getDefault().register(this);
3.声明回调方法,@Subscribe关键字不能忽略
@Subscribe
public void onEventMainThread(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
4.使用
EventBus.getDefault().post("Hello everyone!");//传值内容与定义的回调方法参数一致
5.在destroy方法中反注册
@Override
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
6.注意在混淆文件中加入(否则打包后无法使用)
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}