android-apt是什么?
android-apt 是一個Gradle插件佛猛,協(xié)助Android Studio 處理annotation processors, 它有兩個目的:
1.允許配置只在編譯時作為注解處理器的依賴早抠,而不添加到最后的APK或library
2.設(shè)置源路徑,使注解處理器生成的代碼能被Android Studio正確的引用此插件依賴項(xiàng)目中配置android或android-library(version 0.9.x or up)加酵,
添加android-apt到構(gòu)建腳本中
使用該插件玛迄,添加如下到你的構(gòu)建腳本中:
//配置在Project下的build.gradle中
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:+'
//替換成最新android-apt版本
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
//配置到Module下的build.gradle中
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
傳遞處理器參數(shù)
有些注解處理器需要傳遞參數(shù)乙墙,你能通過使用apt.arguments達(dá)到此目的际看,如下是一個向AndroidAnnotations傳遞參數(shù)的例子
apt {
arguments {
resourcePackageName android.defaultConfig.applicationId
androidManifestFile variant.outputs[0]?.processResources?.manifestFile
}
}
AndroidAnnotations 需要知道AndroidManifest.xml文件所在的位置,檢索variant獲取不同flavor的AndroidManifest.xml文件盖高。然而并非所有變量都有這個屬性(例如慎陵,單元測試就沒有),因此使用groovy操作符?.區(qū)分不能屬性的不同的情況喻奥。
取參數(shù)以也通過以下定義一個函數(shù)席纽,相關(guān)Groovy語法不翻譯(暫時會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)
}
}
配置不同編譯風(fēng)格的依賴
注解處理器一般包含API和使用API生成代碼的processor映凳。項(xiàng)目依賴可能分為多個部分胆筒。例如Dagger有兩個組件Dagger-compiler和dagger。dagger-commpiler僅用于編譯時诈豌,運(yùn)行時必需使用dagger仆救。配置此類組件,apt能這樣使用
dependencies {
apt 'com.squareup.dagger:dagger-compiler:1.1.0'
compile 'com.squareup.dagger:dagger:1.1.0'
}
如果是instrumentation test并需要在Android Studio 中顯示processor生成的代碼矫渔,使用androidTestApt
dependencies {
androidTestApt 'com.github.frankiesardo:android-auto-value-processor:0.1'
androidTestCompile 'com.github.frankiesardo:android-auto-value:0.1'
}
配置 unit test 使用 testApt (注:要求Android Studio 是1.4以上版本)
dependencies {
testApt 'com.github.frankiesardo:android-auto-value-processor:0.1'
testCompile 'com.github.frankiesardo:android-auto-value:0.1'
}
其它配置
它可以指定編譯時處理器的類名彤蔽,并禁用javac默認(rèn)的發(fā)現(xiàn)機(jī)制,需要配置這些類到apt塊中:
apt {
processor "my.class.name"
processor "another.processor.class.name"
// 僅運(yùn)行上面的聲名的處理器類
disableDiscovery true
}
配置其它注解處理器
添加其它注解器不需要額外的配置庙洼,你只需要使用apt添加相關(guān)組件到compile模塊中顿痪。另外,處理器所有生成資源都在代碼正常引用油够。
FAQ
Q:什么時候需要這個插件?
A:當(dāng)你需要引入Processors 生成的源代碼到你的代碼中時蚁袭。例如,當(dāng)你使用Dagger 2 或 AndroidAnnotaition.該插件使得Android Studio可以配置生成資源的build path,避免IDE報錯石咬。當(dāng)使用 apt添加添加依賴揩悄,它將不會被包含到最終的APK里。
Q:provided vs apt 使用注解處理器的不同鬼悠?
A:provided 將會導(dǎo)入注解處理器的classes和它的依賴到IDE的類路徑下删性。這意味著你可以附帶的引入并使用這些classes。例如焕窝,當(dāng)注解處理器使用Guava蹬挺,你可能錯誤的import其相關(guān)代碼到你的Android 代碼中。當(dāng)運(yùn)行時將導(dǎo)致crash它掂。而使用apt巴帮,注解處理器的classes將不會添加到你當(dāng)前的類路徑下,僅僅用于注解處理過程。并且會把所有注解處理器生成的source放在IDE的類路徑下榕茧,方便Android Studio引用发乔。