Skip to content

Instantly share code, notes, and snippets.

@Abhimanyu14
Created September 4, 2022 16:40
Show Gist options
  • Save Abhimanyu14/7c9b06628fdb19be154ceb36c65ee3ba to your computer and use it in GitHub Desktop.
Save Abhimanyu14/7c9b06628fdb19be154ceb36c65ee3ba to your computer and use it in GitHub Desktop.
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
data class AppVersion(
val versionName: String,
val versionNumber: Long,
)
fun getAppVersion(
context: Context,
): AppVersion? {
return try {
val packageManager = context.packageManager
val packageName = context.packageName
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
} else {
packageManager.getPackageInfo(packageName, 0)
}
AppVersion(
versionName = packageInfo.versionName,
versionNumber = packageInfo.longVersionCode,
)
} catch (e: Exception) {
null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment