Android Chronometer start with defined value

Nuno Gonçalves picture Nuno Gonçalves · May 10, 2013 · Viewed 10.6k times · Source

I have an application in which I'm displaying a chronometer to the user for what he's doing. Whenever the activity goes to the background (wether by home button, or back) I save that time (in seconds) and when the activity is brought back, I want to continue the chronometer running from the same time. The user might select a different item from the list, and the time is different, and also he might turn off the phone... I can save the time of the chronometer, however I can't set it with a start time.

From the Chornometer API, the method setBase() states:

Set the time that the count-up timer is in reference to.

On my understanding, this means that if I set this value to currentTime, it'll start counting with 0. Now, if I want it to start with the value 17s I thought about setting the base to the currentTime less the time 17 seconds ago. So something like:

setBase(system.currentTimeMillis() - (17 * 1000)).

However this doesn't work, and the it starts always with 0!

I read a few other threads around here, and none of the answers helped. It always starts with 0!

Thanks in advance.

Answer

MarsAtomic picture MarsAtomic · May 10, 2013

I think you're going to have to keep track of some time marks yourself.

Chronometer myChrono;
long baseTime;
long stopTime;
long elapsedTime;

When you set the base time, you want to use:

baseTime = SystemClock.elapsedRealtime() - stopTime;
myChrono.setBase(baseTime);

When you want to see how much time has passed, use:

elapsedTime = SystemClock.elapsedRealtime() - myChrono.getBase();

Take a look at the SystemClock doc.