應用版本號是用戶感知更新、崩溃上報標識版本、服務端接口兼容性判斷的關鍵信息。在 Android 中,版本號定義於 AndroidManifest.xml 的 versionName 屬性,通過 PackageManager API 獲取。本文提供標準獲取代碼、異常處理、緩存優化及現代化封裝方案。
PackageInfo.versionName(字符串,如 "1.2.3")PackageInfo.versionCode(整數,如 10203,用於升級判斷)/**
* 獲取當前應用版本號
* @return 版本號字符串,失敗時返回 "Unknown"
*/
public String getAppVersionName() {
try {
PackageManager pm = getPackageManager();
PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
return pi.versionName;
} catch (PackageManager.NameNotFoundException e) {
Log.e("VersionUtil", "Package not found", e);
return "Unknown";
}
}
/**
* 獲取版本碼(用於版本比較)
*/
public int getAppVersionCode() {
try {
return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
return -1;
}
}
public class VersionUtil {
private static final String TAG = "VersionUtil";
private static VersionUtil instance;
private String cachedVersionName;
private int cachedVersionCode;
private boolean initialized = false;
private VersionUtil() {}
public static VersionUtil getInstance() {
if (instance == null) {
synchronized (VersionUtil.class) {
if (instance == null) instance = new VersionUtil();
}
}
return instance;
}
public synchronized void init(Context context) {
if (initialized) return;
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
cachedVersionName = info.versionName;
cachedVersionCode = info.versionCode;
initialized = true;
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Init failed", e);
cachedVersionName = "Unknown";
cachedVersionCode = -1;
}
}
public String getVersionName() {
return initialized ? cachedVersionName : "Unknown";
}
public int getVersionCode() {
return initialized ? cachedVersionCode : -1;
}
/** 版本比較:當前版本是否大於指定版本 */
public boolean isNewerThan(int targetVersionCode) {
return getVersionCode() > targetVersionCode;
}
/** 版本比較:語義化版本號比較 (支持 "1.2.3" 格式) */
public boolean isNewerThan(String targetVersionName) {
return compareVersionNames(getVersionName(), targetVersionName) > 0;
}
private int compareVersionNames(String v1, String v2) {
String[] parts1 = v1.split("\\.");
String[] parts2 = v2.split("\\.");
int len = Math.max(parts1.length, parts2.length);
for (int i = 0; i < len; i++) {
int n1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
int n2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
if (n1 != n2) return Integer.compare(n1, n2);
}
return 0;
}
}
// 在 Activity/Fragment 中
TextView tvVersion = findViewById(R.id.tv_version);
tvVersion.setText(String.format("版本: v%s (Build %d)",
VersionUtil.getInstance().getVersionName(),
VersionUtil.getInstance().getVersionCode()));
// SplashActivity 或 MainActivity onCreate 中
VersionUtil.getInstance().init(this);
int localVersionCode = VersionUtil.getInstance().getVersionCode();
// 請求服務端最新版本信息
ApiService.getLatestVersion(new Callback() {
@Override
public void onResponse(VersionInfo serverInfo) {
if (serverInfo.versionCode > localVersionCode) {
showUpdateDialog(serverInfo); // 彈出更新提示
}
}
});
// 自定義 UncaughtExceptionHandler
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
String version = VersionUtil.getInstance().getVersionName();
int versionCode = VersionUtil.getInstance().getVersionCode();
// 上報至崩溃收集平台(Bugly、Sentry、Firebase Crashlytics)
CrashReporter.report(throwable, version, versionCode);
});
避免硬編碼,在 build.gradle 中統一管理:
android {
defaultConfig {
versionCode 1020300 // 1.2.3 -> 1020300
versionName "1.2.3"
}
}
// 構建時自動生成 BuildConfig.VERSION_NAME / VERSION_CODE
// 代碼中直接引用:BuildConfig.VERSION_NAME
| 問題 | 原因 | 解決方案 |
|---|---|---|
| getPackageInfo 拋 NameNotFoundException | 包名錯誤、應用未安裝、多進程調用 | 使用 getPackageName() 獲取當前包名,確保在主進程初始化 |
| 版本號顯示 "Unknown" | 異常未捕獲、上下文非 Application/Activity | 傳入 Application Context,完善異常處理與日誌 |
| 版本比較邏輯錯誤 | 直接字符串比較 "1.10" < "1.2" | 解析為整數數組逐位比較,或統一使用 versionCode |
| 頻繁調用導致性能抖動 | 每次 IPC 通信開銷 | 單例緩存、Application onCreate 時預初始化 |
版本號管理看似簡單,但貫穿應用全生命週期。建立統一的 VersionUtil,配合 Gradle 自動化構建、服務端版本管理平台、崩溃分析系統,能顯著提升發布效率與問題排查速度。