androidgradleandroid-buildconfig

Access buildConfigField from gradle in Android app


I am building a multi-app project in Android Studio and use Gradle for my versioning.

I use

versionName "1.0"
versionCode 2
versionNameSuffix = ".alpha1"

I also use

def getDate() {
    new Date().format('yyyyMMddHHmmss')
}

and

buildConfigField 'String', 'BUILD_DATE', '\"' + getDate() + '\"'

and all works well.

I can access those though code using

String vN = BuildConfig.versionName;
int vC = BuildConfig.versionCode;
String bD = BuildConfig.BUILD_DATE;

One problem I am having is that I sometimes need to access this information from another application.

I can get versionName and versionCode with

PackageInfo pi = this.getPackageManager().getPackageInfo(packageName, 0);
String vN = pi.versionName;
int vC = pi.versionCode;

is there any way to access BUILD_DATE from another app?


Solution

  • Not readily.

    The simplest approach would be to either switch from buildConfigField to resValue, or to put the same getDate() value in both a buildConfigField and resValue. resValue will let you define a string resource with your date. Then, the app that needs the value can use getPackageManager().getResourcesForApplication() to get a Resources object, from which you can read in the string resource value.

    If the rest of your code can work with the string resource, you could just switch from buildConfigField to resValue. If doing so would be inconvenient, having both the build date in BuildConfig and in a string resource would be a minor bit of data duplication but not a big problem IMHO.