System.currentTimeMillis() vs SystemClock.elapsedRealtime()
System.currentTimemillis is the standard "wall" clock (time and date) expressing milliseconds since the epoch(Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds; the Unix epoch is 00:00:00 UTC on 1 January 1970.). The wall clock can be set by the user or the phone network (see
setCurrentTimeMillis(long)
), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to theACTION_TIME_TICK
,ACTION_TIME_CHANGED
andACTION_TIMEZONE_CHANGED
Intent
broadcasts to find out when the time changes.
elapsedRealtime()
andelapsedRealtimeNanos()
return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.