Android Chronometer start with defined value

荒凉一梦 提交于 2019-12-12 15:59:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!