Skip to content
kgleong edited this page Sep 7, 2015 · 10 revisions

app/build.gradle

A typical gradle build file:

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.sampleapp"
        minSdkVersion 16
        targetSdkVersion 22

        // See sections below for method definitions.
        versionCode generateVersionCode()
        versionName generateVersionName()
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
  • A few attributes worth mentioning:
    • versionCode - internal version number used by the system to determine recency of an application. Type: int. See versionCode description for full details.
    • versionName - version number displayed to users. Type: String. See versionName description for full details.

Generating Version Code

def generateVersionCode() {
    try {
        def output = new ByteArrayOutputStream()

        exec {
            // Count commits in current branch.
            commandLine "git", "rev-list", "HEAD", "--count"
            standardOutput = output
        }

        return output.toString().trim() as int
    }
    catch(exception) {
        return -1
    }
}

Generating Version Name

One approach to version naming is to use the latest tag from the repository.

The git command to retrieve the nearest tag: git describe --tags --abbrev=0.

def generateVersionName() {
    try {
        def output = new ByteArrayOutputStream()

        exec {
            // Get latest tag name.
            commandLine "git", "describe", "--tags", "--abbrev=0"
            standardOutput = output
        }

        return output.toString().trim()
    }
    catch(exception) {
        return null
    }
}
  • Creating a tag:
    • git tag -a 1.0 -m 1.0: creates a tag with name (-a) and message (-m).
    • git push --tags: pushes all local tags to remote repository.

Build a release version using Gradle

// Keystore credentials stored in an external properties file.
def keystorePropertiesPath = System.getenv('MAKORATI_RELEASE_CREDENTIALS_PATH')

// Load keystore credentials.
if(keystorePropertiesPath != null) {
    def keystoreProperties = new Properties()
    keystoreProperties.load(new FileInputStream(keystorePropertiesPath))

    android {
        signingConfigs {
            release {
                storeFile file(keystoreProperties['keystoreFile'])
                storePassword keystoreProperties['keystorePassword']
                keyAlias keystoreProperties['keyAlias']
                keyPassword keystoreProperties['keyPassword']
            }
        }

        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
    }
}
Clone this wiki locally