android-gradle-深入淺出四:自定義構建過程之配置manifest

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


示例:
[java] view plain copy
  1. android {  
  2.     compileSdkVersion 19  
  3.     buildToolsVersion "19.0.0"  
  4.   
  5.   
  6.     defaultConfig {  
  7.         versionCode 12  
  8.         versionName "2.0"  
  9.         minSdkVersion 16  
  10.         targetSdkVersion 16  
  11.     }  
  12. }  

android元素中的defaultConfig元素就是我們用來配置Manifest的地方。早期版本的Android插件使用packageName來配置manifest中的packageName屬性,從0.11.0開始,使用applicationId來代替packageName。這樣可以消除應用的包名(其實就是應用的id)和java的包名之間的混淆。


更強大的是build文件中描述的配置可以是動態的,比如可以從文件或者自定義的邏輯中獲取版本名稱。
[java] view plain copy
  1. def computeVersionName() {  
  2.     ...  
  3. }  
  4.   
  5.   
  6. android {  
  7.     compileSdkVersion 19  
  8.     buildToolsVersion "19.0.0"  
  9.   
  10.   
  11.     defaultConfig {  
  12.         versionCode 12  
  13.         versionName computeVersionName()  
  14.         minSdkVersion 16  
  15.         targetSdkVersion 16  
  16.     }  
  17. }  

注意:不要使用作用域中的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腳本中使用自定義的邏輯來查詢這些屬性,第二列中的值就很重要。比如,你可以編寫如下的代碼:
[java] view plain copy
  1. if (android.defaultConfig.testInstrumentationRunner == null) {  
  2.     // assign a better default...  
  3. }  
如果屬性的值仍然是null,那麼在構建的時候,就會使用第三列的默認值,但是DSL元素中並不包含這些默認值,因此你不能在程序中查詢這些值。這樣做的目的是僅在必要的時候(構建時)纔會去解析manifest內容。
發佈了54 篇原創文章 · 獲贊 78 · 訪問量 70萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章