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