我想在 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
}
任务在最后运行,但如果测试在多个设备上运行,则此任务不起作用。
然后我创建了为所有正在运行的设备获取 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)
}
}
这是每个设备的“复制”任务:
def copy(String device) {
def copyTask = exec {
executable "${android.getAdbExe().toString()}"
args '-s', item, 'pull', '/sdcard/Pictures/screenshots/.', reportDirectory
}
}
问题是:
任务 fetchScreenshotsForAllDeviceTask 在测试开始时运行,当我将它插入 block 中时:
task.finalizedBy {
// here is my task
}
而如果我把它放在同一个 block 中,“fetchScreenshotsTask”会在最后运行。
最佳答案
任务 fetchScreenshotsForAllDeviceTask(group: 'reporting') 在配置阶段 gradle 生命周期中运行。
要在执行阶段运行此任务,需要在 doLast block 中运行此任务,或在任务中添加“<<”:
task fetchScreenshotsForAllDeviceTask(group: 'reporting') << {
//here is task code
}
关于android - 为什么gradle任务以错误的顺序运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55999313/