如何获取 Android 应用程序的内部版本号?

发布于 2024-11-19 01:46:01 字数 101 浏览 2 评论 0原文

我需要弄清楚如何获取或创建我的 Android 应用程序的内部版本号。我需要在用户界面中显示内部版本号。

我是否必须对 AndroidManifest.xml 执行某些操作?

I need to figure out how to get or make a build number for my Android application. I need the build number to display in the UI.

Do I have to do something with AndroidManifest.xml?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

左耳近心 2024-11-26 01:46:01

如果您使用 Gradle 插件/Android Studio,自版本 0.7.0< /a>,版本代码和版本名称在 BuildConfig 中静态可用。 确保导入应用程序的包,而不是另一个 BuildConfig

import com.yourpackage.BuildConfig;
...
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

不需要 Context 对象!

另请确保在 build.gradle 文件而不是 AndroidManifest.xml 中指定它们。

defaultConfig {
    versionCode 1
    versionName "1.0"
}

If you're using the Gradle plugin/Android Studio, as of version 0.7.0, version code and version name are available statically in BuildConfig. Make sure you import your app's package, and not another BuildConfig:

import com.yourpackage.BuildConfig;
...
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

No Context object needed!

Also make sure to specify them in your build.gradle file instead of the AndroidManifest.xml.

defaultConfig {
    versionCode 1
    versionName "1.0"
}
嘦怹 2024-11-26 01:46:01

使用:

try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

并且可以通过使用它来获取版本代码

int verCode = pInfo.versionCode;

Use:

try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

And you can get the version code by using this

int verCode = pInfo.versionCode;
飘过的浮云 2024-11-26 01:46:01

如果您只想要版本名称,则版本稍短。

try{
    String versionName = context.getPackageManager()
    .getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
}

Slightly shorter version if you just want the version name.

try{
    String versionName = context.getPackageManager()
    .getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
}
猫烠⑼条掵仅有一顆心 2024-11-26 01:46:01

您需要两个部分:

  • android:versionCode
  • android:versionName

versionCode 是一个数字,您提交到市场的应用程序的每个版本都需要具有比上一个更高的数字。

VersionName 是一个字符串,可以是您想要的任何内容。您可以在此处将应用程序定义为“1.0”或“2.5”或“2 Alpha EXTREME!”或其他什么。

例子:

科特林:

val manager = this.packageManager
val info = manager.getPackageInfo(this.packageName, PackageManager.GET_ACTIVITIES)
toast("PackageName = " + info.packageName + "\nVersionCode = "
            + info.versionCode + "\nVersionName = "
            + info.versionName + "\nPermissions = " + info.permissions)

Java:

PackageManager manager = this.getPackageManager();
PackageInfo info = manager.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
Toast.makeText(this,
     "PackageName = " + info.packageName + "\nVersionCode = "
       + info.versionCode + "\nVersionName = "
       + info.versionName + "\nPermissions = " + info.permissions, Toast.LENGTH_SHORT).show();

There are two parts you need:

  • android:versionCode
  • android:versionName

versionCode is a number, and every version of the app you submit to the market needs to have a higher number than the last.

VersionName is a string and can be anything you want it to be. This is where you define your app as "1.0" or "2.5" or "2 Alpha EXTREME!" or whatever.

Example:

Kotlin:

val manager = this.packageManager
val info = manager.getPackageInfo(this.packageName, PackageManager.GET_ACTIVITIES)
toast("PackageName = " + info.packageName + "\nVersionCode = "
            + info.versionCode + "\nVersionName = "
            + info.versionName + "\nPermissions = " + info.permissions)

Java:

PackageManager manager = this.getPackageManager();
PackageInfo info = manager.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
Toast.makeText(this,
     "PackageName = " + info.packageName + "\nVersionCode = "
       + info.versionCode + "\nVersionName = "
       + info.versionName + "\nPermissions = " + info.permissions, Toast.LENGTH_SHORT).show();
