Android / Android studio工具 · 2016年9月25日 0

Android 使用Gradle打包APP名称和版本号

需求:我想根据不同的类型,打包不同的版本号,在Android中怎么实现?
例如:release(发布)版本号 1.0.1,debug(测试)版本号1.0.1.20160924
在Android开发中,我们会不断的进行版本打包,打包分为2类:
1、release(正式发布上线版)
2、debug(测试版)。
我们可以通过每次打包前修改build.gradle中android->versionName实现,作为一个程序员,有不断探索的精神,能懒就懒(重复没有意义的工作懒的做)。

    知识介绍
    1、gradle中定义变量和函数 通过关键字 def 来定义
        例如:def versionStr = "1.0.1"  
                   def myFunction() { return "xxxxx" }

    2、gradle中时间使用
          new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC");
          这行代码的意思是“当前时间是UTC时区,已yyyyMMdd格式化时间输出”

    3、gradle中variant.mergedFlavor使用
          variant.mergedFlavor.versionName 表示修改打包时versionName的值

    4、gradle中variant.outputs使用
          variant.outputs表示输出相关配置

   下面是我的build.gradle文件

        apply plugin: 'com.android.application'
        apply plugin: 'android-apt'

//定义时间
def releaseTime() {
   return new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC"))
}

//设置发布的显示的版本号
def getVersionName(){
    return "1.2.0"
}

android {
   compileSdkVersion 23
   buildToolsVersion "24.0.0"

   defaultConfig {
    applicationId "com.xxx.xxxx"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 3
    //versionName getVersionName()
    }
buildTypes {
    debug {
        buildConfigField("boolean","API_DEBUG","true")
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    release {
        buildConfigField("boolean","API_DEBUG","false")
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

//修改打包不能成功配置
lintOptions {
    checkReleaseBuilds false
    abortOnError false
}
//配置自定义打包名称
applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def outputFile = output.outputFile
        def fileName
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
            if (variant.buildType.name.equals('release')) {
                variant.mergedFlavor.versionName = getVersionName()
                fileName = "XXXX_{variant.mergedFlavor.versionName}_release.apk"
            } else if (variant.buildType.name.equals('debug')) {
                variant.mergedFlavor.versionName = getVersionName()+"."+releaseTime()
                fileName = "XXXX_{variant.mergedFlavor.versionName}_debug.apk"
            }
            output.outputFile = new File(outputFile.parent, fileName)
        }
    }
}
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
}
tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

大家可以举一反三
例如想修改versionCode可以这么写
variant.mergedFlavor.versionCode = xxxx;
现在试试吧!

打包输出apk效果图

Paste_Image.png

在应用程序中看效果图

Paste_Image.png

关注公众号获取更多内容和反馈沟通
Paste_Image.png

Share this: