I'm trying to configure the build variants of my application, as part of the migration from Ant to Gradle. The structure I came up with is the following:
main
|-> monkey
I want a way of auto incrementing the version code for the 'monkey' flavour, among other things. I've duplicated the AndroidManifest, so that it resembles the structure below. I've added two version codes and two version names, which I will use to explain the issue I'm facing.
main
|-> AndroidManifest.xml
| -> versionName="mainFlavour"
| -> versionCode=12
monkey
|-> AndroidManifest.xml
| -> versionName="monkeyFlavour"
| -> versionCode=13
FIRST APPROACH
My first try is based on this answer, and consists in defining a task which parses the AndroidManifest file and increments the version code. That task will be a dependency for the generateBuildConfig
task.
The result is that whenever I build with the 'monkey' flavour, reading the version code and version name properties leads to this output:
versionName "monkeyFlavour"
versionCode 12
That is to say, the build has the version name of the 'monkey' flavour, but the version code of the 'main' flavour. There is no difference in using PackageManager
or BuildConfig
to read those values. This is the code I use:
// Increment version code for 'monkey' builds
task('increaseVersionCode') << {
def manifestFile = file("src/monkey/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
manifestFile.write(manifestContent)
}
tasks.whenTaskAdded { task ->
if (task.name == 'generateMonkeyReleaseBuildConfig') {
task.dependsOn 'increaseVersionCode'
}
}
SECOND APPROACH
I then tried an alternative approach, described here, which consists in defining a function that increments the version code of the AndroidManifest file and returns the incremented value. This value is then assigned via the versionCode
property of the 'monkey' flavour.
apply plugin: 'android'
android {
...
productFlavors {
monkey {
versionCode incrementVersionCode()
}
}
...
}
def incrementVersionCode() {
def manifestFile = file("src/monkey/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
manifestFile.write(manifestContent)
return versionCode
}
This approach proved to make me achieve what I wanted. But I would like to understand what's wrong in the first approach. I hope someone will enlighten me.