以往的大感动 2024-11-26 01:46:01

使用 Gradle 和 BuildConfig

从 BuildConfig 获取 VERSION_NAME

BuildConfig.VERSION_NAME

是的,现在就这么简单。

它是否为 VERSION_NAME 返回空字符串?

如果您得到的 BuildConfig.VERSION_NAME 为空字符串,请继续阅读。

我一直得到 BuildConfig.VERSION_NAME 的空字符串,因为我没有在我的 Grade 构建文件中设置 versionName (我是从 Ant到摇篮)。因此,以下说明可确保您通过 Gradle 设置 VERSION_NAME

文件 build.gradle

def versionMajor = 3
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // Bump for dogfood builds, public betas, etc.

android {

  defaultConfig {
    versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild

    versionName "${versionMajor}.${versionMinor}.${versionPatch}"
  }

}

注意:这是来自大师 Jake沃顿商学院

AndroidManifest.xml 中删除 versionNameversionCode

因为您已经设置了现在 build.gradle 文件中的 versionNameversionCode,您也可以从 AndroidManifest.xml 文件中删除它们,如果他们在那里的话。

Using Gradle and BuildConfig

Getting the VERSION_NAME from BuildConfig

BuildConfig.VERSION_NAME

Yep, it's that easy now.

Is it returning an empty string for VERSION_NAME?

If you're getting an empty string for BuildConfig.VERSION_NAME then read on.

I kept getting an empty string for BuildConfig.VERSION_NAME, because I wasn't setting the versionName in my Grade build file (I migrated from Ant to Gradle). So, here are instructions for ensuring you're setting your VERSION_NAME via Gradle.

File build.gradle

def versionMajor = 3
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // Bump for dogfood builds, public betas, etc.

android {

  defaultConfig {
    versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild

    versionName "${versionMajor}.${versionMinor}.${versionPatch}"
  }

}

Note: This is from the masterful Jake Wharton.

Removing versionName and versionCode from AndroidManifest.xml

And since you've set the versionName and versionCode in the build.gradle file now, you can also remove them from your AndroidManifest.xml file, if they are there.

这是一个干净的解决方案,基于scottyab 的解决方案(由 Xavi 编辑)。它展示了如何首先获取上下文(如果您的方法未提供)。此外,它使用多行而不是每行调用多个方法。当您必须调试应用程序时,这会让您变得更容易。

Context context = getApplicationContext(); // or activity.getApplicationContext()
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();

String myVersionName = "not available"; // initialize String

