How to generate or set version number for Android apps

Here are two sources of version number (code and/or name) generation for Android projects.

Commit timestamp
Buildscript (build.gradle snippet):

buildscript {
	repositories {
		jcenter()
	}
	dependencies {
		classpath 'org.ajoberstar:gradle-git:1.7.2'
	}
}

import org.ajoberstar.grgit.Grgit

def commitTimestamp = Grgit.open(currentDir: projectDir).head().time

android {
    defaultConfig {
        versionCode commitTimestamp
        versionName "1.2.$commitTimestamp" //optional
    }
}

versionCode will always be equal to the timestamp (in seconds) of the last commit on current branch.

Pros:

  • works everywhere (both locally and on bitrise.io) out of the box, no need for additional steps nor environment variables setup
  • the same (commited) source code will always have the same version number
  • newer code will have higher version number

Cons:

  • may not be suitable for some branching strategies (e.g. if new major version is ready but not released while older one is still maintained and receives new commits)

Bitrise build number

def rawBuildNumber = System.getenv("BITRISE_BUILD_NUMBER") ?: "0"
def buildNumber = Integer.parseInt(rawBuildNumber)

android {
    defaultConfig {
        versionCode buildNumber
        versionName "1.2.$buildNumber" //optional
    }
}

Pros:

  • newer builds will always have higher version number

Cons:

Commit timestamp should be suitable for most of the cases. Build number may be better if you are using dynamic dependency versions/snapshots and/or content downloaded at build time from outside the repository.

3 Likes

Thanks for the detailed #how-to @koral ! :slight_smile:

Just wanted to mention that this #how-to is super useful, linked it to so many users by now… :wink: Thanks again @koral!