'Reach the version code and name from a library module

I'm currently working on modularizing my application, so I'm putting each feature in a library module. In one of my features, I access the version code and name. However, although I defined them in the build.gradle file specific for that module

build.gradle file for the library module

they were not there in the generated BuildConfig file

generated BuildConfig file in the module

I cannot reference the BuildConfig file of the original :app module since I cannot let my feature modules have a dependency on that module.

is there an alternative way of accessing this info from the library module?



Solution 1:[1]

Version code and version name are properties of an application package and they are not supported for a library module.

At runtime, you can pass in a Context and access this application package metadata with the help of PackageManager. Example: Detect my app's own android:versionCode at run time

Solution 2:[2]

While the answer above is okay, IMO it's not the best way to go about it. Generally speaking, you want your version name and code stored somewhere outside of the build.gradle file. Very often we do that so we can easily access it from the outside of the app, or to update it automatically for CI systems, etc.

A very simple example: You can put those in the gradle.properties file, like so:

// add to the end of the file:
VERSION_NAME=0.0.1
VERSION_CODE=1

Then you can then simply access them in build.gradle via properties object, and add them to BuildConfig like so (note: they will only become available after a successful build):

def versionName = properties["VERSION_NAME"]
def versionCode = properties["VERSION_CODE"]
buildTypes.all {
    buildConfigField "String", "VERSION_NAME", "\"$versionName\"" // Escaping quote marks to convert property to String
    buildConfigField "int", "VERSION_CODE", "$versionCode"
}

Alternatively, you can put those in a dedicated version.properties file. Then you can do the same like this:

def versionProps = loadPropertiesFile(project.file('version.properties'))
buildTypes.all {
    buildConfigField "String", "VERSION_NAME", getPropEscaped("VERSION_NAME", versionProps)
    buildConfigField "int", "VERSION_CODE", getProp("VERSION_CODE", versionProps)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 laalto
Solution 2 Serge