这篇文章: http://android-developers.blogspot.co.uk/2007/11/stitch-in-time.html
描述了如何使用 Handler 实现定时器。我可以使用 CountDown 计时器实现相同的目的: http://developer.android.com/reference/android/os/CountDownTimer.html
这将在前台服务中运行,该服务正在播放音乐,以便在指定时间段后停止播放音乐(想想音乐椅)。屏幕锁定时的时间需要可靠,我认为在前台服务中运行它应该确保这一点,是这样吗?
我从这个帖子知道: Why does CountDown Timer in Android use a Handler?
CountDown 计时器是使用处理程序实现的,所以我的想法是我使用哪个可能无关紧要,但在我开始编码之前,我想我会寻求人群的智慧!
谢谢安德鲁
最佳答案
我最终选择了一个 Handler,它运行良好:
//required import
import android.os.Handler;
//class wide variable... are these considered bad?
private Handler timeHandler = new Handler();
//wherever in your code you want to begin the timer or reset it
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime, 100);
//this is the callback which will be called every 100ms or whatever value you gave in postDelayed
private Runnable updateTime = new Runnable() {
public void run() {
timeHandler.postDelayed(this, 100);
currentTimeMillis = currentTimeMillis + 100;
//do whatever you need to do every 100ms here... or whenever currentTimeMillis reaches the value you're waiting for.
}
我添加了一个 wakeLock 以在屏幕锁定时保持 CPU 唤醒,并且还使用了前台服务。到目前为止,我所做的测试都是准确的。
关于android - 在 Android 中使用 CountDown Timer 或基于 Handler 自己滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28113576/