为EventBus添加注解处理器

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;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值