14

I can programmatically get my app's version name like this:

String versionName = BuildConfig.VERSION_NAME; // 1.0

However, I have a demo app for a library I am making. In my project (since the library and the demo app are in the same project) I use

dependencies {
    implementation project(":mongol-library")
}

In other apps people would import it with

dependencies {
    implementation 'net.studymongolian:mongol-library:0.9.16'
}

In the demo app I would like to include the library's version name rather than the demo app version name. I could hard code the string, of course and update it every time that I updated the library, but that would be error prone. Is there a way to programmatically access a library module's version name?

Related questions

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

14

Use
String libVersionName = your.lib.package.name.BuildConfig.VERSION_NAME;

or in your library, just use BuildConfig.VERSION_NAME to get it.


NB:
BuildConfig.VERSION_NAME in app module is your.app.package.name.BuildConfig.VERSION_NAME

Toris
  • 2,348
  • 13
  • 16
  • This worked very well. In my particular demo app I got the library version name with this: `String versionName = net.studymongolian.mongollibrary.BuildConfig.VERSION_NAME;` – Suragch Dec 15 '17 at 03:09
  • 4
    This will not work if you are using an app module inside your project to test your library module. It will end up returning the versionName from the build.gradle that is associated with your app module and not your library module, even if you specify the package of your library. – Johann Dec 23 '19 at 17:12
0

Somehow the other options with BuildConfig didn't work out for me. I ended up with this code:

context.getPackageManager().getPackageInfo("com.package.name", 0).versionName

For my library "com.package.name" was only the first part of the dependency from build.gradle:

implementation 'com.package.name:library:1.0.0'
mspnr
  • 416
  • 4
  • 12