我需要弄清楚如何获取或制作Android应用程序的版本号。我需要在UI中显示内部版本号。

我必须使用AndroidManifest.xml吗?


当前回答

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导入到类中。

其他回答

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

int versionCode = BuildConfig.VERSION_CODE;

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

String versionName = BuildConfig.VERSION_NAME;

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

以下是获取版本代码的方法:

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

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

版本名称:公共字符串getVersionName(){return Application.Context.ApplicationContext.BackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName,0).VersionName;}版本代码:公共字符串getVersionCode(){return Application.Context.ApplicationContext.BackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName,0).VersionCode;}

内部片段用法示例。

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