你如何获取你的Android应用程序的构建/版本号?

1574
我需要弄清楚如何为我的Android应用程序获取或生成一个版本号。我需要在用户界面中显示版本号。
我需要在AndroidManifest.xml文件中做一些操作吗?

1
重复的问题:https://dev59.com/1m855IYBdhLWcg3wNhd1 - Idemax
37
获取版本号使用int versionCode = BuildConfig.VERSION_CODE;,获取版本名使用String versionName = BuildConfig.VERSION_NAME; - Lukas
39个回答

9

我通过使用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);
        }
    }
}

这里的Preference的目的是什么?PackageManager在没有它的情况下也可以工作。 - The incredible Jan

8

这段代码在之前已经被提到过,但现在将其整合在一起展示。你需要使用try/catch块,因为它可能会抛出"NameNotFoundException"异常。

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

我希望这可以为后来的某个人简化事情。 :)

你可以选择抛出异常而不是使用try/catch。 - The incredible Jan

5

对于不需要应用程序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)

4
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) {

    }
  }
}

嗨,@donmj。如果您正在使用非官方的Android设备根目录,我认为您会需要这个。这是我的方法。 - Durul Dalkanat
感谢@Durul Dalkanat的帮助:) - donmj
需要解释一下。 - Peter Mortensen

4

首先:

import android.content.pm.PackageManager.NameNotFoundException;

然后使用这个:
PackageInfo pInfo = null;
try {
     pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} 
catch (NameNotFoundException e) {
     e.printStackTrace();
}

String versionName = pInfo.versionName;

4

Kotlin示例:

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())
    }
}

谢谢你,Alexander!去年我在一个项目中使用了旧的BuildConfig代码,但现在它已经不再起作用了,所以我改用了你的代码。非常好用。 - Zonker.in.Geneva

4
尝试这个:

试一试:

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

3
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;
    }
}

需要解释一下。 - Peter Mortensen

3

内部 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

在发布您的答案之前,您应该查看其他答案。例如,如果您正在片段中执行getActivity.getApplicationContext,则需要上下文,但如果您在活动中,则我认为您不需要调用getActivity。 - Sahil Manchanda
在我的情况下,我为Fragment创建了这个。代码在onCreate中使用。 - Sapphire91140
如果您在Fragment中使用它,为什么不直接使用getContext()呢? - The incredible Jan

2

我需要获取应用程序的版本代码并检查是否已更新,如果是,则需要启动Play商店以获取更新版本。我是这样做的。

public class CheckForUpdate {

    public static final String ACTION_APP_VERSION_CHECK = "app-version-check";

    public static void launchPlayStoreApp(Context context)
    {
        // getPackageName() from Context or Activity object
        final String appPackageName = context.getPackageName();
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("market://details?id=" + appPackageName)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("https://play.google.com/store/apps/details?id=" +
                                             appPackageName)));
        }
    }

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

然后,我创建了一个工具类,使用SharedPreference保存版本代码。
public class PreferenceUtils {

    // This is for version code
    private  final String APP_VERSION_CODE = "APP_VERSION_CODE";
    private  SharedPreferences sharedPreferencesAppVersionCode;
    private SharedPreferences.Editor editorAppVersionCode;
    private static Context mContext;

    public PreferenceUtils(Context context)
    {
        this.mContext = context;
        // This is for the app versioncode
        sharedPreferencesAppVersionCode = mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
        editorAppVersionCode = sharedPreferencesAppVersionCode.edit();
    }

    public void createAppVersionCode(int versionCode) {

        editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
        editorAppVersionCode.apply();
    }

    public int getAppVersionCode()
    {
        return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // As the default version code is 0
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接