2016-05-14 16 views
2

我的代码的作用是:我的活动有一个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过程中定期运行一个方法?

+1

使用你的第一种方法,使它更宽容一点。不要测试60年代的界限。测试当前60秒间隔播放的声音。 – tynn

+0

好主意@tynn。我有一个想法,让另一个计时器有一个'tick'间隔,你想要播放声音,而'onFinish'也可以播放声音。我认为这是一个可行的解决方案。 – Vucko

回答

0

这个思考了之后而我提出的解决方案能够满足我对简单性的主要要求。以下是如何使用它:

声明两个类级变量

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; 
    } 
} 

内的间隔运行,然后调用方法在onTick方法的CountDownTimer

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

在这里,它是如何工作的:CountDownTimeronTick方法每次蜱时间的推移millisUntilFinished。然后runOnInterval()检查该值是否小于startTime。如果是,它将运行if语句中的代码(在我的示例中为playSound()),然后将startTime减去值interval。一旦millisUntilFinished再次低于startTime,该过程重新开始。

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

0

如果不使用,你可以简单地使用一个后一个倒数计时器延迟处理程序和thread.At方法结束后与指定的时间间隔的处理程序,下面的代码

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 
+0

我会试试这个。处理程序可以暂停(或至少丢弃)?我需要包含用户在完成之前取消定时器的功能。 –

+0

似乎后期处理程序需要取消并重新创建,就像CountDownTimers一样。谢谢。 –

+0

是的,你可以设置一个布尔变量并将其设置为cancle click,并在调用postDelayed之前检查条件。 –

相关问题