Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: chronometer as a persistent stopwatch. How to set starting time? What is Chronometer "Base"?

I do have one service running in the background. Whenever it starts I store in memory the starting time in milliseconds:

startingTime = new Date().getTime();

I want to display a chronometer that starts counting when the service starts and never stops until the user presses a button. I want to allow the user to leave the activity rendering the chronometer, do some stuff and then return. But the idea is that when the user returns I dont want the chronometer to go to 0:00 again. Insted I want it to show the exact time that has passed ever since the service has started.

I can calculate elapsedTime every time the user return to the chronometer activity:

elapsedTime =  new Date().getTime() - startingTime;

The thing is that i dont know how to tell the chronometer to start counting from that time!

Setting it as the chronometer base does not work. Can someon explain what exactly "base" means or how to accomplish this?

thanks a lot! BYE

like image 496
Santiago Avatar asked Feb 24 '10 08:02

Santiago


People also ask

How do you find the time from a chronometer?

getText(). toString() gives you the total elapsed time in seconds (my application is some kind of stop watch, so you can pause it and resume it). Hope it helps.

How do I change the chronometer format?

By default it will display the current timer value in the form "MM:SS" or "H:MM:SS", or you can use setFormat(String) to format the timer value into an arbitrary string. This works, but it is more efficient to work with the time as a long rather than instantiating a new Date and DateFormat object every second.

How do you use the chronometer on Kotlin?

Create ChronoMeter in MainActivity. First, we declare a variable meter to create the Chronometer in Kotlin file. then, we access the button from the xml file and set setOnClickListener to start and stop the timer. val btn = findViewById<Button>(R. id.


2 Answers

This works for me :

Date now = new Date();
long elapsedTime = now.getTime() - startTime.getTime(); //startTime is whatever time you want to start the chronometer from. you might have stored it somwehere
myChronometer.setBase(SystemClock.elapsedRealtime() - elapsedTime);
myChronometer.start();
like image 179
faizal Avatar answered Dec 01 '22 17:12

faizal


The base time is the time that the Chronometer started ticking at. You can set it using Chronometer.setBase(). You should get the base time by using SystemClock.getElapsedTime(). Call setBase() with the start time each time the Chronometer is started. If there is potential for the Activity to be destroyed and recreated while the timer is still active then you will need to hold the base time somewhere outside of the Activity that owns the Chronometer.

like image 28
Graeme Duncan Avatar answered Dec 01 '22 18:12

Graeme Duncan