1. 程式人生 > >如果通過Gradle自動生成各個brand的versionName和VersionCode

如果通過Gradle自動生成各個brand的versionName和VersionCode

在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;
    }