我刚刚发现PackageInfo.versionCode
在Android Pie中被弃用了。他们指出你改用PackageInfo.getLongVersionCode()
。这个新方法的JavaDoc是:
返回
versionCode
和versionCodeMajor
组合为单个多整型值。versionCodeMajor
位于上部 32 位。
但什么是versionCodeMajor
?我必须如何使用它?versionCodeMajor
和旧versionCode
有什么区别?
它的文档几乎没有说什么:
内部主要版本代码。这本质上是基本版本代码的额外高位;它没有其他含义,只是数字越高是最近的。这不是通常向用户显示的版本号,通常随 R.attr.versionName 一起提供。
到目前为止,我发现使用Android Studio 3.2.1设置versionCodeMajor
的唯一方法是通过AndroidManifest.xml
并禁用InstantRun。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:versionCodeMajor="8" [...]
'因为将其设置在你得到build.gradle
文件中
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.xxx.myapplicationp"
minSdkVersion 'P'
targetSdkVersion 'P'
versionCode 127
//versionCodeMajor 8
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
找不到参数的方法版本代码专业((
因此,在AndroidManifest.xml
中设置您选择的主要版本代码号并禁用InstantRun后,您可以通过以下方式获得它:
static long getAppVersionCode(Context context) throws PackageManager.NameNotFoundException {
PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
long returnValue = Long.MAX_VALUE;
//if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P
&& !"P".equals(Build.VERSION.CODENAME) /* This 'cause the dev preview */) {
returnValue = pinfo.versionCode;
} else {
returnValue = pinfo.getLongVersionCode();
Log.d("AAA", "Full long value: " + returnValue);
Log.d("AAA", "Major Version Code (your chosen one) " + (returnValue >> 32)); // 8 in this scenario
Log.d("AAA", "Version Code (your chosen one) " + (int)(returnValue & 0x00000000ffffffff)); // 127 in this scenario
}
return returnValue;
}
或者你可以像这样使用PackageInfoCompat:
static long getAppVersionCode(Context context) throws PackageManager.NameNotFoundException {
PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
long returnValue = Long.MAX_VALUE;
returnValue = PackageInfoCompat.getLongVersionCode(pinfo);
if (BuildConfig.DEBUG) {
int majorCode = (int)(returnValue >> 32);
int versionCode = (int)(returnValue & 0x00000000ffffffff); // or simply returnValue
Log.d("AAA", "Full long value: " + returnValue);
Log.d("AAA", "Major Version Code (your chosen one) " + majorCode); // 8 in this scenario
Log.d("AAA", "Version Code (your chosen one) " + versionCode); // 127 in this scenario
}
return returnValue;
}
这应该回答如何使用它或一种方法。
何时以及为何使用它...我想这取决于你...正如您所指出的,文档没有告诉您为什么要使用它。文档说的是,您应该仅向用户显示众所周知的版本编号。
我猜他们在版本代码中添加了更多位,因为他们的版本控制^^需要更多的数字">
也就是说,如果您没有在AndroidManifest.xml
或build.gradle
文件中设置versionCodeMajor
(当它将处理它时(或将其设置为0
则此值与旧的versionNumber
弃用字段相同。
获取版本名称和版本代码的另一种方法是通过 BuildConfig
BuildConfig.VERSION_CODE
BuildConfig.VERSION_NAME