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.