gradle执行打包并导出Apk到指定文件夹

例:build.gradle(:app)配置如下

...

 buildTypes {
        release {
         ...
        }
      
        debug {
          ...
        }
    }


    productFlavors {
        product {
            ...
        }
        
        develop {
            ...
        }
    }
    
    

通过自定义复制Task实现打包并导出到指定文件夹实现如下:

def releaseTime = new Date().format("yyyy-MM-dd_HH-mm", TimeZone.getTimeZone("GMT+8"))
def versionName = android.defaultConfig.versionName

def defaultDestinationPath = rootDir.getAbsolutePath() +
        "${File.separator}package-output${File.separator}"
def defaultNewFileName = "App_${versionName}_${releaseTime}_release.apk"

android.applicationVariants.all { variant ->
     //取正式发布环境
    if ("product" == variant.productFlavors[0].name && "release" == variant.buildType.name) {
        def releaseCollect = project.task('CollectApk', type: Copy)
        String outputApkPath =
                variant.getPackageApplicationProvider().get().outputDirectory.getAsFile().get().getPath() +
                File.separator +
                variant.getPackageApplicationProvider().get().outputScope.getMainSplit().outputFileName
                    
        releaseCollect.doFirst {
            if (!file(defaultDestinationPath).exists()) {
                file(defaultDestinationPath).mkdirs()
            }
        }
        releaseCollect.from(outputApkPath)
        releaseCollect.into(defaultDestinationPath)
        releaseCollect.rename { defaultNewFileName }
        releaseCollect.outputs.file(defaultNewFileName)
        releaseCollect.dependsOn project.tasks.getByName(
                "assemble"
                        + "${variant.productFlavors[0].name.capitalize()}"
                        + "${variant.buildType.name.capitalize()}")

        if (variant.buildType.minifyEnabled) {
            variant.getAssembleProvider().get().doLast {
                copy {
                    from variant.mappingFile
                    into "${defaultDestinationPath}" +
                            "${File.separator}mappings" +
                            "-${android.defaultConfig.versionCode}" +
                            "-${android.defaultConfig.versionName}" +
                            "-$releaseTime"
                    rename { String fileName ->
                        "mapping-${flavorName}.txt"
                    }
                }
            }
        }
    }

}

原文地址:https://www.cnblogs.com/MillerKevin/p/12567609.html