Android – Override android gradle versionCode form command line

androidandroid-gradle-plugingradleJenkins

i have a build.gradle file in my android app with this settings:

android {
    ...
    defaultConfig {
        applicationId "some.app.id"
        versionName '1.2'
        versionCode 3
        ...
    }
...
}

My AndroidManifest.xml does not contain versionCode and not contain versionName.

Now i want to build this app on Jenkins and pass BUILD_NUMBER as a versionCode for app, so that every build has a higher version.

So in job I hava a call:

./gradlew -PversionCode=$BUILD_NUMBER clean build

When i use "versionCode" to rename "app-release.apk" value of versionCode is the same as passed from command line:

applicationVariants.all { variant ->
    variant.outputs.each { output ->
        output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace("app-release.apk", "MyApp_" + "_v" + versionName + "." + versionCode + ".apk"))
    }
}

Summary

So I have a default value of "versionCode" set to 3, but when building on Jenkins I want to override it from command line.

The problem

The problem is that in AndroidManifest inside build .apk app has versionCode set to 3 instead of value from BUILD_NUMBER.
I checked it with "aapt dump badging"

The question

Can this value "versionCode" from android defaultConfig be overriden by command line parameter?

I know, I could use a function as explained in:
http://robertomurray.co.uk/blog/2013/gradle-android-inject-version-code-from-command-line-parameter/
but I prefer the cleaner way of simple override but I cant get it working.

Best Answer

You can use properties by defining them in a gradle.properties file, see gradle documentation. But you'll have to be really careful which names you use for your properties: if you use versionName that property will have the correct value in gradle (you can println it) but it won't end up in your AndroidManifest.xml! So I chose to use 'versName'. (I don't know enough about gradle to understand why this is so...)

So in your project's gradle.properties you can define the following properties: versCode=3 versName=1.2

And then change the build.gradle file into:

android {
    ...
    defaultConfig {
        applicationId "some.app.id"
        versionName versName
        versionCode versCode as Integer
        ...
    }
    ...
}

Now you can override them on the command line like this: ./gradlew -PversCode=4 -PversName=2.1.3 clean build