[英]How can I call a method at regular intervals inside of a CountDownTimer?
我的代码做什么:我的活动有一个CountDownTimer
,它在用户按下按钮时启动。 完成后,将播放声音。 这是代码:
public class PrepTimer extends CountDownTimer {
public PrepTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
updateSessionRemaining(millisUntilFinished);
setPrepDigits(millisUntilFinished);
}
@Override
public void onFinish() {
session.setPrepRemaining(0);
playSound();
}
}
我想要做的是:我希望声音在计时器的过程中定期播放(除了结束时)。 例如,在十分钟的计时器中,声音可能每60秒播放一次。
我尝试过的事情:
onTick
方法内使用if
语句检查millisUntilFinished
是否等于某个值(例如60秒的倍数),然后运行该方法。 这似乎是最直接的解决方案,但我发现该方法未持续触发(也许millisUntilFinished
跳过了我要检查的值?)。 CountDownTimers
并使用for
循环重复。 问题是代码很快变得过于复杂,我的直觉告诉我,我不应该在计时器中运行计时器。 问题:如何在CountDownTimer的过程中定期运行方法?
不用使用倒数计时器,您可以简单地使用延迟发布的处理程序和线程。在方法的末尾以指定的时间间隔发布处理程序,如下代码
Runnable myThread = new Runnable() {
@Override
public void run() {
//call the method here
myHandler.postDelayed(myThread, 1000);//calls thread after 60 seconds
}
};
myHandler.post(myThread);//calls the thread for the first time
在考虑了一段时间之后,我想出了一个满足我对简单性的主要要求的解决方案。 使用方法如下:
声明两个类级别的变量
private long startTime = 60000; // Set this equal to the length of the CountDownTimer
private long interval = 10000; // This will make the method run every 10 seconds
声明一种在CountDownTimer
内部的间隔上运行的方法
private void runOnInterval(long millisUntilFinished) {
if (millisUntilFinished < startTime) {
playSound();
startTime -= interval;
}
}
然后在CountDownTimer
的onTick
方法中调用该方法
// ...
@Override
public void onTick(long millisUntilFinished) {
runOnInterval(millisUntilFinished);
}
// ...
这是它的工作方式: CountDownTimer
的onTick
方法每次计时都会传递millisUntilFinished
。 然后, runOnInterval()
检查该值是否小于startTime
。 如果是这样,它将在if
语句(在我的情况下为playSound()
)中运行代码,然后将interval
的值减少startTime
。 一旦millisUntilFinished
小于startTime
,该过程将重新开始。
上面的代码比采用另一个CountDownTimer
或Handler
和Runnable
更简单。 它还可以自动与可能已添加到活动中以处理CountDownTimer
暂停和重置的任何功能结合使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.