到目前为止,我发现使用 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'
}
}
}
找不到参数的方法 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) {
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;
}
这应该回答如何使用它或如何使用它。
何时以及为什么使用它...我想这取决于您...正如您所指出的,文档没有告诉您为什么应该使用它。什么文档说你应该只向你的用户展示众所周知的版本号。
我猜他们在 versionCode 中添加了更多位,因为他们需要更大的数字来进行版本控制 ^^'
也就是说,如果您没有在AndroidManifest.xml 或build.gradle 文件中设置versionCodeMajor(当它将处理它时),或者您将其设置为0,那么此值与旧的 versionNumber 已弃用的字段。