在 Android studio 中 配置Gradle 做到 “根据命令行提示符生成指定versionCode, versionName,指定apk的打包输出路径”

需求:

  1. 使用 Android studio ,使用 gradle 进行构建

  2. 在实际开发中,我们需要使用jenkins进行打包。就需要配置我们的 gradle 脚本以支持参数化的方式。

  3. 想获得一个可配置打包脚本的方法,允许 配置人员根据需要修改 服务器地址,versionCode, versionName 等

  4. 隔离的源代码的配置,使用者在 jenkins里进行配置。

概述:

先展示我配置好的 参数,可以在命令提示行下执行,如下:

gradle assembleBeta -PVERSION_CODE_PARA=101 -PVERSION_NAME_PARA=fd21.0 -POUT_PUT_DIR_PARA=/Users/zhangyunfei/Desktop/yyy -PAPI_HOST_USER_PARA=http://10.0.1.245:9000 -PAPI_HOST_CABZOO_PARA=http://10.0.1.245:9002 -POUT_PUT_APK_SUFFIX_PARA=245
参数说明:
  1. assembleBeta 其中 Beta是我配置好的 构建任务,
  2. -P标示后面跟的内容是参数,比如:
    -PVERSION_CODE_PARA=101 表示  传入一个 VERSION_CODE_PARA 参数,它的值是 101

这里的参数都是自定义的,我在这里参入了多个参数,有 versionName,versionCode ,输入文件路径,和 指定的服务器地址。


实现:

修改versionCode和 versionName

上面的演示中,我们传入了gradle的参数,如何在gradle中使用呢? 下面是我配置 versionCode和 versionName 的代码,示例如下:
defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
        signingConfig signingConfigs.debug
        buildConfigField("String", "API_HOST_USER", ""http://10.0.1.232:9000"")
        buildConfigField("String", "API_HOST_CABZOO", ""http://10.0.1.232:9002"")
        buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "true")
        if (project.hasProperty('VERSION_CODE_PARA')) {
            versionCode Integer.parseInt(VERSION_CODE_PARA)
        }
        if (project.hasProperty('VERSION_NAME_PARA')) {
            versionName VERSION_NAME_PARA
        }
    }
我们需要配置 defaultConfig 节点,读取上面传入的参数的值作为 versionCode或者 versionName。在读取参数的时候,我们先检查参数是否存在,使用代码: 
  project.hasProperty('参数名') 
所有通过命令行传入的参数都或作为 project 内建对象的属性,我们这里判断了 指定的参数名 是否存在。如何使用参数呢?直接使用即可,比如下面:
  
   versionCode Integer.parseInt(VERSION_CODE_PARA)    注意这里,进行了 转型,从字符串转型为 int 类型
   versionName VERSION_NAME_PARA 

和普通的变量使用方法是一样的。我们还会遇到在 字符串中使用的时候,可以使用 表达式 来引用,比如:
   ${参数名}
示例:
  fileName = fileName.replace(".apk", "-${android.defaultConfig.versionName}.apk")

明白了变量(属性,参数)的读取方式,我们就可以像普通代码那样编码了。我们继续回到我们的主题行来。我们需要 在 buildTypes 节点(任务)
下,添加一个 自定义的打包方式,比如 名称叫做 beta 的配置。beta 是我自定义的,在开头我们见过这个参数的使用,在 “gradle
assembleBeta ” 中的Beta就会调用这个我们配置好的任务,演示代码如下:
if (project.hasProperty('API_HOST_USER_PARA') && project.hasProperty('API_HOST_CABZOO_PARA')) {

            beta {
                debuggable true
                signingConfig signingConfigs.debug
                minifyEnabled false
                buildConfigField("String", "API_HOST_USER", """ + API_HOST_USER_PARA + """)
                buildConfigField("String", "API_HOST_CABZOO", """ + API_HOST_CABZOO_PARA + """)
                buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "false")
            }
        }

控制输出的APK的 名称和存放路径

我们继续配置 apk 输出 的目录的配置,这就需要获得 编译完成后的文件名称的配置,如何获得和设置输入路径呢?代码如下: 

