Problem with Auto-increment VersionCode with Gradle

I am trying to customize my application build options as part of the transition from Ant to Gradle. The structure I came up with is this:

main |-> monkey 

I want, for example, a way to automatically increase the version code for the taste of "monkey". I duplicated AndroidManifest so that it looks like the structure below. I added two version codes and two version names, which I will use to explain the problem I am facing.

 main |-> AndroidManifest.xml | -> versionName="mainFlavour" | -> versionCode=12 monkey |-> AndroidManifest.xml | -> versionName="monkeyFlavour" | -> versionCode=13 

FIRST APPROACH

My first attempt is based on this answer and is to define a task that parses the AndroidManifest file and increments the version code. This task will depend on the generateBuildConfig task.

The result is that whenever I build using the โ€œmonkeyโ€, reading the version code and properties of the version name leads to this conclusion:

  versionName "monkeyFlavour" versionCode 12 

That is, the assembly has the name of the version of "monkey", but the version code of the "main" flavor. There is no difference in using PackageManager or BuildConfig to read these values. This is the code I'm using:

 // 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

Then I tried the alternative approach described here , which is to define a function that increments the version code of the AndroidManifest file and returns an extra value. This value is then assigned using the versionCode property of the versionCode flavor.

 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 helped me achieve what I wanted. But I would like to understand what is wrong in the first approach. Hope someone enlightens me.

+5
source share

Source: https://habr.com/ru/post/1201714/


All Articles