EventBus从3.0开始支持APT,编译期生成文件,就可以得到eventType、subscriberMethod、subscriberClass的映射关系。
app下的build.gradle中引入EventBus和EventBus注解处理器
android {
defaultConfig {
//添加这个,eventBusIndex
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'packageName.MyEventBusIndex' ]
}
}
}
}
dependencies {
//添加eventBus、eventBus的注解
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
RetrofitActivity.java
- 在onCreate()/onDestroy中分别注册、取消注册eventBus
- 定义两个方法,监听同一个事件Repo
- 定义一个方法,监听Book事件
EventBus mEventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEventBus.register(this); //注册
}
@Subscribe
public void receiveRepo(Repo repo) {} //监听Repo 1
@Subscribe
public void receiveRepoTwo(Repo repo) {} //监听Repo 2
@Subscribe
public void receiveBook(Book book) {} //监听Book
@Override
protected void onDestroy() {
mEventBus.unregister(this); //取消注册
super.onDestroy();
}
拷贝一份RetrofitActivity.java ,并重命名为RetrofitTwoActivity.java,build项目
在app/build/generated/source/apt/debug/packageName下,会自动生成一个MyEventBusIndex.java文件。
如下:
public class MyEventBusIndex implements SubscriberInfoIndex {
private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;
static { //静态语句
SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();
putIndex(new SimpleSubscriberInfo(com.example.dexloader.net.RetrofitActivity.class,
true, new SubscriberMethodInfo[] {
new SubscriberMethodInfo("receiveRepo", com.example.dexloader.net.Repo.class),
new SubscriberMethodInfo("receiveRepoTwo", com.example.dexloader.net.Repo.class),
new SubscriberMethodInfo("receiveBook", com.example.dexloader.gson.Book.class),
}));
putIndex(new SimpleSubscriberInfo(com.example.dexloader.net.RetrofitTwoActivity.class,
true, new SubscriberMethodInfo[] {
new SubscriberMethodInfo("receiveRepo", com.example.dexloader.net.Repo.class),
new SubscriberMethodInfo("receiveRepoTwo", com.example.dexloader.net.Repo.class),
new SubscriberMethodInfo("receiveBook", com.example.dexloader.gson.Book.class),
}));
}
private static void putIndex(SubscriberInfo info) {
SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
}
@Override
public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
if (info != null) {
return info;
} else {
return null;
}
}
}