返回列表
android #Android开发如何获取gradle中的版本号 #versionName #Android

Android 获取gradle中versionName

FD
Flame Dream
2024年3月15日 1 分钟阅读 0

Android项目中会配置当前APP的版本versionName,其中build.gradle配置如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 33

    defaultConfig {
        applicationId "com.example.myapplication_test"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

实现获取versionName代码如下:

PackageInfo pInfo;
try {
    pInfo = sContext.getPackageManager().getPackageInfo("com.example.xxxx", 0);   // com.example.xxxx 替换成APP的applicationId
    String versionName = pInfo.versionName;
}catch (PackageManager.NameNotFoundException e){

}
        这段代码将获取到当前安装的 APP 的版本号。
分享