1

Is there a way to access the current application version during a build using Android Studio? I'm trying to include the build version string in the filename of the apk.

I'm using the following to change the filename based on the date for a nightly build, but would like to have another flavor for a release build that includes the version name.

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"
                )
            }
        }
    }

}
karl
  • 3,544
  • 3
  • 30
  • 46

1 Answers1

2

Via https://stackoverflow.com/a/19406109/1139908, if you are not defining your version numbers in Gradle, you can access them using the Manifest Parser:

   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)

Also worth noting is that (per https://stackoverflow.com/a/22126638/1139908) using applicationVariants.all can have unexpected behavior for your default debug build. In my final solution, my buildTypes section looks like this:

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
    }
}
Community
  • 1
  • 1
karl
  • 3,544
  • 3
  • 30
  • 46
  • 1
    Great fix. For the import statement, you must update it to `import com.android.builder.core.DefaultManifestParser`, though – espinchi Apr 08 '15 at 15:41
  • This started failing the compilation for me with Gradle 2.14.1 - maybe it's due to my local environment, but just saying. – milosmns Sep 13 '16 at 12:22
  • 1
    This doesn't work with gradle 7. DefaultManifestParser is deprecated and no longer has getVersionName() method – Shivam Pokhriyal Aug 31 '21 at 15:14