1 /*
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 
17 package android.os;
18 
19 import android.annotation.NonNull;
20 import android.app.IAlarmManager;
21 import android.app.time.UnixEpochTime;
22 import android.app.timedetector.ITimeDetectorService;
23 import android.compat.annotation.UnsupportedAppUsage;
24 import android.content.Context;
25 import android.location.ILocationManager;
26 import android.location.LocationTime;
27 import android.util.Slog;
28 
29 import dalvik.annotation.optimization.CriticalNative;
30 
31 import java.time.Clock;
32 import java.time.DateTimeException;
33 import java.time.ZoneOffset;
34 
35 /**
36  * Core timekeeping facilities.
37  *
38  * <p> Three different clocks are available, and they should not be confused:
39  *
40  * <ul>
41  *     <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
42  *     is the standard "wall" clock (time and date) expressing milliseconds
43  *     since the epoch.  The wall clock can be set by the user or the phone
44  *     network (see {@link #setCurrentTimeMillis}), so the time may jump
45  *     backwards or forwards unpredictably.  This clock should only be used
46  *     when correspondence with real-world dates and times is important, such
47  *     as in a calendar or alarm clock application.  Interval or elapsed
48  *     time measurements should use a different clock.  If you are using
49  *     System.currentTimeMillis(), consider listening to the
50  *     {@link android.content.Intent#ACTION_TIME_TICK ACTION_TIME_TICK},
51  *     {@link android.content.Intent#ACTION_TIME_CHANGED ACTION_TIME_CHANGED}
52  *     and {@link android.content.Intent#ACTION_TIMEZONE_CHANGED
53  *     ACTION_TIMEZONE_CHANGED} {@link android.content.Intent Intent}
54  *     broadcasts to find out when the time changes.
55  *
56  *     <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
57  *     system was booted.  This clock stops when the system enters deep
58  *     sleep (CPU off, display dark, device waiting for external input),
59  *     but is not affected by clock scaling, idle, or other power saving
60  *     mechanisms.  This is the basis for most interval timing
61  *     such as {@link Thread#sleep(long) Thread.sleep(millls)},
62  *     {@link Object#wait(long) Object.wait(millis)}, and
63  *     {@link System#nanoTime System.nanoTime()}.  This clock is guaranteed
64  *     to be monotonic, and is suitable for interval timing when the
65  *     interval does not span device sleep.  Most methods that accept a
66  *     timestamp value currently expect the {@link #uptimeMillis} clock.
67  *
68  *     <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
69  *     return the time since the system was booted, and include deep sleep.
70  *     This clock is guaranteed to be monotonic, and continues to tick even
71  *     when the CPU is in power saving modes, so is the recommend basis
72  *     for general purpose interval timing.
73  *
74  * </ul>
75  *
76  * There are several mechanisms for controlling the timing of events:
77  *
78  * <ul>
79  *     <li> <p> Standard functions like {@link Thread#sleep(long)
80  *     Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
81  *     are always available.  These functions use the {@link #uptimeMillis}
82  *     clock; if the device enters sleep, the remainder of the time will be
83  *     postponed until the device wakes up.  These synchronous functions may
84  *     be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
85  *     you must handle {@link InterruptedException}.
86  *
87  *     <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
88  *     very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
89  *     ignores {@link InterruptedException}.  Use this function for delays if
90  *     you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
91  *     preserve the interrupted state of the thread.
92  *
93  *     <li> <p> The {@link android.os.Handler} class can schedule asynchronous
94  *     callbacks at an absolute or relative time.  Handler objects also use the
95  *     {@link #uptimeMillis} clock, and require an {@link android.os.Looper
96  *     event loop} (normally present in any GUI application).
97  *
98  *     <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
99  *     recurring events which occur even when the device is in deep sleep
100  *     or your application is not running.  Events may be scheduled with your
101  *     choice of {@link java.lang.System#currentTimeMillis} (RTC) or
102  *     {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
103  *     {@link android.content.Intent} broadcast when they occur.
104  * </ul>
105  */
106 public final class SystemClock {
107     private static final String TAG = "SystemClock";
108 
109     private static volatile IAlarmManager sIAlarmManager;
110 
111     /**
112      * This class is uninstantiable.
113      */
114     @UnsupportedAppUsage
SystemClock()115     private SystemClock() {
116         // This space intentionally left blank.
117     }
118 
119     /**
120      * Waits a given number of milliseconds (of uptimeMillis) before returning.
121      * Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
122      * {@link InterruptedException}; {@link Thread#interrupt()} events are
123      * deferred until the next interruptible operation.  Does not return until
124      * at least the specified number of milliseconds has elapsed.
125      *
126      * @param ms to sleep before returning, in milliseconds of uptime.
127      */
sleep(long ms)128     public static void sleep(long ms)
129     {
130         long start = uptimeMillis();
131         long duration = ms;
132         boolean interrupted = false;
133         do {
134             try {
135                 Thread.sleep(duration);
136             }
137             catch (InterruptedException e) {
138                 interrupted = true;
139             }
140             duration = start + ms - uptimeMillis();
141         } while (duration > 0);
142 
143         if (interrupted) {
144             // Important: we don't want to quietly eat an interrupt() event,
145             // so we make sure to re-interrupt the thread so that the next
146             // call to Thread.sleep() or Object.wait() will be interrupted.
147             Thread.currentThread().interrupt();
148         }
149     }
150 
151     /**
152      * Sets the current wall time, in milliseconds.  Requires the calling
153      * process to have appropriate permissions.
154      *
155      * @return if the clock was successfully set to the specified time.
156      */
setCurrentTimeMillis(long millis)157     public static boolean setCurrentTimeMillis(long millis) {
158         final IAlarmManager mgr = getIAlarmManager();
159         if (mgr == null) {
160             Slog.e(TAG, "Unable to set RTC: mgr == null");
161             return false;
162         }
163 
164         try {
165             return mgr.setTime(millis);
166         } catch (RemoteException e) {
167             Slog.e(TAG, "Unable to set RTC", e);
168         } catch (SecurityException e) {
169             Slog.e(TAG, "Unable to set RTC", e);
170         }
171 
172         return false;
173     }
174 
getIAlarmManager()175     private static IAlarmManager getIAlarmManager() {
176         if (sIAlarmManager == null) {
177             sIAlarmManager = IAlarmManager.Stub
178                     .asInterface(ServiceManager.getService(Context.ALARM_SERVICE));
179         }
180         return sIAlarmManager;
181     }
182 
183     /**
184      * Returns milliseconds since boot, not counting time spent in deep sleep.
185      *
186      * @return milliseconds of non-sleep uptime since boot.
187      */
188     @CriticalNative
uptimeMillis()189     native public static long uptimeMillis();
190 
191     /**
192      * Returns nanoseconds since boot, not counting time spent in deep sleep.
193      *
194      * @return nanoseconds of non-sleep uptime since boot.
195      * @hide
196      */
197     @CriticalNative
uptimeNanos()198     public static native long uptimeNanos();
199 
200     /**
201      * Return {@link Clock} that starts at system boot, not counting time spent
202      * in deep sleep.
203      *
204      * @removed
205      */
uptimeClock()206     public static @NonNull Clock uptimeClock() {
207         return new SimpleClock(ZoneOffset.UTC) {
208             @Override
209             public long millis() {
210                 return SystemClock.uptimeMillis();
211             }
212         };
213     }
214 
215     /**
216      * Returns milliseconds since boot, including time spent in sleep.
217      *
218      * @return elapsed milliseconds since boot.
219      */
220     @CriticalNative
221     native public static long elapsedRealtime();
222 
223     /**
224      * Return {@link Clock} that starts at system boot, including time spent in
225      * sleep.
226      *
227      * @removed
228      */
229     public static @NonNull Clock elapsedRealtimeClock() {
230         return new SimpleClock(ZoneOffset.UTC) {
231             @Override
232             public long millis() {
233                 return SystemClock.elapsedRealtime();
234             }
235         };
236     }
237 
238     /**
239      * Returns nanoseconds since boot, including time spent in sleep.
240      *
241      * @return elapsed nanoseconds since boot.
242      */
243     @CriticalNative
244     public static native long elapsedRealtimeNanos();
245 
246     /**
247      * Returns milliseconds running in the current thread.
248      *
249      * @return elapsed milliseconds in the thread
250      */
251     @CriticalNative
252     public static native long currentThreadTimeMillis();
253 
254     /**
255      * Returns microseconds running in the current thread.
256      *
257      * @return elapsed microseconds in the thread
258      *
259      * @hide
260      */
261     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
262     @CriticalNative
263     public static native long currentThreadTimeMicro();
264 
265     /**
266      * Returns current wall time in  microseconds.
267      *
268      * @return elapsed microseconds in wall time
269      *
270      * @hide
271      */
272     @UnsupportedAppUsage
273     @CriticalNative
274     public static native long currentTimeMicro();
275 
276     /**
277      * Returns milliseconds since January 1, 1970 00:00:00.0 UTC, synchronized
278      * using a remote network source outside the device.
279      * <p>
280      * While the time returned by {@link System#currentTimeMillis()} can be
281      * adjusted by the user, the time returned by this method cannot be adjusted
282      * by the user.
283      * <p>
284      * This performs no blocking network operations and returns values based on
285      * a recent successful synchronization event; it will either return a valid
286      * time or throw.
287      * <p>
288      * Note that synchronization may occur using an insecure network protocol,
289      * so the returned time should not be used for security purposes.
290      * The device may resynchronize with the same or different network source
291      * at any time. Due to network delays, variations between servers, or local
292      * (client side) clock drift, the accuracy of the returned times cannot be
293      * guaranteed. In extreme cases, consecutive calls to {@link
294      * #currentNetworkTimeMillis()} could return times that are out of order.
295      *
296      * @throws DateTimeException when no network time can be provided.
297      * @hide
298      */
299     public static long currentNetworkTimeMillis() {
300         ITimeDetectorService timeDetectorService = ITimeDetectorService.Stub
301                 .asInterface(ServiceManager.getService(Context.TIME_DETECTOR_SERVICE));
302         if (timeDetectorService != null) {
303             UnixEpochTime time;
304             try {
305                 time = timeDetectorService.latestNetworkTime();
306             } catch (ParcelableException e) {
307                 e.maybeRethrow(DateTimeException.class);
308                 throw new RuntimeException(e);
309             } catch (RemoteException e) {
310                 throw e.rethrowFromSystemServer();
311             }
312 
313             if (time == null) {
314                 // This is not expected.
315                 throw new DateTimeException("Network based time is not available.");
316             }
317             long currentMillis = elapsedRealtime();
318             long deltaMs = currentMillis - time.getElapsedRealtimeMillis();
319             return time.getUnixEpochTimeMillis() + deltaMs;
320         } else {
321             throw new RuntimeException(new DeadSystemException());
322         }
323     }
324 
325    /**
326      * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
327      * synchronized using a remote network source outside the device.
328      * <p>
329      * While the time returned by {@link System#currentTimeMillis()} can be
330      * adjusted by the user, the time returned by this method cannot be adjusted
331      * by the user.
332      * <p>
333      * This performs no blocking network operations and returns values based on
334      * a recent successful synchronization event; it will either return a valid
335      * time or throw.
336      * <p>
337      * Note that synchronization may occur using an insecure network protocol,
338      * so the returned time should not be used for security purposes.
339      * The device may resynchronize with the same or different network source
340      * at any time. Due to network delays, variations between servers, or local
341      * (client side) clock drift, the accuracy of the returned times cannot be
342      * guaranteed. In extreme cases, consecutive calls to {@link
343      * Clock#millis()} on the returned {@link Clock}could return times that are
344      * out of order.
345      *
346      * @throws DateTimeException when no network time can be provided.
347      */
348     public static @NonNull Clock currentNetworkTimeClock() {
349         return new SimpleClock(ZoneOffset.UTC) {
350             @Override
351             public long millis() {
352                 return SystemClock.currentNetworkTimeMillis();
353             }
354         };
355     }
356 
357     /**
358      * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
359      * synchronized using the device's location provider.
360      *
361      * @throws DateTimeException when the location provider has not had a location fix since boot.
362      */
363     public static @NonNull Clock currentGnssTimeClock() {
364         return new SimpleClock(ZoneOffset.UTC) {
365             private final ILocationManager mMgr = ILocationManager.Stub
366                     .asInterface(ServiceManager.getService(Context.LOCATION_SERVICE));
367             @Override
368             public long millis() {
369                 LocationTime time;
370                 try {
371                     time = mMgr.getGnssTimeMillis();
372                 } catch (RemoteException e) {
373                     throw e.rethrowFromSystemServer();
374                 }
375                 if (time == null) {
376                     throw new DateTimeException("Gnss based time is not available.");
377                 }
378                 long currentNanos = elapsedRealtimeNanos();
379                 long deltaMs = (currentNanos - time.getElapsedRealtimeNanos()) / 1000000L;
380                 return time.getUnixEpochTimeMillis() + deltaMs;
381             }
382         };
383     }
384 }
385