try {
    myVersionName = packageManager.getPackageInfo(packageName, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

现在您已收到字符串 myVersionName 中的版本名称,您可以将其设置为 TextView 或您喜欢的任何内容。

// Set the version name to a TextView
TextView tvVersionName = (TextView) findViewById(R.id.tv_versionName);
tvVersionName.setText(myVersionName);

Here is a clean solution, based on the solution of scottyab (edited by Xavi). It shows how to get the context first, if it's not provided by your method. Furthermore, it uses multiple lines instead of calling multiple methods per line. This makes it easier when you have to debug your application.

Context context = getApplicationContext(); // or activity.getApplicationContext()
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();

String myVersionName = "not available"; // initialize String

try {
    myVersionName = packageManager.getPackageInfo(packageName, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

Now that you received the version name in the String myVersionName, you can set it to a TextView or whatever you like..

// Set the version name to a TextView
TextView tvVersionName = (TextView) findViewById(R.id.tv_versionName);
tvVersionName.setText(myVersionName);
妄司 2024-11-26 01:46:01

使用以下命令获取应用程序版本或构建代码,用于通过版本代码识别 APK 文件。版本代码用于检测更新、发布等时的实际构建配置。

int versionCode = BuildConfig.VERSION_CODE;

版本名称用于向用户或开发人员显示开发顺序。您可以根据需要添加任何类型的版本名称。

String versionName = BuildConfig.VERSION_NAME;

Use the following to get the app version or build code which is used to identify the APK file by its version code. The version code is used to detect the actual build configuration at the time of update, publishing, etc.

int versionCode = BuildConfig.VERSION_CODE;

The version name is used to show the users or the developers of the development sequence. You can add any kind of version name as you want.

String versionName = BuildConfig.VERSION_NAME;
冷默言语 2024-11-26 01:46:01

Kotlin 的单行代码

val versionCode = BuildConfig.VERSION_CODE
val versionName = BuildConfig.VERSION_NAME

Java 的单行代码

String versionCode = String.valueOf(BuildConfig.VERSION_CODE);
String versionName = String.valueOf(BuildConfig.VERSION_NAME);

确保将 BuildConfig 导入到您的类中。

Kotlin one-liners

val versionCode = BuildConfig.VERSION_CODE
val versionName = BuildConfig.VERSION_NAME

Java one-liners

String versionCode = String.valueOf(BuildConfig.VERSION_CODE);
String versionName = String.valueOf(BuildConfig.VERSION_NAME);

Make sure to import BuildConfig into your class.

別甾虛僞 2024-11-26 01:46:01

使用 BuildConfig 类:

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

文件 build.gradle (应用程序)

defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 17
    versionName "1.0"
}

Use the BuildConfig class:

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

File build.gradle (app)

defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 17
    versionName "1.0"
}
江挽川 2024-11-26 01:46:01

截至 2020 年:从 API 28 (Android 9 (Pie)) 开始, “versionCode”已弃用,因此我们可以使用“longVersionCode”

Kotlin 中的示例代码

val manager = context?.packageManager
val info = manager?.getPackageInfo(
    context?.packageName, 0
)

val versionName = info?.versionName
val versionNumber = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        info?.longVersionCode
                    } else {
                        info?.versionCode
                    }

As in 2020: As of API 28 (Android 9 (Pie)), "versionCode" is deprecated so we can use "longVersionCode".

Sample code in Kotlin

val manager = context?.packageManager
val info = manager?.getPackageInfo(
    context?.packageName, 0
)

val versionName = info?.versionName
val versionNumber = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        info?.longVersionCode
                    } else {
                        info?.versionCode
                    }
澉约 2024-11-26 01:46:01

这个问题有两种不同的情况,任何答案都没有正确解决。

场景 1:您没有使用模块

如果您没有使用模块,您可以访问您的 BuildConfig 文件并立即获取您的版本代码:

val versionCode = BuildConfig.VERSION_CODE 

这是有效的,因为这是您的应用程序级别的 BuildConfig 文件,因此它将包含对您的应用程序版本代码

场景 2:您的应用程序有许多模块,并且您假装从模块层次结构中较低的模块访问应用程序版本代码

对于您来说,有许多具有给定层次结构的模块是正常的,例如 app -> >数据->域->在这种情况下,如果您从“ui”模块访问 BuildConfig 文件,它不会为您提供应用程序版本代码的引用,而是该模块的版本代码。

为了获取应用程序版本代码,您可以使用以下给定代码:

首先是一个获取 PackageInfo 的扩展函数

@Suppress("DEPRECATION")
fun Context.getPackageInfo(): PackageInfo {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        packageManager.getPackageInfo(packageName, 0)
    }
}

获取版本代码的扩展函数

fun Context.getVersionCode(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    getPackageInfo().longVersionCode.toInt()
} else {
    getPackageInfo().versionCode
}

版本名称的方法类似:

fun Context.getVersionName(): String = try {
    getPackageInfo().versionName
} catch (e: PackageManager.NameNotFoundException) {
    ""
}

There are two different scenarios in this question that are not properly addressed in any of the answers.

Scenario 1: You are not using modules

If you are not making use of modules, you can access your BuildConfig file and immeditally get your version code with:

val versionCode = BuildConfig.VERSION_CODE 

This is valid because this is your app level BuildConfig file and therefor it will contain the reference to your application version code

