codaR0y codaR0y - 1 month ago 19
Android Question

How to set versionName in APK filename using gradle?

I'm trying to set a specific version number in the gradle auto-generated APK filename.

Now gradle generates

myapp-release.apk
but I want it to look something like
myapp-release-1.0.apk
.

I have tried renaming options that seems messy. Is there a simple way to do this?

buildTypes {
release {
signingConfig signingConfigs.release
applicationVariants.each { variant ->
def file = variant.outputFile
variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" + defaultConfig.versionName + ".apk"))
}
}


I have tried the code above with no luck. Any suggestions?
(using gradle 1.6)

Answer

This solved my problem: using applicationVariants.all instead of applicationVariants.each

buildTypes {
      release {
        signingConfig signingConfigs.release
        applicationVariants.all { variant ->
            def file = variant.outputFile
            variant.outputFile = new File(file.parent, file.name.replace(".apk", "-" + defaultConfig.versionName + ".apk")) 
        }
    }       
}

Update:

So it seems this does not work with 0.14+ versions of android studio gradle plugin.

This does the trick (Reference from this question ) :

android {
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.outputFile = new File(
                    output.outputFile.parent,
                    output.outputFile.name.replace(".apk", "-${variant.versionName}.apk"))
        }
    }
}