Reputation: 1505
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.
BuildConfig.VERSION_NAME
will be fine?Not Working Until Project is Rebuild and Build Folder is recreated
Upvotes: 1
Views: 4550
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)
}
}
binding.tvBuildVersion.text = requireContext().getPackageInfo().versionName
binding.tvBuildVersion.text = getPackageInfo().versionName
Upvotes: 0
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