gpt4 book ai didi

java - 如何以编程方式导致 Android 延迟?

转载 作者:行者123 更新时间:2023-12-01 11:26:23 26 4
gpt4 key购买 nike

我尝试使用Thread.sleep()但它不起作用。当我使用它时,应用程序停止响应。

我需要在我的代码中添加一些延迟,如下所示:

public void inicioJogo(){
for (int jogada = 1; jogada <= 50; jogada++) {
for (int contador = 0; contador < jogada; contador++){
// HERE - Wait 1 sec before go to next line.
btPedra[sequencia[contador]].setBackgroundResource(imagensHover[sequencia[contador]]);
// HERE - Wait 1 sec before go to next line.
btPedra[sequencia[contador]].setBackgroundResource(imagensNormal[sequencia[contador]]);
// Now continue looping.
}
}
}

我尝试使用处理程序,如下所示:

private Handler handler = new Handler();
for (int jogada = 1; jogada <= 50; jogada++) {
for (int contador = 0; contador < jogada; contador++){
handler.postDelayed(new Runnable () {
@Override
public void run() {
btPedra[sequencia[contador]].setBackgroundResource(imagensHover[sequencia[contador]]);
}
}, 1000);
}
}

但是当我使用它时,循环会在等待 1 秒之前继续。我需要一个可以停止循环 1 秒的延迟,转到下一行,然后继续循环。

最佳答案

您可以使用ScheduledExecutorService,例如

ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(NO_OF_THREADS);

ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(task, NO_OF_SECONDS_TO_WAIT, TimeUnit.SECONDS);

现在“任务”在延迟 NO_OF_SECONDS_TO_WAIT 后执行

关于java - 如何以编程方式导致 Android 延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com