package com.block.android
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.os.Build
import androidx.core.content.pm.PackageInfoCompat
fun Context.getVersionName(): String {
return try {
getInfo().versionName
} catch (e: NameNotFoundException) {
""
}
}
fun Context.getVersionCode(): Int {
return try {
getInfo().versionCode
} catch (e: NameNotFoundException) {
0
}
}
fun Context.getVersionCodeLong(): Long {
return try {
PackageInfoCompat.getLongVersionCode(getInfo())
} catch (e: NameNotFoundException) {
0L
}
}
private fun Context.getInfo(): PackageInfo {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
} else {
packageManager.getPackageInfo(packageName, 0)
}
}
小记
- Android 33 进一步规范了
getPackageInfo
参数,只接收 0 和 PackageInfoFlags 中的值 - Android 28 引入了主版本
versionCodeMajor
, 只支持在 AndroidManifest 文件中配置。可以扩大 VersionCode 的值,一般情况下用不到。
资料
PackageInfoFlags