Frage

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%).

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top