gradle3.0之后Android自定义输出APK名称的正确方式

升级gradle到3.0.1的时候,app.gradle报了如下错误:Cannot set the value of read-only property ‘outputFile’ for ApkVariantOutputImpl_Decorated,即outputFile只是可读的,这是我的代码是:

                applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def outputFile = output.outputFile
                    def fileName
                    if (outputFile != null && outputFile.name.endsWith('.apk')) {
                        // 输出apk名称为XXapp1.4.0_2017-02-14.apk
                        if (variant.buildType.name.equals('release')) {
                            fileName = "XXapp${defaultConfig.versionName}_${releaseTime()}.apk"
                        } else if (variant.buildType.name.equals('debug')) {
                            fileName = "XXapp${defaultConfig.versionName}_${releaseTime()}_debug.apk"
                        }
                        output.outputFile = new File(outputFile.parent, fileName)
                    }
                }
            }

查阅资料后得知:
Android plugin 3.0 建议使用

Use all() instead of each()
Use outputFileName instead of output.outputFile if you change only file name (that is your case)

 //配置自定义打包名称
    applicationVariants.all { variant ->
        variant.outputs.all {
            def fileName
            def date = new Date()
            def formattedDate = date.format('yyyyMMdd')
                if (variant.buildType.name.equals('release')) {
                    fileName = "${variant.mergedFlavor.versionName}_release_${formattedDate}.apk"
                } else if (variant.buildType.name.equals('debug')) {
                    fileName = "${variant.mergedFlavor.versionName}_debug_${formattedDate}.apk"
                }
                outputFileName = fileName;
        }
    }

你可能感兴趣的:(Android)