Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the VERSION_NAME of an application in a method included in a library common to several applications?

I have developed a library to share code that is common to two applications. One of the shared methods is intended to display the VERSION_NAME of the application. This VERSION_NAME is set in the build.gradle file of each application. When I Use BuildConfig.VERSION_NAME in the code of the library method, it returns the version name of the library. How can I reference the variable set into the application gradle file?

like image 898
ema3272 Avatar asked Mar 13 '23 18:03

ema3272


1 Answers

You will not be able to use BuildConfig.VERSION_NAME, because when your library is compiled the consuming application's BuildConfig won't exist.

Instead, you will need to use the package manager to query the current application's version name like so:

public String getCurrentApplicationVersionName(Context context) {
    PackageManager packageManager = context.getPackageManager();
    PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0);
    return info.versionName;
}
like image 113
Bryan Herbst Avatar answered Apr 26 '23 04:04

Bryan Herbst