Scenario 2: Your app has many modules and you pretend to access the application version code from a lower module in your module hierarchy

It is normal for you to have many modules with a given hierarchy such as app -> data -> domain -> ui, etc. In this case, if you access the BuildConfig file from the "ui" module it will not give you a reference to the app version code but to the version code of that module.

In order to get the application version code you can use the following given code:

First an extension function to get the PackageInfo

@Suppress("DEPRECATION")
fun Context.getPackageInfo(): PackageInfo {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        packageManager.getPackageInfo(packageName, 0)
    }
}

Extension function to get the version code

fun Context.getVersionCode(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    getPackageInfo().longVersionCode.toInt()
} else {
    getPackageInfo().versionCode
}

The approach for version name is similar:

fun Context.getVersionName(): String = try {
    getPackageInfo().versionName
} catch (e: PackageManager.NameNotFoundException) {
    ""
}
清秋悲枫 2024-11-26 01:46:01

如果您使用的是 PhoneGap,则创建一个自定义 PhoneGap 插件:

在应用程序包中创建一个新类:

package com.Demo; //replace with your package name

import org.json.JSONArray;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PackageManagerPlugin extends Plugin {

    public final String ACTION_GET_VERSION_NAME = "GetVersionName";

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult result = new PluginResult(Status.INVALID_ACTION);
        PackageManager packageManager = this.ctx.getPackageManager();

        if(action.equals(ACTION_GET_VERSION_NAME)) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(
                                              this.ctx.getPackageName(), 0);
                result = new PluginResult(Status.OK, packageInfo.versionName);
            }
            catch (NameNotFoundException nnfe) {
                result = new PluginResult(Status.ERROR, nnfe.getMessage());
            }
        }

        return result;
    }
}

在 plugins.xml 中,添加以下行:

<plugin name="PackageManagerPlugin" value="com.Demo.PackageManagerPlugin" />

在您的 deviceready事件,添加以下代码:

var PackageManagerPlugin = function() {

};
PackageManagerPlugin.prototype.getVersionName = function(successCallback, failureCallback) {
    return PhoneGap.exec(successCallback, failureCallback, 'PackageManagerPlugin', 'GetVersionName', []);
};
PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin('packageManager', new PackageManagerPlugin());
});

然后,您可以通过以下方式获取versionName属性:

window.plugins.packageManager.getVersionName(
    function(versionName) {
        //do something with versionName
    },
    function(errorMessage) {
        //do something with errorMessage
    }
);

Derived from 此处以及此处

If you're using PhoneGap, then create a custom PhoneGap plugin:

Create a new class in your app's package:

package com.Demo; //replace with your package name

import org.json.JSONArray;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PackageManagerPlugin extends Plugin {

    public final String ACTION_GET_VERSION_NAME = "GetVersionName";

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult result = new PluginResult(Status.INVALID_ACTION);
        PackageManager packageManager = this.ctx.getPackageManager();

        if(action.equals(ACTION_GET_VERSION_NAME)) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(
                                              this.ctx.getPackageName(), 0);
                result = new PluginResult(Status.OK, packageInfo.versionName);
            }
            catch (NameNotFoundException nnfe) {
                result = new PluginResult(Status.ERROR, nnfe.getMessage());
            }
        }

        return result;
    }
}

In the plugins.xml, add the following line:

<plugin name="PackageManagerPlugin" value="com.Demo.PackageManagerPlugin" />

In your deviceready event, add the following code:

var PackageManagerPlugin = function() {

};
PackageManagerPlugin.prototype.getVersionName = function(successCallback, failureCallback) {
    return PhoneGap.exec(successCallback, failureCallback, 'PackageManagerPlugin', 'GetVersionName', []);
};
PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin('packageManager', new PackageManagerPlugin());
});

Then, you can get the versionName attribute by doing:

window.plugins.packageManager.getVersionName(
    function(versionName) {
        //do something with versionName
    },
    function(errorMessage) {
        //do something with errorMessage
    }
);

