Reach the version code and name from a library module
Asked Answered
L

2

7

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?

Laoighis answered 1/10, 2021 at 11:53 Comment(0)
E
7

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

Engle answered 1/10, 2021 at 11:59 Comment(0)
S
8

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 simply access them in any build.gradle via properties object, and add them to BuildConfig like so (note: they will only become available after a successful build):

// build.gradle file of the chosen module
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)
}
Sarmentose answered 10/5, 2022 at 20:17 Comment(0)
E
7

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

Engle answered 1/10, 2021 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.