2023-03-06 Android studio java获取当前app版本号(versionCode)和版本名称(versionName)

  • Post author:
  • Post category:java

一、app build.gradle 里面可以设置版本号,versionCode 和versionName 

android {
    namespace 'com.xxx.xxx'
    compileSdk 32

    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRu

二、获取版本号的java 代码

 /**
     * 获取当前app version code
     */
    public static long getAppVersionCode(Context context) {
        long appVersionCode = 0;
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersionCode = packageInfo.getLongVersionCode();
            } else {
                appVersionCode = packageInfo.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("", e.getMessage());
        }
        return appVersionCode;
    }

    /**
     * 获取当前app version name
     */
    public static String getAppVersionName(Context context) {
        String appVersionName = "";
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            appVersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("", e.getMessage());
        }
        return appVersionName;
    }

三、  activity里面调用m_tx_version.setText(“v” + Utils.getAppVersionName(this)) 就可以显示版本号。

四、参考文章

安卓获取当前app版本号(versionCode)和版本名称(versionName) – 简书https://www.jianshu.com/p/337b9e15ed7b


版权声明:本文为qq_37858386原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。