Derived from here and here.

少跟Wǒ拽 2024-11-26 01:46:01

不,您不需要对 AndroidManifest.xml 执行任何操作

基本上,您应用的版本名称和版本代码位于 应用级 Gradle 文件内的 defaultConfig 标记下:

defaultConfig {
   versionCode 1
   versionName "1.0"
}

< em>注意:当您希望将应用程序上传到Play商店时,可以使用任何名称作为版本名称,但如果该应用程序已在Play商店中,则版本代码必须与当前版本代码不同。< /em>

只需使用以下代码片段即可获取版本代码 &应用中任意位置的版本名称

try {
    PackageInfo pInfo =   context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
    int verCode = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

No, you don't need to do anything with AndroidManifest.xml

Basically, your app's version name and version code are inside the app level Gradle file, under defaultConfig tag:

defaultConfig {
   versionCode 1
   versionName "1.0"
}

Note: When you wish to upload an app to the play store, it can give any name as the version name, but the version code has to be different than the current version code if this app is already in the play store.

Simply use the following code snippet to get the version code & version name from anywhere in your app:

try {
    PackageInfo pInfo =   context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
    int verCode = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
远昼 2024-11-26 01:46:01

对于 API 28 (Android 9 (Pie)),PackageInfo.versionCode已弃用,因此请使用下面的代码:

Context context = getApplicationContext();
PackageManager manager = context.getPackageManager();
try {
    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
    myversionName = info.versionName;
    versionCode = (int) PackageInfoCompat.getLongVersionCode(info);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    myversionName = "Unknown-01";
}

For API 28 (Android 9 (Pie)), the PackageInfo.versionCode is deprecated, so use this code below:

Context context = getApplicationContext();
PackageManager manager = context.getPackageManager();
try {
    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
    myversionName = info.versionName;
    versionCode = (int) PackageInfoCompat.getLongVersionCode(info);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    myversionName = "Unknown-01";
}
驱逐舰岛风号 2024-11-26 01:46:01

版本名称:BuildConfig.VERSION_NAME
版本代码:BuildConfig.VERSION_CODE

Version name: BuildConfig.VERSION_NAME
Version code: BuildConfig.VERSION_CODE

咆哮 2024-11-26 01:46:01

如果您想在 XML 内容上使用它,请在 Gradle 文件中添加以下行:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

然后在 XML 内容上使用它,如下所示:

<TextView
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/versionName" />

If you want to use it on XML content then add the below line in your Gradle file:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

And then use it on your XML content like this:

<TextView
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/versionName" />
╭⌒浅淡时光〆 2024-11-26 01:46:01

对于 Xamarin 用户,请使用此代码获取版本名称和代码

  1. 版本名称:< /p>

     public string getVersionName(){
         返回Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionName;
     }
    
  2. 版本代码:

     public string getVersionCode(){
         返回Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionCode;
     }
    

For Xamarin users, use this code to get version name and code

  1. Version Name:

     public string getVersionName(){
         return Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionName;
     }
    
  2. Version code:

     public string getVersionCode(){
         return Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionCode;
     }
    
爱格式化 2024-11-26 01:46:01

2024 年 5 月
要检索 VERSION_CODE,只需使用 BuildConfig 类,如以下代码:

val versionCode = BuildConfig.VERSION_CODE

请记住,BuildConfig 类是为所有 Android 自动生成的默认情况下使用模块(Gradle 插件 8.0.0+),但是如果您使用较旧版本的插件或在您的项目中使用自定义字段 BuildConfig 类,您需要显式启用模块的 build.gradle 文件中的 BuildConfig。 (就像 compose 项目

要解决在 Jetpack Compose 项目中导入 BuildConfig 的问题,请按照以下步骤操作:

1。在 android 块内的 build.gradle(应用程序模块)中添加以下代码。

 android {
     //....
     buildFeatures {
        //...
        buildConfig = true // add this
        //...
     }
     //....
 }

2。将您的项目与 Gradle 文件(带有向下箭头的大象按钮)同步。此步骤确保构建系统应用更改并生成所需的代码。

3。 (如果问题仍然存在)从“文件”菜单运行“使缓存无效并重新启动”

4。最后,从“构建”菜单运行“重建项目”

⭕ 不要忘记导入 import com.xxx.zzz.BuildConfig (有时 IDE 不会为您执行此操作)

May 2024
To retrieve the VERSION_CODE, simply you can use the BuildConfig class like the following code:

val versionCode = BuildConfig.VERSION_CODE

Just remember, The BuildConfig class is automatically generated for all Android modules by default (Gradle Plugin 8.0.0+), but If you are using an older version of the plugin or using custom fields in your BuildConfig class, you will need to explicitly enable BuildConfig in your module's build.gradle file. (like as compose projects)

To fix the issue of importing BuildConfig in your Jetpack Compose project, follow these steps:

1. Add the below code in the build.gradle(app module) within android block.

 android {
     //....
     buildFeatures {
        //...
        buildConfig = true // add this
        //...
     }
     //....
 }

2. Sync your project with the Gradle files(the elephant button with a down arrow). This step ensures that the build system applies the changes and generates the required code.

3. (If the problem still persists) Run "invalidate cache and restart" from the "File" menu.

4. Finally, Run "Rebuild Project" from the "Build" menu.

⭕ Don't forget to import import com.xxx.zzz.BuildConfig (Sometimes IDE doesn't do it for you)

此刻的回忆 2024-11-26 01:46:01

始终使用 try catch 块来执行此操作:

String versionName = "Version not found";

try {
    versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    Log.i(TAG, "Version Name: " + versionName);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    Log.e(TAG, "Exception Version Name: " + e.getLocalizedMessage());
}

Always do it with a try catch block:

String versionName = "Version not found";

try {
    versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    Log.i(TAG, "Version Name: " + versionName);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    Log.e(TAG, "Exception Version Name: " + e.getLocalizedMessage());
}
原来分手还会想你 2024-11-26 01:46:01

获取版本号的方法如下:

public String getAppVersion() {
    String versionCode = "1.0";
    try {
        versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return versionCode;
}

Here is the method for getting the version code:

public String getAppVersion() {
    String versionCode = "1.0";
    try {
        versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return versionCode;
}
月亮坠入山谷 2024-11-26 01:46:01

我通过使用 Preference 类解决了这个问题。

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

I have solved this by using the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}
空名 2024-11-26 01:46:01

有一些方法可以通过编程方式获取 versionCodeversionName

  1. PackageManager获取版本。这是大多数情况下的最佳方法。

    <前><代码>尝试{
    String versionName = packageManager.getPackageInfo(packageName, 0).versionName;
    int versionCode = packageManager.getPackageInfo(packageName, 0).versionCode;
    } catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    }

  2. 从生成的BuildConfig.java中获取它。但请注意,如果您在库中访问此值,它将返回使用此库的库版本,而不是应用程序版本。因此仅在非库项目中使用!

     String versionName = BuildConfig.VERSION_NAME;
     int versionCode = BuildConfig.VERSION_CODE;
    

除了在库项目中使用第二种方式之外,还有一些细节。在新的 Android Gradle 插件 (3.0.0+) 中,一些 功能已删除。因此,目前,即为不同的口味设置不同的版本无法正常工作。

错误的方式:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.mergedFlavor.versionCode = versionCode
    variant.mergedFlavor.versionName = versionName
}

上面的代码将在 BuildConfig 中正确设置值,但从 PackageManager 您将收到 0null如果您没有在default配置中设置版本。因此,您的应用在设备上将具有 0 版本代码。

有一个解决方法 - 手动设置输出 apk 文件的版本:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.outputs.all { output ->
        output.versionCodeOverride = versionCode
        output.versionNameOverride = versionName
    }
}

