• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.annotation.UnsupportedAppUsage;
21 import android.app.IAlarmManager;
22 import android.content.Context;
23 import android.location.ILocationManager;
24 import android.location.LocationTime;
25 import android.util.Slog;
26 
27 import dalvik.annotation.optimization.CriticalNative;
28 
29 import java.time.Clock;
30 import java.time.DateTimeException;
31 import java.time.ZoneOffset;
32 
33 /**
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
46  *     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.
53  *
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
62  *     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.
65  *
66  *     <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
67  *     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  *
72  * </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  */
104 public final class SystemClock {
105     private static final String TAG = "SystemClock";
106 
107     /**
108      * This class is uninstantiable.
109      */
110     @UnsupportedAppUsage
SystemClock()111     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      */
sleep(long ms)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);
138 
139         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     }
146 
147     /**
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      */
setCurrentTimeMillis(long millis)153     public static boolean setCurrentTimeMillis(long millis) {
154         final IAlarmManager mgr = IAlarmManager.Stub
155                 .asInterface(ServiceManager.getService(Context.ALARM_SERVICE));
156         if (mgr == null) {
157             return false;
158         }
159 
160         try {
161             return mgr.setTime(millis);
162         } catch (RemoteException e) {
163             Slog.e(TAG, "Unable to set RTC", e);
164         } catch (SecurityException e) {
165             Slog.e(TAG, "Unable to set RTC", e);
166         }
167 
168         return false;
169     }
170 
171     /**
172      * Returns milliseconds since boot, not counting time spent in deep sleep.
173      *
174      * @return milliseconds of non-sleep uptime since boot.
175      */
176     @CriticalNative
uptimeMillis()177     native public static long uptimeMillis();
178 
179     /**
180      * @removed
181      */
182     @Deprecated
uptimeMillisClock()183     public static @NonNull Clock uptimeMillisClock() {
184         return uptimeClock();
185     }
186 
187     /**
188      * Return {@link Clock} that starts at system boot, not counting time spent
189      * in deep sleep.
190      *
191      * @removed
192      */
uptimeClock()193     public static @NonNull Clock uptimeClock() {
194         return new SimpleClock(ZoneOffset.UTC) {
195             @Override
196             public long millis() {
197                 return SystemClock.uptimeMillis();
198             }
199         };
200     }
201 
202     /**
203      * Returns milliseconds since boot, including time spent in sleep.
204      *
205      * @return elapsed milliseconds since boot.
206      */
207     @CriticalNative
208     native public static long elapsedRealtime();
209 
210     /**
211      * Return {@link Clock} that starts at system boot, including time spent in
212      * sleep.
213      *
214      * @removed
215      */
216     public static @NonNull Clock elapsedRealtimeClock() {
217         return new SimpleClock(ZoneOffset.UTC) {
218             @Override
219             public long millis() {
220                 return SystemClock.elapsedRealtime();
221             }
222         };
223     }
224 
225     /**
226      * Returns nanoseconds since boot, including time spent in sleep.
227      *
228      * @return elapsed nanoseconds since boot.
229      */
230     @CriticalNative
231     public static native long elapsedRealtimeNanos();
232 
233     /**
234      * Returns milliseconds running in the current thread.
235      *
236      * @return elapsed milliseconds in the thread
237      */
238     @CriticalNative
239     public static native long currentThreadTimeMillis();
240 
241     /**
242      * Returns microseconds running in the current thread.
243      *
244      * @return elapsed microseconds in the thread
245      *
246      * @hide
247      */
248     @UnsupportedAppUsage
249     @CriticalNative
250     public static native long currentThreadTimeMicro();
251 
252     /**
253      * Returns current wall time in  microseconds.
254      *
255      * @return elapsed microseconds in wall time
256      *
257      * @hide
258      */
259     @UnsupportedAppUsage
260     @CriticalNative
261     public static native long currentTimeMicro();
262 
263     /**
264      * Returns milliseconds since January 1, 1970 00:00:00.0 UTC, synchronized
265      * using a remote network source outside the device.
266      * <p>
267      * While the time returned by {@link System#currentTimeMillis()} can be
268      * adjusted by the user, the time returned by this method cannot be adjusted
269      * by the user. Note that synchronization may occur using an insecure
270      * network protocol, so the returned time should not be used for security
271      * purposes.
272      * <p>
273      * This performs no blocking network operations and returns values based on
274      * a recent successful synchronization event; it will either return a valid
275      * time or throw.
276      *
277      * @throws DateTimeException when no accurate network time can be provided.
278      * @hide
279      */
280     public static long currentNetworkTimeMillis() {
281         final IAlarmManager mgr = IAlarmManager.Stub
282                 .asInterface(ServiceManager.getService(Context.ALARM_SERVICE));
283         if (mgr != null) {
284             try {
285                 return mgr.currentNetworkTimeMillis();
286             } catch (ParcelableException e) {
287                 e.maybeRethrow(DateTimeException.class);
288                 throw new RuntimeException(e);
289             } catch (RemoteException e) {
290                 throw e.rethrowFromSystemServer();
291             }
292         } else {
293             throw new RuntimeException(new DeadSystemException());
294         }
295     }
296 
297     /**
298      * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
299      * synchronized using a remote network source outside the device.
300      * <p>
301      * While the time returned by {@link System#currentTimeMillis()} can be
302      * adjusted by the user, the time returned by this method cannot be adjusted
303      * by the user. Note that synchronization may occur using an insecure
304      * network protocol, so the returned time should not be used for security
305      * purposes.
306      * <p>
307      * This performs no blocking network operations and returns values based on
308      * a recent successful synchronization event; it will either return a valid
309      * time or throw.
310      *
311      * @throws DateTimeException when no accurate network time can be provided.
312      * @hide
313      */
314     public static @NonNull Clock currentNetworkTimeClock() {
315         return new SimpleClock(ZoneOffset.UTC) {
316             @Override
317             public long millis() {
318                 return SystemClock.currentNetworkTimeMillis();
319             }
320         };
321     }
322 
323     /**
324      * Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
325      * synchronized using the device's location provider.
326      *
327      * @throws DateTimeException when the location provider has not had a location fix since boot.
328      */
329     public static @NonNull Clock currentGnssTimeClock() {
330         return new SimpleClock(ZoneOffset.UTC) {
331             private final ILocationManager mMgr = ILocationManager.Stub
332                     .asInterface(ServiceManager.getService(Context.LOCATION_SERVICE));
333             @Override
334             public long millis() {
335                 LocationTime time;
336                 try {
337                     time = mMgr.getGnssTimeMillis();
338                 } catch (RemoteException e) {
339                     e.rethrowFromSystemServer();
340                     return 0;
341                 }
342                 if (time == null) {
343                     throw new DateTimeException("Gnss based time is not available.");
344                 }
345                 long currentNanos = elapsedRealtimeNanos();
346                 long deltaMs = (currentNanos - time.getElapsedRealtimeNanos()) / 1000000L;
347                 return time.getTime() + deltaMs;
348             }
349         };
350     }
351 }
352