如果通过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;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值