在build.gradle里,我们这样来设置全局变量
import groovy.transform.Field
apply plugin: 'com.android.application'
<strong>String VERSION_NAME = "6.4.1" //全局变量这样来声明的,defaultConfig可以使用,函数里是不可以使用的
int getVersionCode(String str)</strong> {
String[] array = <strong> str.split("\\.").toList()</strong>;
int major = <strong>array[0].toInteger() //如果不调用toInteger结果是错的</strong>
int minor = array[1].toInteger()
int release = array[2].toInteger()
int buildID = 3;
int code = major * 100000000 + minor * 10000000 + release * 100000 + buildID
return code
}
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
def config = defaultConfig {
applicationId "com.example.nickgao.gittest"
minSdkVersion 15
targetSdkVersion 19
versionName <strong>VERSION_NAME</strong>
versionCode <strong>getVersionCode(VERSION_NAME)</strong>
buildConfigField "String", "GIT_REVISION", "\"${gitSha(VERSION_NAME)}\""
}
config
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
def gitSha(String str) {
return getVersionCode('6.5.1')
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
@Field
注意,versionCode只能是int类型,我们可以点击defaultConfig的versionCode
在DefaultProductFlavor里可以看到getter和setter
/**
* Sets the version code. If the value is -1, it is considered not set.
*
* @param versionCode the version code
* @return the flavor object
*/
@NonNull
public ProductFlavor setVersionCode(int versionCode) {
mVersionCode = versionCode;
return this;
}
@Override
public int getVersionCode() {
return mVersionCode;
}
所以versioncode的最大范围是0-2147483648
代码里这样来获取:
public static int getBuildFromPackage(Context context) {
int version = 0;
try {
version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
}
return version;
}