I'm doing this way to save the state and restore it after rotation when the chronometer is running. Android_Chronometer pause
When I stop the timer at Xsec and then after Y seconds I change the orientation the chronometer marks X+Y seconds. I'd like to leave the time of a stopped chronometer as it was before rotation, no matter how much time has passed. How should I do?
If you are into slightly hack-y solutions, you can also do the following: Save the value of the
ChronometerInstance.getText()
into theBundle
and then re-set it withChronometerInstance.setText()
. It's not very friendly, but it works and does not involve calculating offsets and storinglong
values until you actually need them.It completely messes with the ability to re-start the Chronometer, too, but since resuming the Chronometer behaves unexpectedly on resume anyway (continues with the same base, so it'll jump to whatever time it would've had without being stopped), that isn't too big of a loss, in my opinion.
Still, if you will ever need the old base time, go with the solution from the comments of the other solution: Save the value of
Then, when you want to restore it, set
If it does not display the value afterwards, you will probably have to force a re-draw. The easiest way is probably to just do a
(as I have no idea if
.invalidate()
will do the trick)Thanks for the clarification in the comments.
To solve your problem you can easily save in
a variable related to the current status of your cronometer and then retrieve it in onCreate or in
(The second method is better) and set your cronometer status accordingly.
EDIT: To retrieve the elapsed time from the chronometer call:
I had a similar question about the Chronometer class and how to survive orientation changes. While there are several useful posts and examples, none that I found addressed the total question.
This was a helpful post here Android_Chronometer pause, which helped with demonstrating the need to save the elapsedTime in order to resume timing.
However, this did not discuss how to make the Chronometer survive Android life cycle orientation changes. What you do with the elapsed time is slightly different between when the timer is running vs. when it is paused.
Here is that I did to put it all together - pausing, resuming, resetting, in a nice class, and surviving orientation:
Note that you can use this in
onSaveInstanceState()
andonCreate()
like this:and then in onCreate you can restore the timer function with: