android studio 3.0 gradle 打包脚本配置

3,877 阅读1分钟

修改输出的名字 保存输出的文件路径

def fileArray = []
//遍历输出文件    
android.applicationVariants.all { variant ->
    variant.outputs.all { output ->
        def outputFile = output.outputFile
        if (outputFile != null && outputFile.name.endsWith('release.apk')) {
            def fileName = "xxx_${defaultConfig.versionName}_${defaultConfig.versionCode}" +
                    "_${variant.productFlavors[0].name}.apk"
            outputFileName = fileName
            //往数组添加输出的文件路径
            fileArray.add(outputFile.parentFile.absolutePath + File.separator + fileName)
        }
    }

通常多渠道打包后需要输出文件 并保存最新的apk在一个文件夹中
build命令编译生成debug和release版本的包
assembleRelease命令只编译生成release版本的包

build {
//build命令加入这段代码
    doLast() {
        //遍历文件数组并进行操作
        forEachFile(fileArray)
    }
}
//assembleRelease命令加入这段代码
afterEvaluate {
    assembleRelease.doLast {
        //遍历文件数组并进行操作
        forEachFile(fileArray)
    }
}
def forEachFile(fileArray) {
    fileArray.forEach { file ->
    //遍历进行文件操作
    rename_andd_moveout_apk(file)
}

}
可以使用copy rename进行文件操作

def rename_andd_moveout_apk(orignalFile) {
    def intoFile = rootDir.parentFile.getAbsolutePath()+File.separator+"apk"
    copy {
        from orignalFile
        into intoCodeFile
        rename("${android.defaultConfig.versionName}_
        ${android.defaultConfig.versionCode}_", "")
       }
    }        

可以通过gradle脚本动态配置Mainfest里面一些第三方配置,这样可以实现DEV和PRD多环境配置切换
使用:android.defaultConfig.manifestPlaceholders=["key":"value"]
在Mainfest使用${key}引用你要使用的第三方配置数据,开发过程中通常应用于个推、环信等多环境的配置

有错误的地方,望大家指正!
t.cn/Rlvl2Zu