0

Each second that != the previous second a new value is posted and when the value reaches <1 the countdown finishes.

I note the starting time with System.currentTimeMillis() and simply calculate the remainder of the countdown from there. All this is done in a runnable which gets re-run over and over.

When typing out the min & seconds left I use this formula:

secondsLeft=    (int) ((time / 1000) % 60);
minutesLeft =  (int) (time / (60*1000));

The problem Im getting at is that when the secondsLeft reaches <1 the timer finishes. But my Alarm set through AlarmManager which uses pure millis and thus not rounding to nearest second, gets run a little sooner , or later than the timer finishes.

What can I do to make them synchronized?

Some extra info:

I am vibrating the phone when the countdown finishes. Hence I cant have the timer reach 0 and then the phone vibrating sooner/later.

I use AlarmManager for the vibrate as it wont go off if phone is asleep too long (service running in foreground works most of the time,but not 100%).

zoltish
  • 2,122
  • 19
  • 37
  • http://stackoverflow.com/questions/17620641/countdowntimer-in-minutes-and-seconds/17620827#17620827. check this if it helps – Raghunandan Oct 04 '13 at 05:58
  • Thats identical to my current solution. However; doing if(Countdown is near end) Vibrate - Doesnt work 100% of the time as the OS will kill the process. – zoltish Oct 04 '13 at 06:03

1 Answers1

1

By your description, I believe you're getting bit by rounding. If you start the timer at, say, 1380866264454ms, next second by your algorithm happens in only 546 milliseconds, not 1000 - so your countdown would end approximately 454ms before your alarm is scheduled. Thus, get the last three digits of your start time and subtract them from the current time before you do the calculation you show in the post. The first change after (1380866264454 - 454) will be at (1380866265454 - 454), at least 1000ms away.

Amadan
  • 191,408
  • 23
  • 240
  • 301