There are some ways to get versionCode and versionName programmatically.

  1. Get version from PackageManager. This is the best way for most cases.

     try {
         String versionName = packageManager.getPackageInfo(packageName, 0).versionName;
         int versionCode = packageManager.getPackageInfo(packageName, 0).versionCode;
     } catch (PackageManager.NameNotFoundException e) {
         e.printStackTrace();
     }
    
  2. Get it from generated BuildConfig.java. But notice, that if you'll access this values in library it will return library version, not apps one, that uses this library. So use only in non-library projects!

     String versionName = BuildConfig.VERSION_NAME;
     int versionCode = BuildConfig.VERSION_CODE;
    

There are some details, except of using second way in library project. In new Android Gradle plugin (3.0.0+) some functionalities removed. So, for now, i.e. setting different version for different flavors not working correct.

Incorrect way:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.mergedFlavor.versionCode = versionCode
    variant.mergedFlavor.versionName = versionName
}

Code above will correctly set values in BuildConfig, but from PackageManager you'll receive 0 and null if you didn't set version in default configuration. So your app will have 0 version code on device.

There is a workaround - set version for output apk file manually:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.outputs.all { output ->
        output.versionCodeOverride = versionCode
        output.versionNameOverride = versionName
    }
}
鹿童谣 2024-11-26 01:46:01

