我想要实现的是点击后,应用程序显示敬酒消息"TEXT1",并一直显示TEXT1,直到完成其他函数调用20次随机间隔/延迟。调用函数后,显示toast消息"TEXT2"。我的问题:TEXT1不显示,直到应用程序完成函数调用。并且TEXT1保持执行20次函数调用所需的时间,然后TEXT2显示。我的代码:
public void onClick(View v) {
switch (v.getId()) {
case R.id.example:
Toast.makeText(getBaseContext(),"Please wait until finish",Toast.LENGTH_SHORT).show();
int i = 0;
while (i <= 19 ){
int delay = new Random().nextInt(5000);
try {
Thread.sleep(delay);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
//some function here
i++;
}
Toast.makeText(getBaseContext(),"Finished",Toast.LENGTH_SHORT).show();
break;
}
}
}
永远不要阻塞UI线程!
所有用户界面操作都在UI线程中处理。如果用Thread.sleep
调用阻塞UI线程,则会发生ANR(应用程序不响应)。此外,Thread.sleep
永远不是创建计时器的正确方法,除非您正在编写工作线程的核心心跳。
应该使用Handler.postDelayed
:
public void onClick(View v) {
final Handler handler = new Handler();
final Random random = new Random();
Runnable runnable = new Runnable() {
private int count = 0;
@Override
public void run() {
count++;
if(count > 20) { // 20 times passed
Toast.makeText(getBaseContext(), "Finished", LENGTH_SHORT).show();
return;
}
Toast.makeText(getBaseContext(), "Please wait until finish", LENGTH_SHORT).show();
handler.postDelayed(this, random.nextInt(5000));
}
};
runnable.run();
}
编辑:OP想用这样的东西。https://gist.github.com/SOF3/07c3c110aa214fcdd752e95573b7076f
参见:
- Android -使用postDelayed()调用定期运行一个方法
- 如何在Android中延迟后调用方法
- android应用程序等待