0

我只想在一秒钟内播放一次声音文件,但是如果我将 countDownInterval 设置为 100 到 700,我会执行两到三次操作(由于舍入)。如果我将 countDownInterval 设置为从 700 到 1000,我会在 10 到 2 的范围内进行一次操作,但如果我设置在 1 秒内播放声音文件,我会播放两次,因为onTick四舍五入。是的,我知道CountDownTimer 并不精确。感谢帮助!

  public void startTimer() {
          tCountDownTimer = new CountDownTimer(tTime * 1000, 1000) {    
      @Override
      public void onTick(long millisUntilFinished) {
          int seconds = (int) (millisUntilFinished / 1000);       
          int minutes = seconds / 60;
          int hours = minutes / 60;
          minutes = minutes % 60;
          seconds = seconds % 60;
          String curTime = hours + ":" + minutes + "::" + seconds;
          Log.v("log_tag", "Log is here Time is now" + curTime);
          tTimeLabel.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
          runSec (seconds); 
          runMin (minutes);
          runHou (hours);
          if (seconds == 3) {
              playAlertSound(R.raw.beep1);
              }
          else if(seconds == 2){
              playAlertSound(R.raw.beep1);
              }
          else if(seconds == 1){
              playAlertSound(R.raw.beep1);
              }
          else if(seconds == 0){
              playAlertSound(R.raw.beep2);
              }

如果我使用int seconds = Math.round(millisUntilFinished / 1000);

12-06 19:16:54.320: V/log_tag(1121): Log is here Time is now0:0::4
12-06 19:16:55.379: V/log_tag(1121): Log is here Time is now0:0::3
12-06 19:16:56.437: V/log_tag(1121): Log is here Time is now0:0::2
12-06 19:16:57.478: V/log_tag(1121): Log is here Time is now0:0::1

如果我使用int seconds = Math.round(millisUntilFinished / 1000f);

12-06 19:20:14.851: V/log_tag(1167): Log is here Time is now0:0::5
12-06 19:20:15.885: V/log_tag(1167): Log is here Time is now0:0::4
12-06 19:20:16.931: V/log_tag(1167): Log is here Time is now0:0::3
12-06 19:20:17.973: V/log_tag(1167): Log is here Time is now0:0::2

这是用户在驯服器上设置的时间:

protected int tTime = 0;

public void onClick(View v) {
    if(v == upTimesl && tTime <= (11*60*60+1*59*60+55))
      settTime(tTime + 5);
    else if(v == downTimesl && tTime > 5)
      settTime(tTime - 5);
    else if(v == downTimesl && tTime <= 5)
          settTime(tTime=0);
...
4

1 回答 1

0

从数学上讲,您不是四舍五入,而是进行地板操作。如果millisUntilFinished / 1000实际上是 0.9999,那么您肯定会得到 0。您应该使用Math.round()

int seconds = Math.round(millisUntilFinished / 1000f);       

(请注意,我除以1000f,将 long 除以整数仍然是地板操作。)

您当前的间隔是 100 毫秒,这没有意义,因为您的所有计算都是基于秒的。你应该使用:

tCountDownTimer = new CountDownTimer(tTime * 1000, 1000) { 

CountDownTimer 也有一些怪癖:它为每个间隔增加了几毫秒,并且经常在调用之前跳过最后一个间隔onFinish()。不久前,我对此类进行了一些更改,以消除android CountDownTimer 中的这些错误 - 滴答之间的额外毫秒延迟

于 2012-12-06T18:13:46.513 回答