为什么 gradle 任务以错误的顺序运行?

Why gradle task runs in wrong order?

我想 运行 在 UI 测试后从 android 设备复制屏幕截图。 我在模块中添加了 build.gradle:

tasks.whenTaskAdded { task ->
    if (task.name == 'connectedMyAppDebugSources') {
        task.finalizedBy {
            // here is my task
        }
    }
}

当我使用这个任务时:

def fetchScreenshotsTask = task('fetchScreenshots', type: Exec, group: 'reporting') {
    executable "${android.getAdbExe().toString()}"
    args 'pull', '/sdcard/Pictures/screenshots/.', reportDirectory
}

任务 运行s 最后,但如果在多个设备上测试 运行,则此任务无效。 然后我创建了为所有 运行ning 设备获取 ID 的任务和 运行 每个设备的另一个复制任务:

task fetchScreenshotsForAllDeviceTask(group: 'reporting') {

String result = ""
new ByteArrayOutputStream().withStream { os ->
    def output = exec {
        executable "${android.getAdbExe().toString()}"
        args 'devices'
        standardOutput = os
    }
    result = os.toString()

}

List list = result.split('\n')
            .collect {it.split('\t').head()}
            .drop(1)

for(String item: list) {
    createDir(item)
    copy(item)
    clear(item)
    }
}

这是每个设备的 "copy" 任务:

def copy(String device) {
    def copyTask = exec {
        executable "${android.getAdbExe().toString()}"
        args '-s', item, 'pull', '/sdcard/Pictures/screenshots/.', reportDirectory
    }
}

问题是: 任务 fetchScreenshotsForAllDeviceTask 运行s 在测试开始时,当我将其插入块时:

 task.finalizedBy {
            // here is my task
        }

而 "fetchScreenshotsTask" 运行 如果我将它放在同一个块中,则在最后。

任务 fetchScreenshotsForAllDeviceTask(group: 'reporting') 运行 处于配置阶段 gradle 生命周期。 要运行这个任务在执行阶段需要运行这个任务在doLast块中,或者在任务中添加“<<”:

task fetchScreenshotsForAllDeviceTask(group: 'reporting') << {
//here is task code
}