How to define apk output directory when using gradle?

后端 未结 4 763
孤城傲影
孤城傲影 2020-12-08 08:07

How to define apk output directory when using gradle?

I would like to have possibility to upload apk to shared folder after each build.

4条回答
  •  猫巷女王i
    2020-12-08 08:38

    This solution is work for classpath 'com.android.tools.build:gradle:3.1.2' and distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip. Put the following code inside your android scope of app-level build.gradle file. When you use command ./gradlew assembleDebug or ./gradlew assembleRelease, the output folder will be copied to the distFolder.

    // Change all of these based on your requirements
    def archiveBuildTypes = ["release", "debug"];
    def distFolder = "/Users/me/Shared Folder(Personal)/MyApplication/apk/"
    def appName = "MyApplication"
    
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            if (variant.buildType.name in archiveBuildTypes) {
                // Update output filename
                if (variant.versionName != null) {
                    String name = "$appName-${variant.versionName}-${output.baseName}.apk"
                    outputFileName = new File(name)
                }
                def taskSuffix = variant.name.capitalize()
                def assembleTaskName = "assemble${taskSuffix}"
                if (tasks.findByName(assembleTaskName)) {
                    def copyAPKFolderTask = tasks.create(name: "archive${taskSuffix}", type: org.gradle.api.tasks.Copy) {
                        description "Archive/copy APK folder to a shared folder."
                        def sourceFolder = "$buildDir/outputs/apk/${output.baseName.replace("-", "/")}"
                        def destinationFolder = "$distFolder${output.baseName.replace("-", "/")}"
                        print "Copying APK folder from: $sourceFolder into $destinationFolder\n"
                        from(sourceFolder)
                        into destinationFolder
                        eachFile { file ->
                            file.path = file.name // so we have a "flat" copy
                        }
                        includeEmptyDirs = false
                    }
                    tasks[assembleTaskName].finalizedBy = [copyAPKFolderTask]
                }
            }
        }
    }
    

提交回复
热议问题