EventBus同时支持编译时注解和运行时注解, 当没配置编译时注解处理器时, 会自动通过反射查找运行时的注解, 这将有轻微的性能损失. 可以添加注解处理器, 让其支持编译时注解.
build.gradle(Project)中添加 classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
app/build.gradle(Module)的配置
添加 apply plugin: 'com.neenbedankt.android-apt'
......
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
......
apt {
arguments {
//生成java文件路径, 比如
eventBusIndex "com.maimiho.config.EventBusIndex"
}
}
......
}
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
然后正常的使用EventBus, 最终编译出的Apk中就能找到生成的文件EventBusIndex.class
如下:
package com.maimiho.config;
import com.maimiho.EventBusActivity;
import com.maimiho.entity.Entry;
import java.util.HashMap;
import java.util.Map;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
public class EventBusIndex
implements SubscriberInfoIndex
{
private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX = new HashMap();
static
{
putIndex(new SimpleSubscriberInfo(EventBusActivity.class, true, new SubscriberMethodInfo[] { new SubscriberMethodInfo("onEvent", Entry.class, ThreadMode.MAIN) }));
}
private static void putIndex(SubscriberInfo paramSubscriberInfo)
{
SUBSCRIBER_INDEX.put(paramSubscriberInfo.getSubscriberClass(), paramSubscriberInfo);
}
public SubscriberInfo getSubscriberInfo(Class<?> paramClass)
{
paramClass = (SubscriberInfo)SUBSCRIBER_INDEX.get(paramClass);
if (paramClass != null) {
return paramClass;
}
return null;
}
}