上面已经多次提到了这段代码,但这里再次将其全部包含在内。您需要一个 try/catch 块,因为它可能会抛出“NameNotFoundException”。

try {
    String appVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

我希望这能为以后的人简化事情。 :)

This code was mentioned above in pieces, but here it is again all included. You need a try/catch block, because it may throw a "NameNotFoundException".

try {
    String appVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

I hope this simplifies things for someone down the road. :)

無處可尋 2024-11-26 01:46:01

对于不需要应用程序 UI 的 BuildConfig 信息,但想要使用此信息来设置 CI 的人 作业配置或其他,像我一样:

只要你成功构建了项目,在你的项目目录下就会有一个自动生成的文件,BuildConfig.java

{WORKSPACE}/build/ generated/source/buildConfig/{debug|release}/{PACKAGE}/BuildConfig.java

/**
* Automatically generated file. DO NOT MODIFY
*/
package com.XXX.Project;

public final class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String APPLICATION_ID = "com.XXX.Project";
    public static final String BUILD_TYPE = "debug";
    public static final String FLAVOR = "";
    public static final int VERSION_CODE = 1;
    public static final String VERSION_NAME = "1.0.0";
}

通过Python脚本或其他工具分割您需要的信息。这是一个例子:

import subprocess
# Find your BuildConfig.java
_BuildConfig = subprocess.check_output('find {WORKSPACE} -name BuildConfig.java', shell=True).rstrip()

# Get the version name
_Android_version = subprocess.check_output('grep -n "VERSION_NAME" ' + _BuildConfig, shell=True).split('"')[1]
print('Android version: ’ + _Android_version)

For someone who doesn’t need the BuildConfig information for application's UI, however wants to use this information for setting a CI job configuration or others, like me:

There is an automatically generated file, BuildConfig.java, under your project directory as long as you build your project successfully.

{WORKSPACE}/build/generated/source/buildConfig/{debug|release}/{PACKAGE}/BuildConfig.java

/**
* Automatically generated file. DO NOT MODIFY
*/
package com.XXX.Project;

public final class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String APPLICATION_ID = "com.XXX.Project";
    public static final String BUILD_TYPE = "debug";
    public static final String FLAVOR = "";
    public static final int VERSION_CODE = 1;
    public static final String VERSION_NAME = "1.0.0";
}

Split information you need by a Python script or other tools. Here’s an example:

import subprocess
# Find your BuildConfig.java
_BuildConfig = subprocess.check_output('find {WORKSPACE} -name BuildConfig.java', shell=True).rstrip()

