Set Android app version using Gradle

EDITED

In order to define your app version dynamically, specify a custom method with def and call it, as such:

def computeVersionName() {
    return "2.0"
}

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        versionCode 12
        versionName computeVersionName()
        minSdkVersion 16
        targetSdkVersion 16
    }
}

See here for more.

Make sure not to use function names that could conflict with existing getters in the given scope. For instance, defaultConfig { ... } calling getVersionName() will automatically use the getter defaultConfig.getVersionName() instead of the custom method.


It doesn't resolve your issue, but it can be a different solution.

You can use gradle.properties inside your root project and define:

VERSION_NAME=1.2.1
VERSION_CODE=26

Then in your build.gradle you can use:

versionName project.VERSION_NAME
versionCode Integer.parseInt(project.VERSION_CODE)

Here is a build.gradle that I am using based on ideas from JakeWharton :

apply plugin: 'com.android.application'
def versionMajor = 1
def versionMinor = 2
def versionPatch = 0

def gitVersion() {
    def counter = 0
    def process = "git rev-list master --first-parent --count".execute()
    return process.text.toInteger()
}

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 19
    buildToolsVersion '19.1.0'


    defaultConfig {
        applicationId 'my.project.com'
        minSdkVersion 14
        targetSdkVersion 19
        versionCode gitVersion()
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
    }
    ....
}