Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Android Gradle] Auto-Increment version code/name in AndroidManifest/Gradle before Jenkins Build
import java.util.regex.Pattern
def versionMajor = 1
def versionMinor = 0
def versionPatch = 0
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.12.0'
}
}
apply plugin: 'android-sdk-manager'
apply plugin: "com.android.application"
android {
compileSdkVersion project.ANDROID_BUILD_SDK_VERSION
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
applicationId project.APPLICATION_ID
minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION
targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION
def vCode
def vName
def vItem
def buildNum = System.getenv("BUILD_NUMBER") ?: 0
if (buildNum != 0) {
vItem = buildNum.toInteger()
} else {
vItem = versionPatch
}
versionCode versionMajor * 10000 + versionMinor * 1000 + vItem * 100
versionName "${versionMajor}.${versionMinor}.${vItem}"
}
buildTypes {
debug {
applicationIdSuffix ".debug"
minifyEnabled false
debuggable true
testCoverageEnabled true
applicationVariants.all { variant ->
variant.outputs.each { output ->
def buildNum = System.getenv("BUILD_NUMBER") ?: 0
if (buildNum != 0) {
def manifestFile = file("src/main/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def pattern2 = Pattern.compile("versionName=\"(.*?)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def manifestContent = matcher.replaceAll("versionCode=\"" + buildNum + "\"")
def matcher2 = pattern2.matcher(manifestContent)
matcher2.find()
def manifestContent2 = matcher2.replaceAll("versionName=\"" + "${versionMajor}.${versionMinor}." + buildNum + "\"")
manifestFile.write(manifestContent2)
def file = output.outputFile
def newfilename = file.name.replace(".apk", "-" + buildNum + ".apk")
output.outputFile = new File(file.parent, newfilename)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.