How to keep a Chronometer running in the background?

2.8k Views Asked by At

I have in a Activity (1) A Chronometer and is running fine. I click a Button and starts Chronometer time count.

I'm trying to keep the score Chronometer changing Activity (2) but without success.

In this new Activity (2) does not have the layout Chronometer one component. I tried to pass the Chronometer object of Activity (1) to the other Activity (2) and continue the count but continues even taking this Chronometer and giving a new start() does not count the time. I tried to pass the component Chronometer via Intent.putExtra() and creating a memory class.

I tried to even create the Activity (2) a Chronometer in invisible layout and pass only the value of Chronometer.getBase() and give a start(), is not counting the time. In Activity (2) should continue recording the time and return to the Activity (1) Chronometer should be visible elapsed time.

The Activity (1) and (2) die with the finish().

2

There are 2 best solutions below

0
On BEST ANSWER

Thanks for the reply! I had tried before this medium but without success. In fact I analyzed my code better and saw that I was sabotaging myself. A new instance of Chronometer was created after setting it to start counting. So it does not accounted for. and taking advantage would have to use their means of more this code timing:

long restartTime = getIntent().getLongExtra(Constantes.TIME, 0) + SystemClock.elapsedRealtime();

This was when set the current getBase the Chronometer in question the previous Activity.

And step for the Activity to be called the following putExtra():

long valueChrono = chronometer.getBase()
                    - SystemClock.elapsedRealtime();

Thank you and sorry for any problems!

0
On

You just need to keep a reference to the original start time. See the Chronometer docs for more details, but the gist is:

long startTime = SystemClock.elapsedRealtime();
chronometerInstance.setBase(startTime);
chronometerInstance.start();

Then you can pass startTime around to other activities and continue to use that same value anytime you need to start a chronometer.