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

我必须使用AndroidManifest.xml吗?


当前回答

使用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"
}

其他回答

您需要两个部分:

android:版本代码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();

如果您只需要版本名称,请稍微缩短版本。

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

这段代码在上面提到过,但在这里,它再次全部包含在内。您需要try/catch块,因为它可能引发“NameNotFoundException”。

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

我希望这能为将来的人简化事情

试试这个:

try
{
    device_version =  getPackageManager().getPackageInfo("com.google.android.gms", 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
    e.printStackTrace();
}
    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