2015-01-15 145 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

相关问题