问题描述
我在code具有可变说,这是地位。
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.
我已经试过视频下载(延时)
,它失败了。没有更好的方法来完成这件事?
I have tried Thread.sleep(time delay)
and it failed. Any better way to get this done?
推荐答案
您应该使用处理程序
的 postDelayed
功能用于此目的。它将运行您的code与主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) {
...
mHandler = new Handler();
startRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
updateStatus(); //this function can change value of mInterval.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
这篇关于重复与时间延迟一个任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!