Android Gradle插件提供了大量的DSL來自定義構建過程,這篇blog就來講解如何在gradle中配置manifest。
DSL提供了配置以下Manifest條目的功能:
minSdkVersion
targetSdkVersion
versionCode
versionName
applicationId (更加方便有效的包名 -- [參考](http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename))
測試app的包名
Instrumentation test runner
- android {
- compileSdkVersion 19
- buildToolsVersion "19.0.0"
- defaultConfig {
- versionCode 12
- versionName "2.0"
- minSdkVersion 16
- targetSdkVersion 16
- }
- }
android元素中的defaultConfig元素就是我們用來配置Manifest的地方。早期版本的Android插件使用packageName來配置manifest中的packageName屬性,從0.11.0開始,使用applicationId來代替packageName。這樣可以消除應用的包名(其實就是應用的id)和java的包名之間的混淆。
更強大的是build文件中描述的配置可以是動態的,比如可以從文件或者自定義的邏輯中獲取版本名稱。
- def computeVersionName() {
- ...
- }
- android {
- compileSdkVersion 19
- buildToolsVersion "19.0.0"
- defaultConfig {
- versionCode 12
- versionName computeVersionName()
- minSdkVersion 16
- targetSdkVersion 16
- }
- }
注意:不要使用作用域中的getter方法名作爲函數名,比如在defaultConfig{}作用域中調用getVersionName()將會自動調用defaultConfig.getVersionName(),而不會調用自定義的方法。
如果某個屬性的值沒有使用DSL設置,這個屬性將會使用某些默認值,下表展示了默認值的處理過程。
屬性名 DSL對象中的默認值 默認值
Property Name | Default value in DSL object | Default value |
versionCode | -1 | value from manifest if present |
versionName | null | value from manifest if present |
minSdkVersion | -1 | value from manifest if present |
targetSdkVersion | -1 | value from manifest if present |
applicationId | null | value from manifest if present |
testApplicationId | null | applicationId + “.test” |
testInstrumentationRunner | null | android.test.InstrumentationTestRunner |
signingConfig | null | null |
proguardFile | N/A (set only) | N/A (set only) |
proguardFiles | N/A (set only) | N/A (set only) |
如果你想在build腳本中使用自定義的邏輯來查詢這些屬性,第二列中的值就很重要。比如,你可以編寫如下的代碼:
- if (android.defaultConfig.testInstrumentationRunner == null) {
- // assign a better default...
- }