0

When making the countdowntimer with

new CountDownTimer(interval,1000)
{
.
.
}

I expect to get 1 second period in between ticks, but apparently the interval is quite random and because of that, sometimes the timer skipped 1 second.

When I experiment by displaying the millis directly, the interval ranges from 900-1150, and often skips one second because of that.

How can I fix this?

Ax1dy
  • 17
  • 5
  • you can use interval of 500 ms or write your own code using a Handler – pskink Jan 26 '14 at 21:16
  • I can think of some workaround using higher frequency, time counter, and flags, to avoid missing a second, but I'm curious why this code won't produce the exact interval, the 1000 ms – Ax1dy Jan 26 '14 at 22:14

1 Answers1

0

You probably don't want to use this approach if milliseconds are important. You should probably check the system time to see if 1000 millis have elapsed and keep track of when you started counting. Then over long periods (like 1,000 millis) you can correct for the inaccuracy of the counter along the way.

Here is a good post on it: How to measure elapsed time

Use that to check elapsed time every 100 millis or 500 millis with your timer. To a user, 100 millis probably won't be noticed. But over long counting periods it will add up. This is a better approach.

Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36
  • 500 millis should definitely work. with some additional counter inside, the time should be fluid. I still wonder why the code won't run at constant frequency though. Any idea? – Ax1dy Jan 26 '14 at 22:17
  • yes - the thread it's running on is not a priority thread. The UI and other operations will cause the timer to be off slightly because this is not a critical operation. There are ways to prioritize your thread, etc. but for general use the approach I mentioned is preferred. – Jim Jan 26 '14 at 22:51
  • Wow, I didn't expect threading to affect this. I seems to have other issues with countdown timer, as I asked here [link](http://stackoverflow.com/questions/21368723/android-countdowntimer-in-listview-flickers-randomly). Can you please help me with that issue too? – Ax1dy Jan 26 '14 at 23:17