The original source is the following, http://devdeeds.com/auto-increment-build-number-using-gradle-in-android/ I have added some minor changes
Create a file with the build version at the module level version.properties:
VERSION_BUILD=1
VERSION_BUILD_CRASHLYTICS=1
Inside the build gradle do something like this:
versionName "1.0."
/*Setting default value for versionBuild which is the last incremented value stored in the file */
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionBuild = versionProps['VERSION_BUILD'].toInteger()
versionBuildCrashlytics = versionProps['VERSION_BUILD_CRASHLYTICS'].toInteger()
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
/*Wrapping inside a method avoids auto incrementing on every gradle task run. Now it runs only when we build apk*/
ext.autoIncrementBuildNumber = { envVar ->
if (versionPropsFile.canRead()) {
Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionBuild = versionProps[envVar].toInteger() + 1
versionProps[envVar] = versionBuild.toString()
versionProps.store(versionPropsFile.newWriter(), null)
} else {
throw new FileNotFoundException("Could not read version.properties!")
}
}
gradle.taskGraph.whenReady {taskGraph ->
if (taskGraph.hasTask(assembleReleaseCrashlytics)) { /* when run debug task */
autoIncrementBuildNumber('VERSION_BUILD_CRASHLYTICS')
} else if (taskGraph.hasTask(assembleRelease)) { /* when run release task */
autoIncrementBuildNumber('VERSION_BUILD')
}
}
applicationVariants.all { variant ->
variant.outputs.all { output ->
if (variant.name.contains('Crashlytics'))
outputFileName = "${variant.name}-${variant.versionName}${versionBuildCrashlytics}.apk"
else
outputFileName = "${variant.name}-${variant.versionName}${versionBuild}.apk"
}
}