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

我必须使用AndroidManifest.xml吗?


当前回答

对构建系统有用:有一个用APK文件生成的文件,名为output.json,其中包含每个生成的APK文件的一系列信息,包括versionName和versionCode。

例如

[
    {
        "apkInfo": {
            "baseName": "x86-release",
            "enabled": true,
            "filterName": "x86",
            "fullName": "86Release",
            "outputFile": "x86-release-1.0.apk",
            "splits": [
                {
                    "filterType": "ABI",
                    "value": "x86"
                }
            ],
            "type": "FULL_SPLIT",
            "versionCode": 42,
            "versionName": "1.0"
        },
        "outputType": {
            "type": "APK"
        },
        "path": "app-x86-release-1.0.apk",
        "properties": {}
    }
]

其他回答

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

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

与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
                    }
    Log.e("TAG","VERSION.RELEASE {" + Build.VERSION.RELEASE + "}");
    Log.e("TAG","\nVERSION.INCREMENTAL {" + Build.VERSION.INCREMENTAL + "}");
    Log.e("TAG","\nVERSION.SDK {" + Build.VERSION.SDK + "}");
    Log.e("TAG","\nBOARD {" + Build.BOARD + "}");
    Log.e("TAG","\nBRAND {" + Build.BRAND + "}");
    Log.e("TAG","\nDEVICE {" + Build.DEVICE + "}");
    Log.e("TAG","\nFINGERPRINT {" + Build.FINGERPRINT + "}");
    Log.e("TAG","\nHOST {" + Build.HOST + "}");
    Log.e("TAG","\nID {" + Build.ID + "}");

幸亏https://stackoverflow.com/a/40421709/2828651

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

如果要在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" />