android-apt plugin
What is this?
android-apt插件可以看成是Android Studio下annotation processors的輔助工具.有2個(gè)作用:
- annotation processor依賴僅僅作用于編譯期,不包含在最后apk或者library中
- annotation processor生成的.java文件設(shè)置source paths,這樣確保在Android Studio中能被正確引用
Including and using the plugin in build script
配置project build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
// replace with the current version of the Android plugin
classpath 'com.android.tools.build:gradle:1.3.0'
// the latest version of the android-apt plugin
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
Passing processor arguments
有些注解處理器需要傳自定義參數(shù)崭庸,這就用到了apt.arguments.
比如AndroidAnnotation可以進(jìn)行如下配置:
apt {
arguments {
resourcePackageName android.defaultConfig.applicationId
androidManifestFile variant.outputs[0]?.processResources?.manifestFile
}
}
AndroidAnnotations需要知道AndroidManifest.xml位置闸昨。通過檢索variant為不同的flavor設(shè)置不同的AndroidManifest.xml。然而帽驯,并不是所有的variants(比如unit tests)有對應(yīng)的屬性,因此groovy的?.操作符確保安全性。
def getManifestByVariant(variant) {
// return the value based on the variant
if (variant.name == 'release') {
return '/my/path/to/the/manifest.xml'
}
return variant.outputs[0]?.processResources?.manifestFile
}
apt {
arguments {
if (variant.name == 'debug') {
resourcePackageName "com.myapp.package.name.debug"
// more options
}
androidManifestFile project.getManifestByVariant(variant)
}
}
Comfiguration a compiler style dependency
Annotations processors一般包含2個(gè)部分握恳,分別是API和processor, processor生成的code被API所用(可以看作是包裝wrap)。對于有些項(xiàng)目不同的依賴作用的時(shí)間范圍是不一樣的捺僻,比如Dagger有兩個(gè)artifacts,分別是dagger-compiler和dagger乡洼,dagger-compiler僅僅作用于編譯期崇裁,dagger作用于運(yùn)行時(shí)。
配置這種依賴關(guān)系束昵,插件增加apt configuration拔稳,如下:
dependencies {
apt 'com.squareup.dagger:dagger-compiler:1.1.0'
compile 'com.squareup.dagger:dagger:1.1.0'
}
對于instrumentation test code需要用到processor生成的code, 可用androidTestApt configuration:
dependencies {
androidTestApt 'com.github.frankiesardo:android-auto-value-processor:0.1'
androidTestCompile 'com.github.frankiesardo:android-auto-value:0.1'
}
Additional configuration
可以禁掉javac的默認(rèn)發(fā)現(xiàn)機(jī)制,配置編譯期指定的processor锹雏,具體操作如下:
apt {
processor "my.class.name"
processor "another.processor.class.name"
// if you only want to run the processors above
disableDiscovery true
}
Configuration of other annotation processor
如果processor和API用的是同一個(gè)artifact, 那么不需要特別配置巴比,用compile 句柄添加即可。另外礁遵,如果processor生成的code在我們的項(xiàng)目中被引用了轻绞,android studio 能正確解決reference的問題。
annotationProcessor
Android Gradle plugin 2.2版本支持了apt插件的功能榛丢,不過有限制铲球,那就是必須要開啟jack,Hugo同時(shí)也提供了Migration方案晰赞,參考這篇文章