Automatically increment versionCode when building production APKs

·2 min read·paskov

I use Fabric to monitor app statistics such as Time in App per User and its Beta platform to distribute test builds. Manually incrementing the APK’s versionCode for each build has become tedious.

I decided to simplify things by letting Gradle automatically increment versionCode when building release APKs.

Our implementation uses a properties file named version.properties in the app module’s root directory, alongside build.gradle.

The file contains two properties: VERSION_NAME, which defines a version name such as 2.3, and VERSION_CODE, which defines a version code such as 19.

VERSION_NAME=2.3
VERSION_CODE=19

Next, open the app module’s build.gradle file:

Define a function to retrieve these values from the properties file and increment VERSION_CODE when a release build is requested:

/**
 * Gets a value from the 'version.properties' file.
 * @param varName the name of the property to retrieve.
 * @return the property value.
 */
def getVersionPropertiesValue(def varName)
{
    def propertiesFile = file('version.properties')

    if(!propertiesFile.canRead()) {
        throw new GradleException("Could not read " + propertiesFile.name)
    }

    Properties properties = new Properties();
    properties.load(new FileInputStream(propertiesFile))

    def propertyValue = properties[varName]
    if(varName == 'VERSION_CODE')
    {
        // Increment the version code when building a release.
        List gradleTasksNames = gradle.startParameter.getTaskNames();
        for(String taskName : gradleTasksNames)
        {
            if(taskName.contains("Release"))
            {
                propertyValue = propertyValue.toInteger() + 1
                properties[varName] = propertyValue.toString()
                properties.store(propertiesFile.newWriter(), null)
                break
            }
        }
    }

    return propertyValue
}

In the Gradle build script’s defaultConfig block, we’ll call this function to retrieve the app’s versionName and versionCode values:

android {
    compileSdkVersion 28

    defaultConfig {
        applicationId "com.example.foo"
        versionCode Integer.valueOf(getVersionPropertiesValue('VERSION_CODE'))
        versionName getVersionPropertiesValue('VERSION_NAME')
        minSdkVersion 14
        targetSdkVersion 28
    }
}

Now, each time a release build is requested, the version code will increment automatically. To change the version name, update the VERSION_NAME property.