Skip to content

Instantly share code, notes, and snippets.

@akingdom
Last active January 17, 2023 14:25
Show Gist options
  • Save akingdom/7697f0153dbaf1c0643a9cd9314b1be7 to your computer and use it in GitHub Desktop.
Save akingdom/7697f0153dbaf1c0643a9cd9314b1be7 to your computer and use it in GitHub Desktop.
Auto-increment the version number in an Android App
// Android build.gradle
// How to auto-increment the version.
// There are many ways to do this - this is only one example. Its downside is that it updates the gradle file (which will ask for a Sync when opened).
// Note that the 10001 (rather than just 1) is ensure there are enough digits to prevent comparison/sorting issues.
//
// By Andrew Kingdom
// MIT license
// (and use at own risk)
//
plugins {
id 'com.android.library'
}
// HERE>
version='1.0.0.10001' // *** Set a varible, which gets updated...
def versionbuild=10001 // *** set a variable, which gets updated...
android {
namespace 'com.example.apps.myappname'
compileSdk 32
defaultConfig {
minSdk 24
targetSdk 32
// HERE>
versionName version // *** version variable
versionCode versionbuild // *** versionbuild variable
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
debug {
minifyEnabled false
// proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
// HERE>
buildConfigField "String", 'LIB_VERSION', '"' + version + '"' // *** version variable
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
// HERE>
buildConfigField "String", 'LIB_VERSION', '"' + version + '"' // *** version variable
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
// (*** no changes here)
dependencies {
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.6.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
// HERE>
// *** Include this code that updates the variable...
task autoincrementversion() {
// dependson can be assemble, assembledebug or assembleRelease
// Auto-increment version...
def v = version
println v
String minor=v.substring(v.lastIndexOf('.')+1) //get last digit
int m=minor.toInteger()+1 //increment
println m
String major=v.substring(0,v.lastIndexOf(".")); //get the beginning
println major
String s=buildFile.getText().replaceFirst("version='$version'","version='"+major+ "." +m+"'").replaceFirst("def versionbuild=$versionbuild","def versionbuild="+m);
println s
buildFile.setText(s) //replace the build file's text
// ... Auto-increment version end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment