4

I am trying to get the version code of a package compiled in a different project, and linked as a dependency into this one. I make changes to both projects frequently, so I like to know version numbers.

The solutions here: How to get the build/version number of your Android application? shows how to get the version code from context, but that would yield the version code for packages in the current project, not dependent ones.

Here is the code I have tried (3-Scenarios):

public static int getPackageVersion(Context context, Class<?> tClass) {
    int versionCode = 0;

    //#1) Get Package name from class
    String packageName = tClass.getPackage().getName();

    //#2) Set Domain manually to top level package
    //String packageName = "com.somedomain";

    //#3) Get package name from context from this package
    //String packageName = context.getPackageName();

    Log.i(TAG, packageName);

    try {
        versionCode = context.getPackageManager().getPackageInfo(
                packageName, 0).versionCode;
    } catch (PackageManager.NameNotFoundException e) {

        Log.e(TAG, packageName);
        throw new RuntimeException();
    }

    return versionCode;
}

#1) Shows how the method is originally meant to function, it uses the packageName for the class. Results in NameNotFound.

#2) I manually set the top level packageName for the dependent package, which is similar to what context.getPackageName() returns. Results in NameNotFound.

#3) I use context.getPackageName(), and the code returns the version code of packages in this project -- as predicted, but not the result I need.

I have an inelegant hack already, I'm just storing the version number as a field on one of the classes, but a proper solution (if one exists) would be great.

Community
  • 1
  • 1
NameSpace
  • 10,009
  • 3
  • 39
  • 40

1 Answers1

3

A proper solution would be to use the BuildConfig file to store such values (for each project/subproject).
The Android Gradle plugin already contains these fields:

android {
    defaultConfig {
        versionCode 1
        versionName "1.0.0"
    }
}

Then get the field with your.package.name.BuildConfig.VERSION_NAME or your.package.name.BuildConfig.VERSION_CODE

Simon Marquis
  • 7,248
  • 1
  • 28
  • 43
  • Is it yours? Because `BuildConfig.java` is definitely present on aar libs generated with gradle. – Simon Marquis Jan 09 '16 at 20:19
  • You are correct, BuildConfig class is generated in AARs -- that makes it easy. I somehow missed it earlier when I went looking, and assumed it gets stripped out during the build. – NameSpace Jan 10 '16 at 01:34