How to pause the chronometer and continue from where did it stop?

2

Android has view Chronometer , which automatically boots when it enters ativity .

To restart the timer from 0 I use the following code:

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

When I use stop() , it stops visually from timing, but when it is pressed again the start() is as if it had not stopped the timer because it was actually working in the background.

How do I pause chronometer and continue from where did it stop?

    
asked by anonymous 28.04.2017 / 17:21

1 answer

3

The value displayed by the stopwatch is calculated by the difference between the current instant (% with%) and the reference value - the value that was set by% with%. That is why when it returns to call SystemClock.elapsedRealtime() the timer behaves as if it had not been stopped.

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

Save the instant the stopwatch stopped:

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

Before doing setBase() recalculate the base value to include the time it was stopped:

long pauseDuration = SystemClock.elapsedRealtime() - stopTime;
chronometer.setBase(chronometer.getBase() + pauseDuration);
chronometer.start();
    
29.04.2017 / 18:40