androidbuild.gradlebuildconfig

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?


Solution

  • 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;
    }