我在我的Android应用程序中使用可运行程序来更新倒数计时器,如下面的代码所示。它似乎工作,但我注意到我的计时器比预期的要花几秒钟。例如,如果它应该倒数3分钟,则需要3分5秒。我尝试在服务中使用计时器来管理主要活动中的倒计时显示。计时器/服务按预期工作。Runnable执行速度比预期慢
为什么不运行runnable
/postDelayed()
正确的时间?是postDelayed()
时间可靠吗? runnable
递减一个变量,然后使用它来更新EditText
与setText()
。 setText()
花费的时间太长(一秒钟的一小部分),所以runnable
确实每隔1.x秒运行一次?
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// decrement the time remaining and update the display
handler.postDelayed(this, 1000);
}
};
...
// start the runnable
handler.postDelayed(r, 1000);
如果您希望计时器准确无误,最好从可运行内部发布消息,而不是直接更新UI。当然,理想的情况是,您应该像上面提到的那样在服务中安装计时器。 – rajath 2011-03-26 08:17:56
我发现postDelayed发射的时间差异很大。当屏幕*关闭* 2分钟设置会导致6 - 14分钟的延迟。 (Android 2.2,HTC Hero) – fadedbee 2012-06-12 13:25:18