How to get the time from a Chronometer? I tried getText, getFormat, getBase, etc, but none of them could work.
Example code snippet:
Chronometer t = (Chronometer)findViewById(R.id.toptime);
long time = SystemClock.elapsedRealtime()-t.getBase();
Log.d(null,"Was: "+time); //time is not the proper time for some reason - it is a random number between 0 and 50
t.setBase(SystemClock.elapsedRealtime());
t.start();
@nyenyec +1: here is what i ended up with, while using nyenyec's response without a sub class.
where THRESHOLD is
My Solution:
In onCreate:
There are two buttons in the layout which both call the starttimer method (start and stop)
Somewhat late response, but I was trying to solve this myself today. I ended up just parsing the text of the view:
So calling getSecondsFromDurationString with view.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.
I found this example really useful, thanks nyenyec!
Here's my two cents on how to turn it into a real stopwatch function, without subclassing Chronometer. Just change the mStartListener method to parse the text from mChronometer (it's derived from TextView after all), calculate milliseconds, and use setBase() to readjust the base time to that amount of time in the past:
If you look at the source of the Chronometer class, you'll see that it doesn't store the elapsed time in a field and it calculates it internally every time it needs to update the display.
However it's relatively easy to do the same in your own code:
This assumes that you have started your clock something like this:
Here's a full example:
One somewhat confusing thing about Chronometer is that you can't really use it as a stopwatch that gets started, stopped and restarted again. When it's running, it will always show the time elapsed since you last reset it, no matter how many times and for how long you have stopped it in the meantime. When it is stopped, it simply stops updating the display.
If you need something like a stopwatch you'll have to subclass Chronometer or maybe create your own version using the source.