重复一个有时间延迟的任务? [英] Repeat a task with a time delay?
问题描述
我的代码中有一个变量说它是状态".
I have a variable in my code say it is "status".
我想根据这个变量值在应用程序中显示一些文本.这必须以特定的时间延迟来完成.
I want to display some text in the application depending on this variable value. This has to be done with a specific time delay.
就像,
检查状态变量值
Check status variable value
显示一些文字
等待 10 秒
检查状态变量值
显示一些文字
等待 15 秒
等等.时间延迟可能会有所不同,并在显示文本后设置.
and so on. The time delay may vary and it is set once the text is displayed.
我已经尝试过 Thread.sleep(time delay)
但它失败了.有没有更好的方法来完成这项工作?
I have tried Thread.sleep(time delay)
and it failed. Any better way to get this done?
推荐答案
为此您应该使用 Handler
的 postDelayed
函数.它将在主 UI 线程上以指定的延迟运行您的代码,因此您将能够更新 UI 控件.
You should use Handler
's postDelayed
function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
@Override
protected void onCreate(Bundle bundle) {
// your code here
mHandler = new Handler();
startRepeatingTask();
}
@Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
try {
updateStatus(); //this function can change value of mInterval.
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
这篇关于重复一个有时间延迟的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!