繁体   English   中英

如何在CountDownTimer内定期调用方法?

[英]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;
    }
}

然后在CountDownTimeronTick方法中调用该方法

// ...
@Override
    public void onTick(long millisUntilFinished) {
        runOnInterval(millisUntilFinished);
    }
// ...

这是它的工作方式: CountDownTimeronTick方法每次计时都会传递millisUntilFinished 然后, runOnInterval()检查该值是否小于startTime 如果是这样,它将在if语句(在我的情况下为playSound() )中运行代码,然后将interval的值减少startTime 一旦millisUntilFinished小于startTime ,该过程将重新开始。

上面的代码比采用另一个CountDownTimerHandlerRunnable更简单。 它还可以自动与可能已添加到活动中以处理CountDownTimer暂停和重置的任何功能结合使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM