How do you pause Chronometer and pick up where you left off?

Asked

Viewed 177 times

2

On Android has the view Chronometer, automatically initializes when you enter the ativity.

To reset the timer from the 0 use the following code:

chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();

When I use the stop(), he stops visually time, but when it is pressed again the start() It’s like I didn’t stop the clock because it was actually working in the background.

How do I pause the chronometer and pick up where you left off?

1 answer

3


The value shown by the chronometer is calculated by the difference between the current instant(SystemClock.elapsedRealtime()) and the reference value - the one that was "set" through setBase().
That’s why when you call back start() the chronometer behaves as if it had not been stopped.

To get the effect you want you need to adjust the reference value so that the difference between the current instant and it is equal to the value shown by the chronometer at the time it was stopped.

Save the instant you stop the clock:

chronometer.stop();
stopTime = SystemClock.elapsedRealtime();

Before making start() recalculate the base value to include downtime:

long pauseDuration = SystemClock.elapsedRealtime() - stopTime;
chronometer.setBase(chronometer.getBase() + pauseDuration);
chronometer.start();
  • I reviewed only today! I had done something very similar, using the same logic. It worked perfect. Abs;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.