Gradle script for copying apk to external path according to build type

This script helps move builded apk to external path i.e Dropbox drive or Google drive.

Here is a gradle script for copying apk according to build type:

def publish = project.tasks.create("archive")
    applicationVariants.all { variant ->
        if ( !project.hasProperty("type") ) {
            return
        }
        if (variant.buildType.name == project.property("type")) {
            println "=> Called archiveCache"
            variant.outputs.each { output ->
                if (output.outputFileName.endsWith('.apk')) {
                    def task = project.tasks.create("archive${variant.name.capitalize()}Apk", Copy)
                    def srcDir = variant.packageApplicationProvider.get().outputDirectory.getAsFile().get()
                    println "=> srcDir=" + srcDir
                    def srcPath = new File(srcDir, output.outputFileName)
                    println "=> srcPath=" + srcPath

                    task.from(srcPath)

                    def outputFolder = localProperties.getProperty("archiveFolderPath", "") + parent.name + "/" + new Date().format('yyyy-MM-dd-HH_mm_ss') + "/"
                    println "=> outputFolder=" + outputFolder

                    task.into(outputFolder)
                    task.dependsOn variant.assembleProvider.get()
                    publish.dependsOn task
                }
            }
        }
    }

Console usage:

./gradlew archive -Ptype=debug (or release or any other build type)

Output path “archiveFolderPath” was declared in: local.properties file as below:

archiveFolderPath=/path/folder/destination/

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :