Rahul Shyokand
Rahul Shyokand

Reputation: 1505

Is BuildConfig.VERSION_NAME fine to use in Android app to get App version

I needed to use get my app's Version when it launches so I used VERSION_NAME from BuildConfig which works but Is it the right way to get the Version Name of app?

I found that if the app's build folder is removed BuildConfig becomes an undefined or unimported class thus we need to Make Project Again from Build Menu to resolve this issue.

Shall I try other Options to fetch Version Name or BuildConfig.VERSION_NAME will be fine?

Works when Build Folder is Available (As Expected)

enter image description here

enter image description here

Without Build Folder / After Deleting Build Folder

Not Working Until Project is Rebuild and Build Folder is recreated enter image description here

Upvotes: 1

Views: 4550

Answers (2)

Ahmed Goda
Ahmed Goda

Reputation: 113

You Can Use This to Get The Version Name

Extension Function

fun Context.getPackageInfo(): PackageInfo {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        @Suppress("DEPRECATION") packageManager.getPackageInfo(packageName, 0)
    }
}

Fragment

binding.tvBuildVersion.text = requireContext().getPackageInfo().versionName

Activity

binding.tvBuildVersion.text = getPackageInfo().versionName

Upvotes: 0

Ganesh
Ganesh

Reputation: 199

Hi, This is Correct way to get the Version_name, and by way you can also get version code also from same method, so this is correct, what exactly happens is, Gradle allows buildConfigField lines to define constants. These constants will be accessible at runtime as static fields of the BuildConfig class. This can be used to create flavors by defining all fields within the defaultConfig block, then overriding them for individual build flavors as needed.

ALSO alternatively you can have a code something like this,

PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;//Version Name
int verCode = pInfo.versionCode;//Version Code

Upvotes: 8

Related Questions