使用Android Studio 3.0中的发布任务进行Gradle Copy APK文件

时间:2017-06-16 18:52:13

标签: android android-studio gradle android-studio-3.0

在Android插件版本3.0.0-alpha4之前,我一直在使用以下内容将我的APK的不同变体发布到特定的文件路径:

def publish = project.tasks.create("publishAll")
android.applicationVariants.all { variant ->
  def task = project.tasks.create("publish${variant.name}Apk", Copy)
  task.from(variant.outputs[0].outputFile)
  task.into(buildDir)

  task.dependsOn variant.assemble
  publish.dependsOn task
}

我最初是从Xavier Ducrohet的答案中得到的:Copying APK file in Android Gradle project

对于使用版本3.0.0-alpha4的Android Studio Preview的新更新,不推荐使用variant.outputFile。有什么新的建议方法来实现这样的目标?

编辑: 看起来无法按照此处的指示访问变体输出文件:https://developer.android.com/studio/preview/features/new-android-plugin-migration.html#variant_api

看起来我们必须等到他们介绍那些apis

1 个答案:

答案 0 :(得分:5)

如果您不使用abi splits,则下一个代码段

project.afterEvaluate {
    android.applicationVariants.all { variant ->
        // create file where to copy 
        def backupFolder = rootProject.file("backup")
        def backupFile = new File(backupFolder, String.format("%s_v%s.%d.apk", variant.flavorName, variant.versionName, variant.versionCode))

        variant.outputs.all { output ->
            Task copyAndRenameAPKTask = project.task("copyAndRename${variant.name.capitalize()}APK", type: Copy) {
                from output.outputFile.getParent()
                into backupFolder
                include output.outputFileName
                rename(output.outputFileName, backupFile.getName())
            }

            // if copyAndRenameAPKTask needs to automatically execute assemble before
            copyAndRenameAPKTask.dependsOn(variant.assemble)
            copyAndRenameAPKTask.mustRunAfter(variant.assemble)

            // if assemble needs to automatically execute copyAndRenameAPKTask after
            variant.assemble.finalizedBy(copyAndRenameAPKTask)
        }
    }
}