Android 设置和获取APP版本信息

首次发布:2020-10-18 12:41
找到build.gradle 文件,设置版本信息
defaultConfig {
    applicationId "com.example.testapp"
    minSdkVersion 16
    targetSdkVersion 30
    versionCode 1
    versionName "1.01"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
获取版本信息
/*
 * 获取当前程序的版本名
 */
private String getVersionName() {
    PackageManager packageManager = MainActivity.this.getPackageManager();
    PackageInfo packInfo = null;
    try {
        packInfo = packageManager.getPackageInfo( MainActivity.this.getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    Log.e("TAG","版本号"+packInfo.versionCode);
    Log.e("TAG","版本名"+packInfo.versionName);
    return packInfo.versionName;
}