blob: c52c22d60adede432060c1e52121fdbd3b926a0c [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;
21import android.content.Context;
22import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
John Reck9481c9e2016-10-03 14:55:00 -070024import dalvik.annotation.optimization.CriticalNative;
25
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070026import java.time.Clock;
27import java.time.Instant;
28import java.time.ZoneId;
29import java.time.ZoneOffset;
30
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031/**
32 * Core timekeeping facilities.
33 *
34 * <p> Three different clocks are available, and they should not be confused:
35 *
36 * <ul>
37 * <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
38 * is the standard "wall" clock (time and date) expressing milliseconds
39 * since the epoch. The wall clock can be set by the user or the phone
40 * network (see {@link #setCurrentTimeMillis}), so the time may jump
41 * backwards or forwards unpredictably. This clock should only be used
42 * when correspondence with real-world dates and times is important, such
43 * as in a calendar or alarm clock application. Interval or elapsed
Joe Onorato37296dc2009-07-31 17:58:55 -070044 * time measurements should use a different clock. If you are using
45 * System.currentTimeMillis(), consider listening to the
46 * {@link android.content.Intent#ACTION_TIME_TICK ACTION_TIME_TICK},
47 * {@link android.content.Intent#ACTION_TIME_CHANGED ACTION_TIME_CHANGED}
48 * and {@link android.content.Intent#ACTION_TIMEZONE_CHANGED
49 * ACTION_TIMEZONE_CHANGED} {@link android.content.Intent Intent}
50 * broadcasts to find out when the time changes.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 *
52 * <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
53 * system was booted. This clock stops when the system enters deep
54 * sleep (CPU off, display dark, device waiting for external input),
55 * but is not affected by clock scaling, idle, or other power saving
56 * mechanisms. This is the basis for most interval timing
57 * such as {@link Thread#sleep(long) Thread.sleep(millls)},
58 * {@link Object#wait(long) Object.wait(millis)}, and
59 * {@link System#nanoTime System.nanoTime()}. This clock is guaranteed
Nick Pelly95f11582012-07-19 10:22:18 -070060 * to be monotonic, and is suitable for interval timing when the
61 * interval does not span device sleep. Most methods that accept a
62 * timestamp value currently expect the {@link #uptimeMillis} clock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 *
Philip Milne41180122012-09-26 11:29:25 -070064 * <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
Nick Pelly95f11582012-07-19 10:22:18 -070065 * return the time since the system was booted, and include deep sleep.
66 * This clock is guaranteed to be monotonic, and continues to tick even
67 * when the CPU is in power saving modes, so is the recommend basis
68 * for general purpose interval timing.
69 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * </ul>
71 *
72 * There are several mechanisms for controlling the timing of events:
73 *
74 * <ul>
75 * <li> <p> Standard functions like {@link Thread#sleep(long)
76 * Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
77 * are always available. These functions use the {@link #uptimeMillis}
78 * clock; if the device enters sleep, the remainder of the time will be
79 * postponed until the device wakes up. These synchronous functions may
80 * be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
81 * you must handle {@link InterruptedException}.
82 *
83 * <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
84 * very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
85 * ignores {@link InterruptedException}. Use this function for delays if
86 * you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
87 * preserve the interrupted state of the thread.
88 *
89 * <li> <p> The {@link android.os.Handler} class can schedule asynchronous
90 * callbacks at an absolute or relative time. Handler objects also use the
91 * {@link #uptimeMillis} clock, and require an {@link android.os.Looper
92 * event loop} (normally present in any GUI application).
93 *
94 * <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
95 * recurring events which occur even when the device is in deep sleep
96 * or your application is not running. Events may be scheduled with your
97 * choice of {@link java.lang.System#currentTimeMillis} (RTC) or
98 * {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
99 * {@link android.content.Intent} broadcast when they occur.
100 * </ul>
101 */
102public final class SystemClock {
Greg Hackmann38bf5142014-02-19 16:39:36 -0800103 private static final String TAG = "SystemClock";
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 /**
106 * This class is uninstantiable.
107 */
108 private SystemClock() {
109 // This space intentionally left blank.
110 }
111
112 /**
113 * Waits a given number of milliseconds (of uptimeMillis) before returning.
114 * Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
115 * {@link InterruptedException}; {@link Thread#interrupt()} events are
116 * deferred until the next interruptible operation. Does not return until
117 * at least the specified number of milliseconds has elapsed.
118 *
119 * @param ms to sleep before returning, in milliseconds of uptime.
120 */
121 public static void sleep(long ms)
122 {
123 long start = uptimeMillis();
124 long duration = ms;
125 boolean interrupted = false;
126 do {
127 try {
128 Thread.sleep(duration);
129 }
130 catch (InterruptedException e) {
131 interrupted = true;
132 }
133 duration = start + ms - uptimeMillis();
134 } while (duration > 0);
John Reck9481c9e2016-10-03 14:55:00 -0700135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 if (interrupted) {
137 // Important: we don't want to quietly eat an interrupt() event,
138 // so we make sure to re-interrupt the thread so that the next
139 // call to Thread.sleep() or Object.wait() will be interrupted.
140 Thread.currentThread().interrupt();
141 }
142 }
John Reck9481c9e2016-10-03 14:55:00 -0700143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 /**
145 * Sets the current wall time, in milliseconds. Requires the calling
146 * process to have appropriate permissions.
147 *
148 * @return if the clock was successfully set to the specified time.
149 */
Greg Hackmann38bf5142014-02-19 16:39:36 -0800150 public static boolean setCurrentTimeMillis(long millis) {
151 IBinder b = ServiceManager.getService(Context.ALARM_SERVICE);
152 IAlarmManager mgr = IAlarmManager.Stub.asInterface(b);
153 if (mgr == null) {
154 return false;
155 }
156
157 try {
158 return mgr.setTime(millis);
159 } catch (RemoteException e) {
160 Slog.e(TAG, "Unable to set RTC", e);
161 } catch (SecurityException e) {
162 Slog.e(TAG, "Unable to set RTC", e);
163 }
164
165 return false;
166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
168 /**
169 * Returns milliseconds since boot, not counting time spent in deep sleep.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 *
171 * @return milliseconds of non-sleep uptime since boot.
172 */
John Reck9481c9e2016-10-03 14:55:00 -0700173 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 native public static long uptimeMillis();
175
176 /**
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700177 * Return {@link Clock} that starts at system boot, not counting time spent
178 * in deep sleep.
179 */
180 public static @NonNull Clock uptimeMillisClock() {
181 return new Clock() {
182 @Override
183 public ZoneId getZone() {
184 return ZoneOffset.UTC;
185 }
186 @Override
187 public Clock withZone(ZoneId zone) {
188 throw new UnsupportedOperationException();
189 }
190 @Override
191 public long millis() {
192 return SystemClock.uptimeMillis();
193 }
194 @Override
195 public Instant instant() {
196 return Instant.ofEpochMilli(millis());
197 }
198 };
199 }
200
201 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 * Returns milliseconds since boot, including time spent in sleep.
203 *
204 * @return elapsed milliseconds since boot.
205 */
John Reck9481c9e2016-10-03 14:55:00 -0700206 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 native public static long elapsedRealtime();
Nick Pelly95f11582012-07-19 10:22:18 -0700208
209 /**
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700210 * Return {@link Clock} that starts at system boot, including time spent in
211 * sleep.
212 */
213 public static @NonNull Clock elapsedRealtimeClock() {
214 return new Clock() {
215 @Override
216 public ZoneId getZone() {
217 return ZoneOffset.UTC;
218 }
219 @Override
220 public Clock withZone(ZoneId zone) {
221 throw new UnsupportedOperationException();
222 }
223 @Override
224 public long millis() {
225 return SystemClock.elapsedRealtime();
226 }
227 @Override
228 public Instant instant() {
229 return Instant.ofEpochMilli(millis());
230 }
231 };
232 }
233
234 /**
Nick Pelly95f11582012-07-19 10:22:18 -0700235 * Returns nanoseconds since boot, including time spent in sleep.
236 *
237 * @return elapsed nanoseconds since boot.
238 */
John Reck9481c9e2016-10-03 14:55:00 -0700239 @CriticalNative
Philip Milne41180122012-09-26 11:29:25 -0700240 public static native long elapsedRealtimeNanos();
Nick Pelly95f11582012-07-19 10:22:18 -0700241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 /**
243 * Returns milliseconds running in the current thread.
John Reck9481c9e2016-10-03 14:55:00 -0700244 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 * @return elapsed milliseconds in the thread
246 */
John Reck9481c9e2016-10-03 14:55:00 -0700247 @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 public static native long currentThreadTimeMillis();
Romain Guy648bee12011-07-20 18:47:17 -0700249
250 /**
251 * Returns microseconds running in the current thread.
John Reck9481c9e2016-10-03 14:55:00 -0700252 *
Romain Guy648bee12011-07-20 18:47:17 -0700253 * @return elapsed microseconds in the thread
John Reck9481c9e2016-10-03 14:55:00 -0700254 *
Romain Guy648bee12011-07-20 18:47:17 -0700255 * @hide
256 */
John Reck9481c9e2016-10-03 14:55:00 -0700257 @CriticalNative
Romain Guy648bee12011-07-20 18:47:17 -0700258 public static native long currentThreadTimeMicro();
259
260 /**
261 * Returns current wall time in microseconds.
John Reck9481c9e2016-10-03 14:55:00 -0700262 *
Romain Guy648bee12011-07-20 18:47:17 -0700263 * @return elapsed microseconds in wall time
John Reck9481c9e2016-10-03 14:55:00 -0700264 *
Romain Guy648bee12011-07-20 18:47:17 -0700265 * @hide
266 */
John Reck9481c9e2016-10-03 14:55:00 -0700267 @CriticalNative
Romain Guy648bee12011-07-20 18:47:17 -0700268 public static native long currentTimeMicro();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269}