到目前为止,我发现在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
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
找不到方法 versionCodeMajor() 的参数。
所以,在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
&& !"P".equals(Build.VERSION.CODENAME) ) {
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));
Log.d("AAA", "Version Code (your chosen one) " + (int)(returnValue & 0x00000000ffffffff));
}
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);
Log.d("AAA", "Full long value: " + returnValue);
Log.d("AAA", "Major Version Code (your chosen one) " + majorCode);
Log.d("AAA", "Version Code (your chosen one) " + versionCode);
}
return returnValue;
}
这应该回答了如何使用它或一种方法。
至于何时和为什么使用它...我想这取决于你...正如你指出的那样,文档没有告诉你为什么应该使用它。文档说你应该向用户展示已知的versionNumber版本。
我猜他们添加了一些位到versionCode中,因为他们需要一个更大的数字来进行版本控制^^'
话虽如此,如果您没有在AndroidManifest.xml或build.gradle文件中设置versionCodeMajor(在处理时),或将其设置为0,则此值与旧的已弃用的versionNumber字段相同。