android.applicationVariants.all { variant ->

    variant.outputs.each { output ->{
         .......
    }
}

我想在输出的 apk 文件名中添加 版本名称(versionName),写下代码:

if (android.defaultConfig.versionName != null) {
                fileName = fileName.replace(".apk", "-${android.defaultConfig.versionName}.apk")
            }

为输入的apk文件名增加指定的后缀

if (project.hasProperty('OUT_PUT_APK_SUFFIX_PARA')) {
                fileName = fileName.replace(".apk", "-${OUT_PUT_APK_SUFFIX_PARA}.apk")
            }

为输出的apk文件名增加 当前日期 部分

def today = new Date().format('yyMMddHHmm');
            fileName = fileName.replace(".apk", "-${today}.apk")

我还想指定 apk的存放 目录:

if (project.hasProperty('OUT_PUT_DIR_PARA')) {
                File output_dir1 = file("${OUT_PUT_DIR_PARA}");
                output.outputFile = new File(output_dir1, fileName)
                println "输出文件位置: " + output.outputFile
                //}
            } 

这部分的示例代码如下:

android.applicationVariants.all { variant ->

    variant.outputs.each { output ->
        def outputFile = output.outputFile
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
            def fileName = outputFile.name;
            if (android.defaultConfig.versionName != null) {
                fileName = fileName.replace(".apk", "-${android.defaultConfig.versionName}.apk")
            }
            if (project.hasProperty('OUT_PUT_APK_SUFFIX_PARA')) {
                fileName = fileName.replace(".apk", "-${OUT_PUT_APK_SUFFIX_PARA}.apk")
            }
            def today = new Date().format('yyMMddHHmm');
            fileName = fileName.replace(".apk", "-${today}.apk")
            if (project.hasProperty('OUT_PUT_DIR_PARA')) {
                File output_dir1 = file("${OUT_PUT_DIR_PARA}");
                output.outputFile = new File(output_dir1, fileName)
                println "输出文件位置: " + output.outputFile
                //}
            } else {
                output.outputFile = new File(outputFile.parent, fileName)
                println "输出文件位置: " + output.outputFile
            }
        }
    }
}
我的整个gradle 脚本,build.gradle 文件如下:

apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':jlb_common')
    compile project(':JlbLibUmeng')
    compile project(':zyf.util.bluetoothprinter')
}


android {
    signingConfigs {
        release {
            keyAlias 'jlb.scanner.apk'
            keyPassword ' '
            storeFile file(' ')
            storePassword ' '
        }
        debug {
            keyAlias 'androiddebugkey'
            keyPassword ' '
            storeFile file(' ')
            storePassword ' '
        }
    }
    compileSdkVersion 19
    buildToolsVersion "22.0.1"
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            buildConfigField("String", "API_HOST_USER", ""http://10.0.1.232:9000"")
            buildConfigField("String", "API_HOST_CABZOO", ""http://10.0.1.232:9002"")
            buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "false")
        }
        release {
            minifyEnabled true
            // 混淆文件的位置
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
            signingConfig signingConfigs.release
            buildConfigField("String", "API_HOST_USER", ""http://uc.jinlinbao.com"")
            buildConfigField("String", "API_HOST_CABZOO", ""http://cabzoo.jinlinbao.com"")
            buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "true")
        }
//        product_245 {
//            debuggable true
//            signingConfig signingConfigs.debug
//            minifyEnabled false
//            buildConfigField("String", "API_HOST_USER", ""http://10.0.1.245:9000"")
//            buildConfigField("String", "API_HOST_CABZOO", ""http://10.0.1.245:9002"")
//        }
        if (project.hasProperty('API_HOST_USER_PARA') && project.hasProperty('API_HOST_CABZOO_PARA')) {

            beta {
                debuggable true
                signingConfig signingConfigs.debug
                minifyEnabled false
                buildConfigField("String", "API_HOST_USER", """ + API_HOST_USER_PARA + """)
                buildConfigField("String", "API_HOST_CABZOO", """ + API_HOST_CABZOO_PARA + """)
                buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "false")
            }
        }
    }
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
        signingConfig signingConfigs.debug
        buildConfigField("String", "API_HOST_USER", ""http://10.0.1.232:9000"")
        buildConfigField("String", "API_HOST_CABZOO", ""http://10.0.1.232:9002"")
        buildConfigField("Boolean", "IS_CHECK_VERSION_UPDATE", "true")
        if (project.hasProperty('VERSION_CODE_PARA')) {
            versionCode Integer.parseInt(VERSION_CODE_PARA)
        }
        if (project.hasProperty('VERSION_NAME_PARA')) {
            versionName VERSION_NAME_PARA
        }
    }
    productFlavors {
    }
}

android {
    lintOptions {
        abortOnError false
    }
}

android.applicationVariants.all { variant ->

    variant.outputs.each { output ->
        def outputFile = output.outputFile
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
            def fileName = outputFile.name;
            if (android.defaultConfig.versionName != null) {
                fileName = fileName.replace(".apk", "-${android.defaultConfig.versionName}.apk")
            }
            if (project.hasProperty('OUT_PUT_APK_SUFFIX_PARA')) {
                fileName = fileName.replace(".apk", "-${OUT_PUT_APK_SUFFIX_PARA}.apk")
            }
            def today = new Date().format('yyMMddHHmm');
            fileName = fileName.replace(".apk", "-${today}.apk")
            if (project.hasProperty('OUT_PUT_DIR_PARA')) {
                File output_dir1 = file("${OUT_PUT_DIR_PARA}");
                output.outputFile = new File(output_dir1, fileName)
                println "输出文件位置: " + output.outputFile
                //}
            } else {
                output.outputFile = new File(outputFile.parent, fileName)
                println "输出文件位置: " + output.outputFile
            }
        }
    }
}


原文地址:https://www.cnblogs.com/xinmengwuheng/p/5955639.html