blob: fd68c2b9b5fd8c61828ec89b383dc0c6740d8da3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070019import android.annotation.NonNull;
Greg Hackmann38bf5142014-02-19 16:39:36 -080020import android.app.IAlarmManager;
Artur Satayevafdb23a2019-12-10 17:47:53 +000021import android.compat.annotation.UnsupportedAppUsage;
Greg Hackmann38bf5142014-02-19 16:39:36 -080022import android.content.Context;
Chad Brubakerf1133332019-03-15 14:13:59 -070023import android.location.ILocationManager;
24import android.location.LocationTime;
Greg Hackmann38bf5142014-02-19 16:39:36 -080025import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
John Reck9481c9e2016-10-03 14:55:00 -070027import dalvik.annotation.optimization.CriticalNative;
28
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070029import java.time.Clock;
Jeff Sharkey9911a282018-02-14 22:29:11 -070030import java.time.DateTimeException;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070031import java.time.ZoneOffset;
32
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033/**
34 * Core timekeeping facilities.
35 *
36 * <p> Three different clocks are available, and they should not be confused:
37 *
38 * <ul>
39 * <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
40 * is the standard "wall" clock (time and date) expressing milliseconds
41 * since the epoch. The wall clock can be set by the user or the phone
42 * network (see {@link #setCurrentTimeMillis}), so the time may jump
43 * backwards or forwards unpredictably. This clock should only be used
44 * when correspondence with real-world dates and times is important, such
45 * as in a calendar or alarm clock application. Interval or elapsed
Joe Onorato37296dc2009-07-31 17:58:55 -070046 * time measurements should use a different clock. If you are using
47 * System.currentTimeMillis(), consider listening to the
48 * {@link android.content.Intent#ACTION_TIME_TICK ACTION_TIME_TICK},
49 * {@link android.content.Intent#ACTION_TIME_CHANGED ACTION_TIME_CHANGED}
50 * and {@link android.content.Intent#ACTION_TIMEZONE_CHANGED
51 * ACTION_TIMEZONE_CHANGED} {@link android.content.Intent Intent}
52 * broadcasts to find out when the time changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 *
54 * <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
55 * system was booted. This clock stops when the system enters deep
56 * sleep (CPU off, display dark, device waiting for external input),
57 * but is not affected by clock scaling, idle, or other power saving
58 * mechanisms. This is the basis for most interval timing
59 * such as {@link Thread#sleep(long) Thread.sleep(millls)},
60 * {@link Object#wait(long) Object.wait(millis)}, and
61 * {@link System#nanoTime System.nanoTime()}. This clock is guaranteed
Nick Pelly95f11582012-07-19 10:22:18 -070062 * to be monotonic, and is suitable for interval timing when the
63 * interval does not span device sleep. Most methods that accept a
64 * timestamp value currently expect the {@link #uptimeMillis} clock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 *
Philip Milne41180122012-09-26 11:29:25 -070066 * <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
Nick Pelly95f11582012-07-19 10:22:18 -070067 * return the time since the system was booted, and include deep sleep.
68 * This clock is guaranteed to be monotonic, and continues to tick even
69 * when the CPU is in power saving modes, so is the recommend basis
70 * for general purpose interval timing.
71 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * </ul>
73 *
74 * There are several mechanisms for controlling the timing of events:
75 *
76 * <ul>
77 * <li> <p> Standard functions like {@link Thread#sleep(long)
78 * Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
79 * are always available. These functions use the {@link #uptimeMillis}
80 * clock; if the device enters sleep, the remainder of the time will be
81 * postponed until the device wakes up. These synchronous functions may
82 * be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
83 * you must handle {@link InterruptedException}.
84 *
85 * <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
86 * very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
87 * ignores {@link InterruptedException}. Use this function for delays if
88 * you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
89 * preserve the interrupted state of the thread.
90 *
91 * <li> <p> The {@link android.os.Handler} class can schedule asynchronous
92 * callbacks at an absolute or relative time. Handler objects also use the
93 * {@link #uptimeMillis} clock, and require an {@link android.os.Looper
94 * event loop} (normally present in any GUI application).
95 *
96 * <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
97 * recurring events which occur even when the device is in deep sleep
98 * or your application is not running. Events may be scheduled with your
99 * choice of {@link java.lang.System#currentTimeMillis} (RTC) or
100 * {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
101 * {@link android.content.Intent} broadcast when they occur.
102 * </ul>
103 */
104public final class SystemClock {
Greg Hackmann38bf5142014-02-19 16:39:36 -0800105 private static final String TAG = "SystemClock";
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 /**
108 * This class is uninstantiable.
109 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000110 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private SystemClock() {
112 // This space intentionally left blank.
113 }
114
115 /**
116 * Waits a given number of milliseconds (of uptimeMillis) before returning.
117 * Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
118 * {@link InterruptedException}; {@link Thread#interrupt()} events are
119 * deferred until the next interruptible operation. Does not return until
120 * at least the specified number of milliseconds has elapsed.
121 *
122 * @param ms to sleep before returning, in milliseconds of uptime.
123 */
124 public static void sleep(long ms)
125 {
126 long start = uptimeMillis();
127 long duration = ms;
128 boolean interrupted = false;
129 do {
130 try {
131 Thread.sleep(duration);
132 }
133 catch (InterruptedException e) {
134 interrupted = true;
135 }
136 duration = start + ms - uptimeMillis();
137 } while (duration > 0);
John Reck9481c9e2016-10-03 14:55:00 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 if (interrupted) {
140 // Important: we don't want to quietly eat an interrupt() event,
141 // so we make sure to re-interrupt the thread so that the next
142 // call to Thread.sleep() or Object.wait() will be interrupted.
143 Thread.currentThread().interrupt();
144 }
145 }
John Reck9481c9e2016-10-03 14:55:00 -0700146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 /**
148 * Sets the current wall time, in milliseconds. Requires the calling
149 * process to have appropriate permissions.
150 *
151 * @return if the clock was successfully set to the specified time.
152 */
Greg Hackmann38bf5142014-02-19 16:39:36 -0800153 public static boolean setCurrentTimeMillis(long millis) {
Jeff Sharkey9911a282018-02-14 22:29:11 -0700154 final IAlarmManager mgr = IAlarmManager.Stub
155 .asInterface(ServiceManager.getService(Context.ALARM_SERVICE));
Greg Hackmann38bf5142014-02-19 16:39:36 -0800156 if (mgr == null) {
Neil Fuller4b03c072019-11-21 17:30:03 +0000157 Slog.e(TAG, "Unable to set RTC: mgr == null");
Greg Hackmann38bf5142014-02-19 16:39:36 -0800158 return false;
159 }
160
161 try {
162 return mgr.setTime(millis);
163 } catch (RemoteException e) {
164 Slog.e(TAG, "Unable to set RTC", e);
165 } catch (SecurityException e) {
166 Slog.e(TAG, "Unable to set RTC", e);
167 }
168
169 return false;
170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 /**
173 * Returns milliseconds since boot, not counting time spent in deep sleep.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 *
175 * @return milliseconds of non-sleep uptime since boot.
176 */
John Reck9481c9e2016-10-03 14:55:00 -0700177 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 native public static long uptimeMillis();
179
180 /**
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700181 * Return {@link Clock} that starts at system boot, not counting time spent
182 * in deep sleep.
Jeff Sharkey9911a282018-02-14 22:29:11 -0700183 *
184 * @removed
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700185 */
Jeff Sharkey9911a282018-02-14 22:29:11 -0700186 public static @NonNull Clock uptimeClock() {
187 return new SimpleClock(ZoneOffset.UTC) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700188 @Override
189 public long millis() {
190 return SystemClock.uptimeMillis();
191 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700192 };
193 }
194
195 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 * Returns milliseconds since boot, including time spent in sleep.
197 *
198 * @return elapsed milliseconds since boot.
199 */
John Reck9481c9e2016-10-03 14:55:00 -0700200 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 native public static long elapsedRealtime();
Nick Pelly95f11582012-07-19 10:22:18 -0700202
203 /**
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700204 * Return {@link Clock} that starts at system boot, including time spent in
205 * sleep.
Jeff Sharkey9911a282018-02-14 22:29:11 -0700206 *
207 * @removed
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700208 */
209 public static @NonNull Clock elapsedRealtimeClock() {
Jeff Sharkey9911a282018-02-14 22:29:11 -0700210 return new SimpleClock(ZoneOffset.UTC) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700211 @Override
212 public long millis() {
213 return SystemClock.elapsedRealtime();
214 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700215 };
216 }
217
218 /**
Nick Pelly95f11582012-07-19 10:22:18 -0700219 * Returns nanoseconds since boot, including time spent in sleep.
220 *
221 * @return elapsed nanoseconds since boot.
222 */
John Reck9481c9e2016-10-03 14:55:00 -0700223 @CriticalNative
Philip Milne41180122012-09-26 11:29:25 -0700224 public static native long elapsedRealtimeNanos();
Nick Pelly95f11582012-07-19 10:22:18 -0700225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 /**
227 * Returns milliseconds running in the current thread.
John Reck9481c9e2016-10-03 14:55:00 -0700228 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 * @return elapsed milliseconds in the thread
230 */
John Reck9481c9e2016-10-03 14:55:00 -0700231 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 public static native long currentThreadTimeMillis();
Romain Guy648bee12011-07-20 18:47:17 -0700233
234 /**
235 * Returns microseconds running in the current thread.
John Reck9481c9e2016-10-03 14:55:00 -0700236 *
Romain Guy648bee12011-07-20 18:47:17 -0700237 * @return elapsed microseconds in the thread
John Reck9481c9e2016-10-03 14:55:00 -0700238 *
Romain Guy648bee12011-07-20 18:47:17 -0700239 * @hide
240 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000241 @UnsupportedAppUsage
John Reck9481c9e2016-10-03 14:55:00 -0700242 @CriticalNative
Romain Guy648bee12011-07-20 18:47:17 -0700243 public static native long currentThreadTimeMicro();
244
245 /**
246 * Returns current wall time in microseconds.
John Reck9481c9e2016-10-03 14:55:00 -0700247 *
Romain Guy648bee12011-07-20 18:47:17 -0700248 * @return elapsed microseconds in wall time
John Reck9481c9e2016-10-03 14:55:00 -0700249 *
Romain Guy648bee12011-07-20 18:47:17 -0700250 * @hide
251 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000252 @UnsupportedAppUsage
John Reck9481c9e2016-10-03 14:55:00 -0700253 @CriticalNative
Romain Guy648bee12011-07-20 18:47:17 -0700254 public static native long currentTimeMicro();
Jeff Sharkey9911a282018-02-14 22:29:11 -0700255
256 /**
257 * Returns milliseconds since January 1, 1970 00:00:00.0 UTC, synchronized
258 * using a remote network source outside the device.
259 * <p>
260 * While the time returned by {@link System#currentTimeMillis()} can be
261 * adjusted by the user, the time returned by this method cannot be adjusted
262 * by the user. Note that synchronization may occur using an insecure
263 * network protocol, so the returned time should not be used for security
264 * purposes.
265 * <p>
266 * This performs no blocking network operations and returns values based on
267 * a recent successful synchronization event; it will either return a valid
268 * time or throw.
269 *
270 * @throws DateTimeException when no accurate network time can be provided.
Jeff Sharkeyae1324a2018-03-26 15:26:00 -0600271 * @hide
Jeff Sharkey9911a282018-02-14 22:29:11 -0700272 */
273 public static long currentNetworkTimeMillis() {
274 final IAlarmManager mgr = IAlarmManager.Stub
275 .asInterface(ServiceManager.getService(Context.ALARM_SERVICE));
276 if (mgr != null) {
277 try {
278 return mgr.currentNetworkTimeMillis();
279 } catch (ParcelableException e) {
280 e.maybeRethrow(DateTimeException.class);
281 throw new RuntimeException(e);
282 } catch (RemoteException e) {
283 throw e.rethrowFromSystemServer();
284 }
285 } else {
286 throw new RuntimeException(new DeadSystemException());
287 }
288 }
289
290 /**
291 * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
292 * synchronized using a remote network source outside the device.
293 * <p>
294 * While the time returned by {@link System#currentTimeMillis()} can be
295 * adjusted by the user, the time returned by this method cannot be adjusted
296 * by the user. Note that synchronization may occur using an insecure
297 * network protocol, so the returned time should not be used for security
298 * purposes.
299 * <p>
300 * This performs no blocking network operations and returns values based on
301 * a recent successful synchronization event; it will either return a valid
302 * time or throw.
303 *
304 * @throws DateTimeException when no accurate network time can be provided.
Jeff Sharkeyae1324a2018-03-26 15:26:00 -0600305 * @hide
Jeff Sharkey9911a282018-02-14 22:29:11 -0700306 */
307 public static @NonNull Clock currentNetworkTimeClock() {
308 return new SimpleClock(ZoneOffset.UTC) {
309 @Override
310 public long millis() {
311 return SystemClock.currentNetworkTimeMillis();
312 }
313 };
314 }
Chad Brubakerf1133332019-03-15 14:13:59 -0700315
316 /**
317 * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
318 * synchronized using the device's location provider.
319 *
320 * @throws DateTimeException when the location provider has not had a location fix since boot.
321 */
322 public static @NonNull Clock currentGnssTimeClock() {
323 return new SimpleClock(ZoneOffset.UTC) {
324 private final ILocationManager mMgr = ILocationManager.Stub
325 .asInterface(ServiceManager.getService(Context.LOCATION_SERVICE));
326 @Override
327 public long millis() {
328 LocationTime time;
329 try {
330 time = mMgr.getGnssTimeMillis();
331 } catch (RemoteException e) {
332 e.rethrowFromSystemServer();
333 return 0;
334 }
335 if (time == null) {
336 throw new DateTimeException("Gnss based time is not available.");
337 }
338 long currentNanos = elapsedRealtimeNanos();
339 long deltaMs = (currentNanos - time.getElapsedRealtimeNanos()) / 1000000L;
340 return time.getTime() + deltaMs;
341 }
342 };
343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344}