# Get the version name
_Android_version = subprocess.check_output('grep -n "VERSION_NAME" ' + _BuildConfig, shell=True).split('"')[1]
print('Android version: ’ + _Android_version)
再见回来 2024-11-26 01:46:01

首先:

import android.content.pm.PackageManager.NameNotFoundException;

然后使用这个:

PackageInfo pInfo = null;
try {
     pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} 
catch (NameNotFoundException e) {
     e.printStackTrace();
}

String versionName = pInfo.versionName;

First:

import android.content.pm.PackageManager.NameNotFoundException;

and then use this:

PackageInfo pInfo = null;
try {
     pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} 
catch (NameNotFoundException e) {
     e.printStackTrace();
}

String versionName = pInfo.versionName;
热风软妹 2024-11-26 01:46:01
package com.sqisland.android.versionview;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textViewversionName = (TextView) findViewById(R.id.text);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        textViewversionName.setText(packageInfo.versionName);

    }
    catch (PackageManager.NameNotFoundException e) {

    }
  }
}
package com.sqisland.android.versionview;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textViewversionName = (TextView) findViewById(R.id.text);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        textViewversionName.setText(packageInfo.versionName);

    }
    catch (PackageManager.NameNotFoundException e) {

    }
  }
}
烦人精 2024-11-26 01:46:01

试试这个:

try
{
    device_version =  getPackageManager().getPackageInfo("com.google.android.gms", 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
    e.printStackTrace();
}

Try this one:

try
{
    device_version =  getPackageManager().getPackageInfo("com.google.android.gms", 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
    e.printStackTrace();
}
我一直都在从未离去 2024-11-26 01:46:01

科特林示例:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.act_signin)

    packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).apply {
        findViewById<TextView>(R.id.text_version_name).text = versionName
        findViewById<TextView>(R.id.text_version_code).text =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "$longVersionCode" else "$versionCode"
    }

    packageManager.getApplicationInfo(packageName, 0).apply{
        findViewById<TextView>(R.id.text_build_date).text =
            SimpleDateFormat("yy-MM-dd hh:mm").format(java.io.File(sourceDir).lastModified())
    }
}

Kotlin example:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.act_signin)

    packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).apply {
        findViewById<TextView>(R.id.text_version_name).text = versionName
        findViewById<TextView>(R.id.text_version_code).text =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "$longVersionCode" else "$versionCode"
    }

    packageManager.getApplicationInfo(packageName, 0).apply{
        findViewById<TextView>(R.id.text_build_date).text =
            SimpleDateFormat("yy-MM-dd hh:mm").format(java.io.File(sourceDir).lastModified())
    }
}
私藏温柔 2024-11-26 01:46:01
private String GetAppVersion() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionName;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

private int GetVersionCode() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionCode;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return -1;
    }
}
private String GetAppVersion() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionName;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

private int GetVersionCode() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionCode;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return -1;
    }
}
巡山小妖精 2024-11-26 01:46:01

内部 Fragment 使用示例。

import android.content.pm.PackageManager;
.......

private String VersionName;
private String VersionCode;
.......


Context context = getActivity().getApplicationContext();

/* Getting application version name and code */
try
{
     VersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

     /* I find it useful to convert vervion code into String,
        so it's ready for TextViev/server side checks
     */

     VersionCode = Integer.toString(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode);
}
catch (PackageManager.NameNotFoundException e)
{
     e.printStackTrace();
}

// Do something useful with that

Example for inside Fragment usage.

import android.content.pm.PackageManager;
.......

private String VersionName;
private String VersionCode;
.......


Context context = getActivity().getApplicationContext();

/* Getting application version name and code */
try
{
     VersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

     /* I find it useful to convert vervion code into String,
        so it's ready for TextViev/server side checks
     */

     VersionCode = Integer.toString(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode);
}
catch (PackageManager.NameNotFoundException e)
{
     e.printStackTrace();
}

// Do something useful with that
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文