问题
I have an application in which I'm displaying a chronometer to the user for what he's doing. Whenever the activity goes to the background (wether by home button, or back) I save that time (in seconds) and when the activity is brought back, I want to continue the chronometer running from the same time. The user might select a different item from the list, and the time is different, and also he might turn off the phone... I can save the time of the chronometer, however I can't set it with a start time.
From the Chornometer API, the method setBase()
states:
Set the time that the count-up timer is in reference to.
On my understanding, this means that if I set this value to currentTime, it'll start counting with 0. Now, if I want it to start with the value 17s I thought about setting the base to the currentTime less the time 17 seconds ago. So something like:
setBase(system.currentTimeMillis() - (17 * 1000)).
However this doesn't work, and the it starts always with 0!
I read a few other threads around here, and none of the answers helped. It always starts with 0!
Thanks in advance.
回答1:
I think you're going to have to keep track of some time marks yourself.
Chronometer myChrono;
long baseTime;
long stopTime;
long elapsedTime;
When you set the base time, you want to use:
baseTime = SystemClock.elapsedRealtime() - stopTime;
myChrono.setBase(baseTime);
When you want to see how much time has passed, use:
elapsedTime = SystemClock.elapsedRealtime() - myChrono.getBase();
Take a look at the SystemClock doc.
回答2:
setBase(system.currentTimeMillis() - (17 * 1000))
Should be changed to
setBase(SystemClock.elapsedRealtime() - (17 * 1000))
In general:
mChronometer.setBase(SystemClock.elapsedRealtime() - (nr_of_min * 60000 + nr_of_sec * 1000)))
Hopefully this will save lots of u folks some time :)
来源:https://stackoverflow.com/questions/16477934/android-chronometer-start-with-defined-value