Android: Generate version name / version code / release apk file name automatically


Version code

versionCode is an incremental integer variable. If you are using Git, then you can write a simple function in your build.gradle file


def gitVersion() {
    def process = "git rev-list master --first-parent --count".execute()
    return process.text.toInteger()
}

this will return the commit number and ensures the incremental integer.

Version Name

For versionName you can maintain 3 global variable

versionMajor = 1
versionMinor = 1
versionPatch = 0

and combine them in a function, then return

def buildNumber() {
    return "${versionMajor}.${versionMinor}.${versionPatch}";
}

You can also use the timeStamp in your versionName for a unique naming convention

def buildTime() {
    def df = new SimpleDateFormat("yyMMddhhmm")
    return df.format(new Date())
}

you can merge these two functions

def genVersionName() {
    return buildNumber() + "." + buildTime();
}

and finally,

defaultConfig {
    minSdkVersion 16
    targetSdkVersion 19
    versionCode genVersionCode()
    versionName genVersionName()
    applicationId "com.wordpress.tausiq.sampleapp"
}

Version code again

Major, minor and patch number can also be used to generate versionCode

def genVersionCode() {
    return versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100;
}

Apk naming convention

First write a signingConfigs

    signingConfigs {
        release {
            storeFile file("keys/KEYSTORE_FILE.jks")
            storePassword "*******************"
            keyAlias "*******************"
            keyPassword "*******************"
        }
    }

then write a buildTypes

    buildTypes {
        release {
            signingConfig signingConfigs.release
            applicationVariants.all { variant ->
                def file = variant.outputFile
                def fileName = "App_" + buildTime() + ".apk";
                variant.outputFile = new File(file.parent, fileName);
            }
        }
    }

Release apk file name will be like, App_1410010507.apk
You can modify the naming convention and write/change the functions based on your need.

some more sample functions you may consider

def gitSha() {
      return 'git rev-parse --short HEAD'.execute().text.trim()
    }
def buildTime() {
      def df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
      df.setTimeZone(TimeZone.getTimeZone("UTC"))
      return df.format(new Date())
    }

As a sample example, here is the whole build.gradle file from one of my applications.

build.gradle

import java.text.SimpleDateFormat

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }
}

apply plugin: 'com.android.application'

versionMajor = 1
versionMinor = 1
versionPatch = 0

def gitVersion() {
    def process = "git rev-list master --first-parent --count".execute()
    return process.text.toInteger()
}

def buildNumber() {
    return "${versionMajor}.${versionMinor}.${versionPatch}";
}

def buildTime() {
    def df = new SimpleDateFormat("yyMMddhhmm")
    return df.format(new Date())
}

def genVersionName() {
    return buildNumber() + "." + buildTime();
}

def genVersionCode() {
    return versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100;
}

android {
    packagingOptions {
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
    }

    lintOptions{
        checkReleaseBuilds false
        abortOnError false
    }

    compileSdkVersion 19
    buildToolsVersion '19.1.0'

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 19
        versionCode genVersionCode()
        versionName genVersionName()
        applicationId "com.wordpress.tausiq.sampleapp"
    }

    signingConfigs {
        release {
            storeFile file("keys/app_keystore.jks")
            storePassword "helloWorld"
            keyAlias "SampleApp"
            keyPassword "helloAndroid"
        }
    }

    buildTypes {
        debug {
            runProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            debuggable true
        }
        release {
            runProguard true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            signingConfig signingConfigs.release
            applicationVariants.all { variant ->
                def file = variant.outputFile
                def fileName = "App_" + buildTime() + ".apk";
                variant.outputFile = new File(file.parent, fileName);
            }
        }
    }

    sourceSets {
        androidTest {
            setRoot('src/test')
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':dependency:Formidable')
    compile 'uk.co.androidalliance:edgeeffectoverride:1.0.1'
    compile 'com.doomonafireball.betterpickers:library:1.5.2'
    compile 'de.greenrobot:eventbus:2.2.1'
}

apply plugin: 'idea'

idea {
    module {
        testOutputDir = file('build/test-classes/debug')
    }
}

For more information,
http://stackoverflow.com/questions/21329849/set-android-app-version-using-gradle

Jake Wharton

http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle

http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Signing-Configurations

http://stackoverflow.com/questions/18332474/how-to-set-versionname-in-apk-filename-using-gradle

2 thoughts on “Android: Generate version name / version code / release apk file name automatically

  1. hi~thanks for your share.
    and ,one problem occurs like”Could not find method versionCode() for arguments”
    why?
    i think it identify versionCode as a function,
    but “versionCode 1” will be correct

    do you know why?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s