Changing app version without a Gradle sync

Raymond Chan
1 min readJul 1, 2023

--

Every time you would like to test for app upgrade during development, you need to change the versionCode on Android Studio and then followed by a Gradle sync before you can build. That is time consuming right?

Here is a little trick that we used in our company’s project, it is actually simple:

  1. Create a file called version.txt in your project folder. It only contains a semver string like this: 1.0.0
  2. Create a method in your build.gradle(.kts) that read version.txt to calculate your version code dynamically.
val getVersionCodeAndName: () -> Pair<Int, String> = {
val versionString = file("version.txt").readText()
val versionArray = versionString.split(".")

val versionMajor = versionArray[0].toInt()
val versionMinor = versionArray[1].toInt()
val versionPatch = versionArray[2].toInt()

val versionCode = versionMajor * 10000000 + versionMinor * 10000 + versionPatch * 100
val versionName = "$versionMajor.$versionMinor.$versionPatch"

versionCode to versionName
}

3. Now things are simple, simply call getVerisonCodeAndName to retrieve versionCode and versionName like this

defaultConfig {
versionCode = getVersionCodeAndName().first
versionName = getVersionCodeAndName().second
}

You can then modify version.txt to any app version you want!

--

--

Raymond Chan

Hello World Engineer @9GAG #android #Hongkonger #StandWithHongKong