2015-01-15 108 views
1

有沒有一種方法可以在使用Android Studio的構建期間訪問當前應用程序版本?我試圖在apk的文件名中包含構建版本字符串。從Android Studio的清單中獲取應用程序版本build.gradle

我正在使用以下命令來根據每晚構建的日期更改文件名,但想要爲包含版本名稱的發佈版本創建另一種風格。

productFlavors { 

    nightly { 
     signingConfig signingConfigs.debug 
     applicationVariants.all { variant -> 
      variant.outputs.each { output -> 
       def file = output.outputFile 
       def date = new Date(); 
       def formattedDate = date.format('yyyy-MM-dd') 
       output.outputFile = new File(
         file.parent, 
         "App-nightly-" + formattedDate + ".apk" 
       ) 
      } 
     } 
    } 

} 

回答

2

通過https://stackoverflow.com/a/19406109/1139908,如果你不是在搖籃定義你的版本號,您可以使用清單解析器訪問它們:

import com.android.builder.core.DefaultManifestParser // At the top of build.gradle 

    def manifestParser = new com.android.builder.core.DefaultManifestParser() 
    String versionName = manifestParser.getVersionName(android.sourceSets.main.manifest.srcFile) 

另外值得一提的是,使用applicationVariants.all(每https://stackoverflow.com/a/22126638/1139908)可以有您的默認調試版本的意外行爲。在我的最終解決方案中,我的buildTypes部分看起來像這樣:

buildTypes { 
    applicationVariants.all { variant -> 
     variant.outputs.each { output -> 
      def String fileName; 
      if(variant.name == android.buildTypes.release.name) { 
       def manifestParser = new DefaultManifestParser() 
       def String versionName = manifestParser.getVersionName((File) android.sourceSets.main.manifest.srcFile) 
       fileName = "App-release-v${versionName}.apk" 
      } else { //etc } 
      def File file = output.outputFile 
      output.outputFile = new File(
        file.parent, 
        fileName 
      ) 
     } 
    } 

    release { 
     //etc 
    } 
} 
+1

很好的修復。對於import語句,您必須將其更新爲'import com.android.builder.core.DefaultManifestParser',儘管 – espinchi 2015-04-08 15:41:26

+0

這開始無法使用Gradle 2.14.1編譯 - 也許這是由於我的本地環境,但只是說。 – milosmns 2016-09-13 12:22:29

相關問題