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

我必须使用AndroidManifest.xml吗?


当前回答

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

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

其他回答

这是一个干净的解决方案,基于scottyab(由哈维编辑)的解决方案。它显示了如果方法没有提供上下文,如何首先获取上下文。此外,它使用多行而不是每行调用多个方法。这使您在调试应用程序时更容易。

Context context = getApplicationContext(); // or activity.getApplicationContext()
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();

String myVersionName = "not available"; // initialize String

try {
    myVersionName = packageManager.getPackageInfo(packageName, 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

现在您在StringmyVersionName中收到了版本名,您可以将其设置为TextView或任何您喜欢的内容。。

// Set the version name to a TextView
TextView tvVersionName = (TextView) findViewById(R.id.tv_versionName);
tvVersionName.setText(myVersionName);

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

试试这个:

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

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

非常简单:

   val manufacturer = Build.MANUFACTURER
   val model = Build.MODEL
   val version = Build.VERSION.SDK_INT
   val versionRelease = Build.VERSION.RELEASE