This example uses a properties file that holds the build number. On every release build, the version number is increased. By adding the file to version control the build number will consistently increase regardless of which team member builds the release.
Note: this is a simple example of automating build number increments. A better way is to use the build number from the CI server.
version.properties
Create a file that holds the current build number, e.g. version.properties
:
# Put this file in the module folder
VERSION_CODE=1
build.gradle
Add the following in your build.gradle
:
android {
def versionPropsFile = file('version.properties')
def buildCode
// Read version number from properties file
if (versionPropsFile.canRead()) {
def Properties props = new Properties()
props.load(new FileInputStream(versionPropsFile))
buildCode = props['VERSION_CODE'].toInteger()
} else {
throw new GradleException('Unable to read version.properties')
}
// Auto-increment versionCode on every release build
ext.autoIncrementBuildNumber = { increment ->
if (versionPropsFile.canRead()) {
def Properties props = new Properties()
props.load(new FileInputStream(versionPropsFile))
buildCode = props['VERSION_CODE'].toInteger()
if (increment) {
buildCode++;
}
props['VERSION_CODE'] = buildCode.toString()
props.store(versionPropsFile.newWriter(), 'Auto-generated, do not edit')
} else {
throw new GradleException('Unable to read version.properties')
}
}
defaultConfig {
versionCode buildCode
versionName "1.0.0"
...
}
buildTypes {
...
}
// Hook to check if the release/debug task is among the tasks to be executed.
//Let's make use of it
gradle.taskGraph.whenReady { taskGraph ->
if (taskGraph.hasTask(assembleDebug)) {
// Get versionCode from file for debug builds
autoIncrementBuildNumber(false)
} else if (taskGraph.hasTask(assembleRelease)) {
// Get versionCode from file and increment by one for release builds
autoIncrementBuildNumber(true)
}
}