代码中 AndroidManifest.xml 的用户 versionName 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3637665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:06:28  来源:igfitidea点击:

User versionName value of AndroidManifest.xml in code

androidandroid-manifest

提问by DonGru

The AndroidManifest.xmlcontains the version name of the application, something like

AndroidManifest.xml包含应用程序的版本名称,像

android:versionName="1.0"

Now the question - is it somehow possible to access this version name in the source code, so that I can display it for example in an About Dialog?

现在的问题是 - 是否可以在源代码中以某种方式访问​​此版本名称,以便我可以在例如 About 中显示它Dialog

回答by Konstantin Burov

If you use ADT and Eclipse:

如果您使用 ADT 和 Eclipse:

String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

If you use Gradle, there is an easier way, since it puts the data into BuildConfig for you:

如果您使用 Gradle,则有一种更简单的方法,因为它会为您将数据放入 BuildConfig 中:

String version = BuildConfig.VERSION_NAME;

回答by DMH

Konstantin's answer (above) is correct, but for what it's worth I found that I got a compiler error if I did not catch a NameNotFoundException, as follows:

Konstantin 的回答(以上)是正确的,但值得一提的是,我发现如果我没有捕获 a NameNotFoundException,就会出现编译器错误,如下所示:

import android.content.pm.PackageManager.NameNotFoundException;
try {
    String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
    Log.e("tag", e.getMessage());
}