Runnable 的执行速度比预期慢
我在 Android 应用程序中使用可运行程序来更新倒计时器,如下面的代码所示。它似乎有效,但我注意到我的计时器比预期的时间长了几秒钟。例如,如果要倒计时 3 分钟,则需要 3 分 5 秒。我尝试在服务中使用计时器来管理主要活动中的倒计时显示。计时器/服务按预期工作。
为什么 runnable
/postDelayed()
没有运行正确的时间? postDelayed()
计时可靠吗? runnable
递减一个变量,然后使用它通过 setText()
更新 EditText
。 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);
I'm using a runnable in my Android app to update a countdown timer, as shown in the code below. It appears to work but I noticed my timer takes a few seconds longer than expected. For example, if it's supposed to count down 3 minutes, it takes 3 minutes and 5 seconds. I tried using a timer in a service to manage the countdown display in the main activity. The timer/service worked as expected.
Why doesn't runnable
/postDelayed()
run for the correct amount of time? Is postDelayed()
timing reliable? The runnable
decrements a variable then uses it to update an EditText
with setText()
. Does setText()
take too long (a small fraction of a second), so the runnable
really runs every 1.x seconds?
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码有点设计不准确,因为您没有考虑可运行的内部所花费的时间。通过执行类似的操作,您可能会获得更好的结果
Your code is kinda sorta designed to be inaccurate because you are not accounting for the time taken by the guts of the runnable. You might get improved results by doing something like
使用倒计时器怎么样?我多次使用它来完成相同的任务,但没有遇到此类问题。
What about using CountDownTimer? I used this for same tasks several times and haven’t met this kind of problem.