Android Chronometer

2019-07-01 09:03发布

问题:

How to start the chronometer with a specific time other than default 00:00? Is it possible to set chronometerObj.setBase(startTime) ?

ch.setBase(SystemClock.elapsedRealtime()-anylongvalue); ch.start(); can I set start time, if I put anylongvalue?

回答1:

In general:

mChronometer.setBase(SystemClock.elapsedRealtime() - (nr_of_min * 60000 + nr_of_sec * 1000)))



回答2:

Chronometer object, when instantiated, defaults to the base time being set to now ('now' as in the value you get from SystemClock.elapsedRealtime()).

You can change the base time (00:00 time) by calling setBase(<some other value>).

Presumably, although I haven't tried the experiment, you could see the elapsed time since last system boot using setBase(0).

So you can use chronometer to see the elapsed time since any arbitrary call you made in the past to SystemClock.elapsedRealtime(). The trick is that you need to have stored that value somewhere you can dependably get it back despite app and phone state changes. (See Android: chronometer as a persistent stopwatch. How to set starting time? What is Chronometer "Base"? for example.)

Many answers suggest persisting that arbitrary time-in-the-past in an intent. but, at best, this only keeps the timer counting up while the phone stays on.

I already am using a database and store my starting time in there. I created a one-column table for it and store a single record in it. My starting time for the chronometer survives a phone reboot.