Ryan's Blog

Like Twitter, but longer


Android Version from Git in Gradle

Back in September Jared Sinclair posted a clever way of updating the build number of an iOS app and I’ve been thinking about adapting it for Android ever since.

Well, tonight I finally got round to doing it.

You can run this git command to get a count of the number of commits on your branch.

git rev-list HEAD --count

So what you want to do is get Gradle to figure that out for you when you build and to use it for the VersionCode.

Your Android app will have a number of gradle files. One of those files will have your App settings (I’m assuming you’ve moved your VersionCode and VersionName out of the AndroidManifest.xml and into your gradle file).

My main module is called “app” (I think this is the default), so I want to adjust the build.gradle file in my app Module.

Your build.gradle file will look something like this

apply plugin: 'com.android.application'
android {
   compileSdkVersion 21
   buildToolsVersion "21.1.1"

   defaultConfig {
       applicationId "com.example.appId"
       minSdkVersion 16
       targetSdkVersion 21
       versionCode 1
       versionName "1.0"

   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_7
       targetCompatibility JavaVersion.VERSION_1_7
   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 
dependencies {
   // some dependencies here

At the top of (and inside) the android {} block, you want to add the following

def gitCount = "git rev-list HEAD --count".execute().text

This counts the number of commits and stores it as a variable gitCount.

Then replace the versionCode 1 (or whatever your number is) with

versionCode gitCount.toInteger()

And Bob’s your uncle!

I’ve only tested this on the latest Android Studio and a new project (3 commits). It might cause problems in projects with huge commit counts or lots of branches. It’s also possible to get two different builds with the same VersionCode.

Say you do have multiple branches and you need a way of identifying which build you’re looking at. You can add the branch name to the VersionName in a similar fashion.

def gitBranch = "git rev-parse --abbrev-ref HEAD".execute().text.trim()
// Don't show the branch name for the master (release) branch
gitBranch = (gitBranch == "master") ? "" : "-" + gitBranch

versionName "1.0" + gitBranch