4

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.

Community
  • 1
  • 1
Nuno Gonçalves
  • 6,202
  • 7
  • 46
  • 66

2 Answers2

9

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.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
  • I was doing some extra code on the onResume and it was overriding the code I was trying on the onCreate method. My bad... Thanks for the help. – Nuno Gonçalves May 10 '13 at 21:48
6
setBase(system.currentTimeMillis() - (17 * 1000))

Should be changed to

setBase(SystemClock.elapsedRealtime() - (17 * 1000))

In general:

mChronometer.setBase(SystemClock.elapsedRealtime() - (nr_of_min * 60000 + nr_of_sec * 1000)))

Hopefully this will save lots of u folks some time :)

René Höhle
  • 26,716
  • 22
  • 73
  • 82
H C M
  • 114
  • 5
  • What if you turn off your phone in the mean time? – Nuno Gonçalves May 28 '13 at 09:46
  • @NunoGonçalves, this is an old post, so presumably you figured this out. But I just worked out a survives-restart solution for myself. So, in case it can help you or someone else, see: http://stackoverflow.com/a/38546506/165164 – Anne Gunn Jul 23 '16 at 21:23