1 /* 2 * Copyright (C) 2007 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.Manifest.permission; 20 import android.annotation.CallbackExecutor; 21 import android.annotation.CurrentTimeMillisLong; 22 import android.annotation.IntDef; 23 import android.annotation.IntRange; 24 import android.annotation.NonNull; 25 import android.annotation.Nullable; 26 import android.annotation.RequiresPermission; 27 import android.annotation.SdkConstant; 28 import android.annotation.SystemApi; 29 import android.annotation.SystemService; 30 import android.annotation.TestApi; 31 import android.app.PropertyInvalidatedCache; 32 import android.compat.annotation.UnsupportedAppUsage; 33 import android.content.Context; 34 import android.service.dreams.Sandman; 35 import android.sysprop.InitProperties; 36 import android.util.ArrayMap; 37 import android.util.Log; 38 import android.util.proto.ProtoOutputStream; 39 40 import com.android.internal.util.Preconditions; 41 42 import java.lang.annotation.Retention; 43 import java.lang.annotation.RetentionPolicy; 44 import java.util.concurrent.Executor; 45 import java.util.concurrent.atomic.AtomicLong; 46 47 /** 48 * This class gives you control of the power state of the device. 49 * 50 * <p> 51 * <b>Device battery life will be significantly affected by the use of this API.</b> 52 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels 53 * possible, and be sure to release them as soon as possible. In most cases, 54 * you'll want to use 55 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead. 56 * 57 * <p> 58 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK} 59 * permission in an {@code <uses-permission>} element of the application's manifest. 60 * </p> 61 */ 62 @SystemService(Context.POWER_SERVICE) 63 public final class PowerManager { 64 private static final String TAG = "PowerManager"; 65 66 /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few 67 * combinations were actually supported so the bit field was removed. This explains 68 * why the numbering scheme is so odd. If adding a new wake lock level, any unused 69 * value (in frameworks/base/core/proto/android/os/enums.proto) can be used. 70 */ 71 72 /** 73 * Wake lock level: Ensures that the CPU is running; the screen and keyboard 74 * backlight will be allowed to go off. 75 * <p> 76 * If the user presses the power button, then the screen will be turned off 77 * but the CPU will be kept on until all partial wake locks have been released. 78 * </p> 79 */ 80 public static final int PARTIAL_WAKE_LOCK = OsProtoEnums.PARTIAL_WAKE_LOCK; // 0x00000001 81 82 /** 83 * Wake lock level: Ensures that the screen is on (but may be dimmed); 84 * the keyboard backlight will be allowed to go off. 85 * <p> 86 * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be 87 * implicitly released by the system, causing both the screen and the CPU to be turned off. 88 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 89 * </p> 90 * 91 * @deprecated Most applications should use 92 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 93 * of this type of wake lock, as it will be correctly managed by the platform 94 * as the user moves between applications and doesn't require a special permission. 95 */ 96 @Deprecated 97 public static final int SCREEN_DIM_WAKE_LOCK = OsProtoEnums.SCREEN_DIM_WAKE_LOCK; // 0x00000006 98 99 /** 100 * Wake lock level: Ensures that the screen is on at full brightness; 101 * the keyboard backlight will be allowed to go off. 102 * <p> 103 * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be 104 * implicitly released by the system, causing both the screen and the CPU to be turned off. 105 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 106 * </p> 107 * 108 * @deprecated Most applications should use 109 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 110 * of this type of wake lock, as it will be correctly managed by the platform 111 * as the user moves between applications and doesn't require a special permission. 112 */ 113 @Deprecated 114 public static final int SCREEN_BRIGHT_WAKE_LOCK = 115 OsProtoEnums.SCREEN_BRIGHT_WAKE_LOCK; // 0x0000000a 116 117 /** 118 * Wake lock level: Ensures that the screen and keyboard backlight are on at 119 * full brightness. 120 * <p> 121 * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be 122 * implicitly released by the system, causing both the screen and the CPU to be turned off. 123 * Contrast with {@link #PARTIAL_WAKE_LOCK}. 124 * </p> 125 * 126 * @deprecated Most applications should use 127 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead 128 * of this type of wake lock, as it will be correctly managed by the platform 129 * as the user moves between applications and doesn't require a special permission. 130 */ 131 @Deprecated 132 public static final int FULL_WAKE_LOCK = OsProtoEnums.FULL_WAKE_LOCK; // 0x0000001a 133 134 /** 135 * Wake lock level: Turns the screen off when the proximity sensor activates. 136 * <p> 137 * If the proximity sensor detects that an object is nearby, the screen turns off 138 * immediately. Shortly after the object moves away, the screen turns on again. 139 * </p><p> 140 * A proximity wake lock does not prevent the device from falling asleep 141 * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and 142 * {@link #SCREEN_DIM_WAKE_LOCK}. If there is no user activity and no other 143 * wake locks are held, then the device will fall asleep (and lock) as usual. 144 * However, the device will not fall asleep while the screen has been turned off 145 * by the proximity sensor because it effectively counts as ongoing user activity. 146 * </p><p> 147 * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported} 148 * to determine whether this wake lock level is supported. 149 * </p><p> 150 * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}. 151 * </p> 152 */ 153 public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 154 OsProtoEnums.PROXIMITY_SCREEN_OFF_WAKE_LOCK; // 0x00000020 155 156 /** 157 * Wake lock level: Put the screen in a low power state and allow the CPU to suspend 158 * if no other wake locks are held. 159 * <p> 160 * This is used by the dream manager to implement doze mode. It currently 161 * has no effect unless the power manager is in the dozing state. 162 * </p><p> 163 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 164 * </p> 165 * 166 * {@hide} 167 */ 168 public static final int DOZE_WAKE_LOCK = OsProtoEnums.DOZE_WAKE_LOCK; // 0x00000040 169 170 /** 171 * Wake lock level: Keep the device awake enough to allow drawing to occur. 172 * <p> 173 * This is used by the window manager to allow applications to draw while the 174 * system is dozing. It currently has no effect unless the power manager is in 175 * the dozing state. 176 * </p><p> 177 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 178 * </p> 179 * 180 * {@hide} 181 */ 182 public static final int DRAW_WAKE_LOCK = OsProtoEnums.DRAW_WAKE_LOCK; // 0x00000080 183 184 /** 185 * Mask for the wake lock level component of a combined wake lock level and flags integer. 186 * 187 * @hide 188 */ 189 public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff; 190 191 /** 192 * Wake lock flag: Turn the screen on when the wake lock is acquired. 193 * <p> 194 * Normally wake locks don't actually wake the device, they just cause 195 * the screen to remain on once it's already on. Think of the video player 196 * application as the normal behavior. Notifications that pop up and want 197 * the device to be on are the exception; use this flag to be like them. 198 * </p><p> 199 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}. 200 * </p> 201 */ 202 public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000; 203 204 /** 205 * Wake lock flag: When this wake lock is released, poke the user activity timer 206 * so the screen stays on for a little longer. 207 * <p> 208 * Will not turn the screen on if it is not already on. 209 * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that. 210 * </p><p> 211 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}. 212 * </p> 213 */ 214 public static final int ON_AFTER_RELEASE = 0x20000000; 215 216 /** 217 * Wake lock flag: This wake lock is not important for logging events. If a later 218 * wake lock is acquired that is important, it will be considered the one to log. 219 * @hide 220 */ 221 public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000; 222 223 /** 224 * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a 225 * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor 226 * indicates that an object is not in close proximity. 227 */ 228 public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1 << 0; 229 230 /** 231 * Flag for {@link WakeLock#release(int)} when called due to timeout. 232 * @hide 233 */ 234 public static final int RELEASE_FLAG_TIMEOUT = 1 << 16; 235 236 /** 237 * Brightness value for fully on. 238 * @hide 239 */ 240 @UnsupportedAppUsage 241 public static final int BRIGHTNESS_ON = 255; 242 243 /** 244 * Brightness value for fully off. 245 * @hide 246 */ 247 public static final int BRIGHTNESS_OFF = 0; 248 249 /** 250 * Brightness value for default policy handling by the system. 251 * @hide 252 */ 253 public static final int BRIGHTNESS_DEFAULT = -1; 254 255 /** 256 * Brightness value for an invalid value having been stored. 257 * @hide 258 */ 259 public static final int BRIGHTNESS_INVALID = -1; 260 261 //Brightness values for new float implementation: 262 /** 263 * Brightness value for fully on as float. 264 * @hide 265 */ 266 public static final float BRIGHTNESS_MAX = 1.0f; 267 268 /** 269 * Brightness value for minimum valid brightness as float. 270 * @hide 271 */ 272 public static final float BRIGHTNESS_MIN = 0.0f; 273 274 /** 275 * Brightness value for fully off in float. 276 * TODO(brightnessfloat): rename this to BRIGHTNES_OFF and remove the integer-based constant. 277 * @hide 278 */ 279 public static final float BRIGHTNESS_OFF_FLOAT = -1.0f; 280 281 /** 282 * Invalid brightness value. 283 * @hide 284 */ 285 public static final float BRIGHTNESS_INVALID_FLOAT = Float.NaN; 286 287 // Note: Be sure to update android.os.BatteryStats and PowerManager.h 288 // if adding or modifying user activity event constants. 289 290 /** 291 * User activity event type: Unspecified event type. 292 * @hide 293 */ 294 @SystemApi 295 public static final int USER_ACTIVITY_EVENT_OTHER = 0; 296 297 /** 298 * User activity event type: Button or key pressed or released. 299 * @hide 300 */ 301 @SystemApi 302 public static final int USER_ACTIVITY_EVENT_BUTTON = 1; 303 304 /** 305 * User activity event type: Touch down, move or up. 306 * @hide 307 */ 308 @SystemApi 309 public static final int USER_ACTIVITY_EVENT_TOUCH = 2; 310 311 /** 312 * User activity event type: Accessibility taking action on behalf of user. 313 * @hide 314 */ 315 @SystemApi 316 public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3; 317 318 /** 319 * User activity event type: {@link android.service.attention.AttentionService} taking action 320 * on behalf of user. 321 * @hide 322 */ 323 public static final int USER_ACTIVITY_EVENT_ATTENTION = 4; 324 325 /** 326 * User activity flag: If already dimmed, extend the dim timeout 327 * but do not brighten. This flag is useful for keeping the screen on 328 * a little longer without causing a visible change such as when 329 * the power key is pressed. 330 * @hide 331 */ 332 @SystemApi 333 public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0; 334 335 /** 336 * User activity flag: Note the user activity as usual but do not 337 * reset the user activity timeout. This flag is useful for applying 338 * user activity power hints when interacting with the device indirectly 339 * on a secondary screen while allowing the primary screen to go to sleep. 340 * @hide 341 */ 342 @SystemApi 343 public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1; 344 345 /** 346 * @hide 347 */ 348 public static final int GO_TO_SLEEP_REASON_MIN = 0; 349 350 /** 351 * Go to sleep reason code: Going to sleep due by application request. 352 * @hide 353 */ 354 public static final int GO_TO_SLEEP_REASON_APPLICATION = GO_TO_SLEEP_REASON_MIN; 355 356 /** 357 * Go to sleep reason code: Going to sleep due by request of the 358 * device administration policy. 359 * @hide 360 */ 361 public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1; 362 363 /** 364 * Go to sleep reason code: Going to sleep due to a screen timeout. 365 * @hide 366 */ 367 @UnsupportedAppUsage 368 public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2; 369 370 /** 371 * Go to sleep reason code: Going to sleep due to the lid switch being closed. 372 * @hide 373 */ 374 public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3; 375 376 /** 377 * Go to sleep reason code: Going to sleep due to the power button being pressed. 378 * @hide 379 */ 380 public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4; 381 382 /** 383 * Go to sleep reason code: Going to sleep due to HDMI. 384 * @hide 385 */ 386 public static final int GO_TO_SLEEP_REASON_HDMI = 5; 387 388 /** 389 * Go to sleep reason code: Going to sleep due to the sleep button being pressed. 390 * @hide 391 */ 392 public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6; 393 394 /** 395 * Go to sleep reason code: Going to sleep by request of an accessibility service 396 * @hide 397 */ 398 public static final int GO_TO_SLEEP_REASON_ACCESSIBILITY = 7; 399 400 /** 401 * Go to sleep reason code: Going to sleep due to force-suspend. 402 * @hide 403 */ 404 public static final int GO_TO_SLEEP_REASON_FORCE_SUSPEND = 8; 405 406 /** 407 * Go to sleep reason code: Going to sleep due to user inattentiveness. 408 * @hide 409 */ 410 public static final int GO_TO_SLEEP_REASON_INATTENTIVE = 9; 411 412 /** 413 * Go to sleep reason code: Going to sleep due to quiescent boot. 414 * @hide 415 */ 416 public static final int GO_TO_SLEEP_REASON_QUIESCENT = 10; 417 418 /** 419 * @hide 420 */ 421 public static final int GO_TO_SLEEP_REASON_MAX = GO_TO_SLEEP_REASON_QUIESCENT; 422 423 /** 424 * @hide 425 */ sleepReasonToString(int sleepReason)426 public static String sleepReasonToString(int sleepReason) { 427 switch (sleepReason) { 428 case GO_TO_SLEEP_REASON_APPLICATION: return "application"; 429 case GO_TO_SLEEP_REASON_DEVICE_ADMIN: return "device_admin"; 430 case GO_TO_SLEEP_REASON_TIMEOUT: return "timeout"; 431 case GO_TO_SLEEP_REASON_LID_SWITCH: return "lid_switch"; 432 case GO_TO_SLEEP_REASON_POWER_BUTTON: return "power_button"; 433 case GO_TO_SLEEP_REASON_HDMI: return "hdmi"; 434 case GO_TO_SLEEP_REASON_SLEEP_BUTTON: return "sleep_button"; 435 case GO_TO_SLEEP_REASON_ACCESSIBILITY: return "accessibility"; 436 case GO_TO_SLEEP_REASON_FORCE_SUSPEND: return "force_suspend"; 437 case GO_TO_SLEEP_REASON_INATTENTIVE: return "inattentive"; 438 default: return Integer.toString(sleepReason); 439 } 440 } 441 442 /** 443 * Go to sleep flag: Skip dozing state and directly go to full sleep. 444 * @hide 445 */ 446 public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0; 447 448 /** 449 * @hide 450 */ 451 @IntDef(prefix = { "BRIGHTNESS_CONSTRAINT_TYPE" }, value = { 452 BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM, 453 BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM, 454 BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT, 455 BRIGHTNESS_CONSTRAINT_TYPE_DIM, 456 BRIGHTNESS_CONSTRAINT_TYPE_DOZE, 457 BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR, 458 BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR, 459 BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT_VR 460 }) 461 @Retention(RetentionPolicy.SOURCE) 462 public @interface BrightnessConstraint{} 463 464 /** 465 * Brightness constraint type: minimum allowed value. 466 * @hide 467 */ 468 public static final int BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM = 0; 469 /** 470 * Brightness constraint type: minimum allowed value. 471 * @hide 472 */ 473 public static final int BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM = 1; 474 475 /** 476 * Brightness constraint type: minimum allowed value. 477 * @hide 478 */ 479 public static final int BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT = 2; 480 481 /** 482 * Brightness constraint type: minimum allowed value. 483 * @hide 484 */ 485 public static final int BRIGHTNESS_CONSTRAINT_TYPE_DIM = 3; 486 487 /** 488 * Brightness constraint type: minimum allowed value. 489 * @hide 490 */ 491 public static final int BRIGHTNESS_CONSTRAINT_TYPE_DOZE = 4; 492 493 /** 494 * Brightness constraint type: minimum allowed value. 495 * @hide 496 */ 497 public static final int BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR = 5; 498 499 /** 500 * Brightness constraint type: minimum allowed value. 501 * @hide 502 */ 503 public static final int BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR = 6; 504 505 /** 506 * Brightness constraint type: minimum allowed value. 507 * @hide 508 */ 509 public static final int BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT_VR = 7; 510 511 /** 512 * @hide 513 */ 514 @IntDef(prefix = { "WAKE_REASON_" }, value = { 515 WAKE_REASON_UNKNOWN, 516 WAKE_REASON_POWER_BUTTON, 517 WAKE_REASON_APPLICATION, 518 WAKE_REASON_PLUGGED_IN, 519 WAKE_REASON_GESTURE, 520 WAKE_REASON_CAMERA_LAUNCH, 521 WAKE_REASON_WAKE_KEY, 522 WAKE_REASON_WAKE_MOTION, 523 WAKE_REASON_HDMI, 524 }) 525 @Retention(RetentionPolicy.SOURCE) 526 public @interface WakeReason{} 527 528 /** 529 * Wake up reason code: Waking for an unknown reason. 530 * @hide 531 */ 532 public static final int WAKE_REASON_UNKNOWN = 0; 533 534 /** 535 * Wake up reason code: Waking up due to power button press. 536 * @hide 537 */ 538 public static final int WAKE_REASON_POWER_BUTTON = 1; 539 540 /** 541 * Wake up reason code: Waking up because an application requested it. 542 * @hide 543 */ 544 public static final int WAKE_REASON_APPLICATION = 2; 545 546 /** 547 * Wake up reason code: Waking up due to being plugged in or docked on a wireless charger. 548 * @hide 549 */ 550 public static final int WAKE_REASON_PLUGGED_IN = 3; 551 552 /** 553 * Wake up reason code: Waking up due to a user performed gesture (e.g. douple tapping on the 554 * screen). 555 * @hide 556 */ 557 public static final int WAKE_REASON_GESTURE = 4; 558 559 /** 560 * Wake up reason code: Waking up due to the camera being launched. 561 * @hide 562 */ 563 public static final int WAKE_REASON_CAMERA_LAUNCH = 5; 564 565 /** 566 * Wake up reason code: Waking up because a wake key other than power was pressed. 567 * @hide 568 */ 569 public static final int WAKE_REASON_WAKE_KEY = 6; 570 571 /** 572 * Wake up reason code: Waking up because a wake motion was performed. 573 * 574 * For example, a trackball that was set to wake the device up was spun. 575 * @hide 576 */ 577 public static final int WAKE_REASON_WAKE_MOTION = 7; 578 579 /** 580 * Wake up reason code: Waking due to HDMI. 581 * @hide 582 */ 583 public static final int WAKE_REASON_HDMI = 8; 584 585 /** 586 * Wake up reason code: Waking due to the lid being opened. 587 * @hide 588 */ 589 public static final int WAKE_REASON_LID = 9; 590 591 /** 592 * Convert the wake reason to a string for debugging purposes. 593 * @hide 594 */ wakeReasonToString(@akeReason int wakeReason)595 public static String wakeReasonToString(@WakeReason int wakeReason) { 596 switch (wakeReason) { 597 case WAKE_REASON_UNKNOWN: return "WAKE_REASON_UNKNOWN"; 598 case WAKE_REASON_POWER_BUTTON: return "WAKE_REASON_POWER_BUTTON"; 599 case WAKE_REASON_APPLICATION: return "WAKE_REASON_APPLICATION"; 600 case WAKE_REASON_PLUGGED_IN: return "WAKE_REASON_PLUGGED_IN"; 601 case WAKE_REASON_GESTURE: return "WAKE_REASON_GESTURE"; 602 case WAKE_REASON_CAMERA_LAUNCH: return "WAKE_REASON_CAMERA_LAUNCH"; 603 case WAKE_REASON_WAKE_KEY: return "WAKE_REASON_WAKE_KEY"; 604 case WAKE_REASON_WAKE_MOTION: return "WAKE_REASON_WAKE_MOTION"; 605 case WAKE_REASON_HDMI: return "WAKE_REASON_HDMI"; 606 case WAKE_REASON_LID: return "WAKE_REASON_LID"; 607 default: return Integer.toString(wakeReason); 608 } 609 } 610 611 /** 612 * @hide 613 */ 614 public static class WakeData { WakeData(long wakeTime, @WakeReason int wakeReason)615 public WakeData(long wakeTime, @WakeReason int wakeReason) { 616 this.wakeTime = wakeTime; 617 this.wakeReason = wakeReason; 618 } 619 public long wakeTime; 620 public @WakeReason int wakeReason; 621 } 622 623 /** 624 * The value to pass as the 'reason' argument to reboot() to reboot into 625 * recovery mode for tasks other than applying system updates, such as 626 * doing factory resets. 627 * <p> 628 * Requires the {@link android.Manifest.permission#RECOVERY} 629 * permission (in addition to 630 * {@link android.Manifest.permission#REBOOT}). 631 * </p> 632 * @hide 633 */ 634 public static final String REBOOT_RECOVERY = "recovery"; 635 636 /** 637 * The value to pass as the 'reason' argument to reboot() to reboot into 638 * recovery mode for applying system updates. 639 * <p> 640 * Requires the {@link android.Manifest.permission#RECOVERY} 641 * permission (in addition to 642 * {@link android.Manifest.permission#REBOOT}). 643 * </p> 644 * @hide 645 */ 646 public static final String REBOOT_RECOVERY_UPDATE = "recovery-update"; 647 648 /** 649 * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on 650 * the device. 651 * @hide 652 */ 653 public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner"; 654 655 /** 656 * The 'reason' value used when rebooting in safe mode 657 * @hide 658 */ 659 public static final String REBOOT_SAFE_MODE = "safemode"; 660 661 /** 662 * The 'reason' value used for rebooting userspace. 663 * @hide 664 */ 665 @SystemApi 666 public static final String REBOOT_USERSPACE = "userspace"; 667 668 /** 669 * The 'reason' value used when rebooting the device without turning on the screen. 670 * @hide 671 */ 672 public static final String REBOOT_QUIESCENT = "quiescent"; 673 674 /** 675 * The value to pass as the 'reason' argument to android_reboot(). 676 * @hide 677 */ 678 public static final String SHUTDOWN_USER_REQUESTED = "userrequested"; 679 680 /** 681 * The value to pass as the 'reason' argument to android_reboot() when battery temperature 682 * is too high. 683 * @hide 684 */ 685 public static final String SHUTDOWN_BATTERY_THERMAL_STATE = "thermal,battery"; 686 687 /** 688 * The value to pass as the 'reason' argument to android_reboot() when device temperature 689 * is too high. 690 * @hide 691 */ 692 public static final String SHUTDOWN_THERMAL_STATE = "thermal"; 693 694 /** 695 * The value to pass as the 'reason' argument to android_reboot() when device is running 696 * critically low on battery. 697 * @hide 698 */ 699 public static final String SHUTDOWN_LOW_BATTERY = "battery"; 700 701 /** 702 * @hide 703 */ 704 @Retention(RetentionPolicy.SOURCE) 705 @IntDef(prefix = { "SHUTDOWN_REASON_" }, value = { 706 SHUTDOWN_REASON_UNKNOWN, 707 SHUTDOWN_REASON_SHUTDOWN, 708 SHUTDOWN_REASON_REBOOT, 709 SHUTDOWN_REASON_USER_REQUESTED, 710 SHUTDOWN_REASON_THERMAL_SHUTDOWN, 711 SHUTDOWN_REASON_LOW_BATTERY, 712 SHUTDOWN_REASON_BATTERY_THERMAL 713 }) 714 public @interface ShutdownReason {} 715 716 /** 717 * constant for shutdown reason being unknown. 718 * @hide 719 */ 720 public static final int SHUTDOWN_REASON_UNKNOWN = 0; 721 722 /** 723 * constant for shutdown reason being normal shutdown. 724 * @hide 725 */ 726 public static final int SHUTDOWN_REASON_SHUTDOWN = 1; 727 728 /** 729 * constant for shutdown reason being reboot. 730 * @hide 731 */ 732 public static final int SHUTDOWN_REASON_REBOOT = 2; 733 734 /** 735 * constant for shutdown reason being user requested. 736 * @hide 737 */ 738 public static final int SHUTDOWN_REASON_USER_REQUESTED = 3; 739 740 /** 741 * constant for shutdown reason being overheating. 742 * @hide 743 */ 744 public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4; 745 746 /** 747 * constant for shutdown reason being low battery. 748 * @hide 749 */ 750 public static final int SHUTDOWN_REASON_LOW_BATTERY = 5; 751 752 /** 753 * constant for shutdown reason being critical battery thermal state. 754 * @hide 755 */ 756 public static final int SHUTDOWN_REASON_BATTERY_THERMAL = 6; 757 758 /** 759 * @hide 760 */ 761 @Retention(RetentionPolicy.SOURCE) 762 @IntDef({ServiceType.LOCATION, 763 ServiceType.VIBRATION, 764 ServiceType.ANIMATION, 765 ServiceType.FULL_BACKUP, 766 ServiceType.KEYVALUE_BACKUP, 767 ServiceType.NETWORK_FIREWALL, 768 ServiceType.SCREEN_BRIGHTNESS, 769 ServiceType.SOUND, 770 ServiceType.BATTERY_STATS, 771 ServiceType.DATA_SAVER, 772 ServiceType.FORCE_ALL_APPS_STANDBY, 773 ServiceType.FORCE_BACKGROUND_CHECK, 774 ServiceType.OPTIONAL_SENSORS, 775 ServiceType.AOD, 776 ServiceType.QUICK_DOZE, 777 ServiceType.NIGHT_MODE, 778 }) 779 public @interface ServiceType { 780 int NULL = 0; 781 int LOCATION = 1; 782 int VIBRATION = 2; 783 int ANIMATION = 3; 784 int FULL_BACKUP = 4; 785 int KEYVALUE_BACKUP = 5; 786 int NETWORK_FIREWALL = 6; 787 int SCREEN_BRIGHTNESS = 7; 788 int SOUND = 8; 789 int BATTERY_STATS = 9; 790 int DATA_SAVER = 10; 791 int AOD = 14; 792 793 /** 794 * Whether to enable force-app-standby on all apps or not. 795 */ 796 int FORCE_ALL_APPS_STANDBY = 11; 797 798 /** 799 * Whether to enable background check on all apps or not. 800 */ 801 int FORCE_BACKGROUND_CHECK = 12; 802 803 /** 804 * Whether to disable non-essential sensors. (e.g. edge sensors.) 805 */ 806 int OPTIONAL_SENSORS = 13; 807 808 /** 809 * Whether to go into Deep Doze as soon as the screen turns off or not. 810 */ 811 int QUICK_DOZE = 15; 812 813 /** 814 * Whether to enable night mode when battery saver is enabled. 815 */ 816 int NIGHT_MODE = 16; 817 } 818 819 /** 820 * Either the location providers shouldn't be affected by battery saver, 821 * or battery saver is off. 822 */ 823 public static final int LOCATION_MODE_NO_CHANGE = 0; 824 825 /** 826 * In this mode, the GPS based location provider should be disabled when battery saver is on and 827 * the device is non-interactive. 828 */ 829 public static final int LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 1; 830 831 /** 832 * All location providers should be disabled when battery saver is on and 833 * the device is non-interactive. 834 */ 835 public static final int LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 2; 836 837 /** 838 * In this mode, all the location providers will be kept available, but location fixes 839 * should only be provided to foreground apps. 840 */ 841 public static final int LOCATION_MODE_FOREGROUND_ONLY = 3; 842 843 /** 844 * In this mode, location will not be turned off, but LocationManager will throttle all 845 * requests to providers when the device is non-interactive. 846 */ 847 public static final int LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 4; 848 849 /** @hide */ 850 public static final int MIN_LOCATION_MODE = LOCATION_MODE_NO_CHANGE; 851 /** @hide */ 852 public static final int MAX_LOCATION_MODE = LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF; 853 854 /** 855 * @hide 856 */ 857 @Retention(RetentionPolicy.SOURCE) 858 @IntDef(prefix = {"LOCATION_MODE_"}, value = { 859 LOCATION_MODE_NO_CHANGE, 860 LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF, 861 LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF, 862 LOCATION_MODE_FOREGROUND_ONLY, 863 LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF, 864 }) 865 public @interface LocationPowerSaveMode {} 866 867 /** @hide */ locationPowerSaveModeToString(@ocationPowerSaveMode int mode)868 public static String locationPowerSaveModeToString(@LocationPowerSaveMode int mode) { 869 switch (mode) { 870 case LOCATION_MODE_NO_CHANGE: 871 return "NO_CHANGE"; 872 case LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF: 873 return "GPS_DISABLED_WHEN_SCREEN_OFF"; 874 case LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF: 875 return "ALL_DISABLED_WHEN_SCREEN_OFF"; 876 case LOCATION_MODE_FOREGROUND_ONLY: 877 return "FOREGROUND_ONLY"; 878 case LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF: 879 return "THROTTLE_REQUESTS_WHEN_SCREEN_OFF"; 880 default: 881 return Integer.toString(mode); 882 } 883 } 884 885 private static final String CACHE_KEY_IS_POWER_SAVE_MODE_PROPERTY = 886 "cache_key.is_power_save_mode"; 887 888 private static final String CACHE_KEY_IS_INTERACTIVE_PROPERTY = "cache_key.is_interactive"; 889 890 private static final int MAX_CACHE_ENTRIES = 1; 891 892 private PropertyInvalidatedCache<Void, Boolean> mPowerSaveModeCache = 893 new PropertyInvalidatedCache<Void, Boolean>(MAX_CACHE_ENTRIES, 894 CACHE_KEY_IS_POWER_SAVE_MODE_PROPERTY) { 895 @Override 896 protected Boolean recompute(Void query) { 897 try { 898 return mService.isPowerSaveMode(); 899 } catch (RemoteException e) { 900 throw e.rethrowFromSystemServer(); 901 } 902 } 903 }; 904 905 private PropertyInvalidatedCache<Void, Boolean> mInteractiveCache = 906 new PropertyInvalidatedCache<Void, Boolean>(MAX_CACHE_ENTRIES, 907 CACHE_KEY_IS_INTERACTIVE_PROPERTY) { 908 @Override 909 protected Boolean recompute(Void query) { 910 try { 911 return mService.isInteractive(); 912 } catch (RemoteException e) { 913 throw e.rethrowFromSystemServer(); 914 } 915 } 916 }; 917 918 final Context mContext; 919 @UnsupportedAppUsage 920 final IPowerManager mService; 921 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) 922 final Handler mHandler; 923 final IThermalService mThermalService; 924 925 /** We lazily initialize it.*/ 926 private PowerWhitelistManager mPowerWhitelistManager; 927 928 private final ArrayMap<OnThermalStatusChangedListener, IThermalStatusListener> 929 mListenerMap = new ArrayMap<>(); 930 931 /** 932 * {@hide} 933 */ PowerManager(Context context, IPowerManager service, IThermalService thermalService, Handler handler)934 public PowerManager(Context context, IPowerManager service, IThermalService thermalService, 935 Handler handler) { 936 mContext = context; 937 mService = service; 938 mThermalService = thermalService; 939 mHandler = handler; 940 } 941 getPowerWhitelistManager()942 private PowerWhitelistManager getPowerWhitelistManager() { 943 if (mPowerWhitelistManager == null) { 944 // No need for synchronization; getSystemService() will return the same object anyway. 945 mPowerWhitelistManager = mContext.getSystemService(PowerWhitelistManager.class); 946 } 947 return mPowerWhitelistManager; 948 } 949 950 /** 951 * Gets the minimum supported screen brightness setting. 952 * The screen may be allowed to become dimmer than this value but 953 * this is the minimum value that can be set by the user. 954 * @hide 955 */ 956 @UnsupportedAppUsage getMinimumScreenBrightnessSetting()957 public int getMinimumScreenBrightnessSetting() { 958 return mContext.getResources().getInteger( 959 com.android.internal.R.integer.config_screenBrightnessSettingMinimum); 960 } 961 962 /** 963 * Gets the maximum supported screen brightness setting. 964 * The screen may be allowed to become dimmer than this value but 965 * this is the maximum value that can be set by the user. 966 * @hide 967 */ 968 @UnsupportedAppUsage getMaximumScreenBrightnessSetting()969 public int getMaximumScreenBrightnessSetting() { 970 return mContext.getResources().getInteger( 971 com.android.internal.R.integer.config_screenBrightnessSettingMaximum); 972 } 973 974 /** 975 * Gets the default screen brightness setting. 976 * @hide 977 */ 978 @UnsupportedAppUsage getDefaultScreenBrightnessSetting()979 public int getDefaultScreenBrightnessSetting() { 980 return mContext.getResources().getInteger( 981 com.android.internal.R.integer.config_screenBrightnessSettingDefault); 982 } 983 984 /** 985 * Gets the minimum supported screen brightness setting for VR Mode. 986 * @hide 987 */ getMinimumScreenBrightnessForVrSetting()988 public int getMinimumScreenBrightnessForVrSetting() { 989 return mContext.getResources().getInteger( 990 com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum); 991 } 992 993 /** 994 * Gets the maximum supported screen brightness setting for VR Mode. 995 * The screen may be allowed to become dimmer than this value but 996 * this is the maximum value that can be set by the user. 997 * @hide 998 */ getMaximumScreenBrightnessForVrSetting()999 public int getMaximumScreenBrightnessForVrSetting() { 1000 return mContext.getResources().getInteger( 1001 com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum); 1002 } 1003 1004 /** 1005 * Gets the default screen brightness for VR setting. 1006 * @hide 1007 */ getDefaultScreenBrightnessForVrSetting()1008 public int getDefaultScreenBrightnessForVrSetting() { 1009 return mContext.getResources().getInteger( 1010 com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault); 1011 } 1012 1013 /** 1014 * Gets a float screen brightness setting. 1015 * @hide 1016 */ 1017 @UnsupportedAppUsage getBrightnessConstraint(int constraint)1018 public float getBrightnessConstraint(int constraint) { 1019 try { 1020 return mService.getBrightnessConstraint(constraint); 1021 } catch (RemoteException e) { 1022 throw e.rethrowFromSystemServer(); 1023 } 1024 } 1025 1026 /** 1027 * Creates a new wake lock with the specified level and flags. 1028 * <p> 1029 * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags 1030 * combined using the logical OR operator. 1031 * </p><p> 1032 * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK}, 1033 * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK} 1034 * and {@link #SCREEN_BRIGHT_WAKE_LOCK}. Exactly one wake lock level must be 1035 * specified as part of the {@code levelAndFlags} parameter. 1036 * </p> 1037 * <p> 1038 * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP} 1039 * and {@link #ON_AFTER_RELEASE}. Multiple flags can be combined as part of the 1040 * {@code levelAndFlags} parameters. 1041 * </p><p> 1042 * Call {@link WakeLock#acquire() acquire()} on the object to acquire the 1043 * wake lock, and {@link WakeLock#release release()} when you are done. 1044 * </p><p> 1045 * {@samplecode 1046 * PowerManager pm = (PowerManager)mContext.getSystemService( 1047 * Context.POWER_SERVICE); 1048 * PowerManager.WakeLock wl = pm.newWakeLock( 1049 * PowerManager.SCREEN_DIM_WAKE_LOCK 1050 * | PowerManager.ON_AFTER_RELEASE, 1051 * TAG); 1052 * wl.acquire(); 1053 * // ... do work... 1054 * wl.release(); 1055 * } 1056 * </p><p> 1057 * Although a wake lock can be created without special permissions, 1058 * the {@link android.Manifest.permission#WAKE_LOCK} permission is 1059 * required to actually acquire or release the wake lock that is returned. 1060 * </p><p class="note"> 1061 * If using this to keep the screen on, you should strongly consider using 1062 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead. 1063 * This window flag will be correctly managed by the platform 1064 * as the user moves between applications and doesn't require a special permission. 1065 * </p> 1066 * 1067 * <p> 1068 * Recommended naming conventions for tags to make debugging easier: 1069 * <ul> 1070 * <li>use a unique prefix delimited by a colon for your app/library (e.g. 1071 * gmail:mytag) to make it easier to understand where the wake locks comes 1072 * from. This namespace will also avoid collision for tags inside your app 1073 * coming from different libraries which will make debugging easier. 1074 * <li>use constants (e.g. do not include timestamps in the tag) to make it 1075 * easier for tools to aggregate similar wake locks. When collecting 1076 * debugging data, the platform only monitors a finite number of tags, 1077 * using constants will help tools to provide better debugging data. 1078 * <li>avoid using Class#getName() or similar method since this class name 1079 * can be transformed by java optimizer and obfuscator tools. 1080 * <li>avoid wrapping the tag or a prefix to avoid collision with wake lock 1081 * tags from the platform (e.g. *alarm*). 1082 * <li>never include personnally identifiable information for privacy 1083 * reasons. 1084 * </ul> 1085 * </p> 1086 * 1087 * @param levelAndFlags Combination of wake lock level and flag values defining 1088 * the requested behavior of the WakeLock. 1089 * @param tag Your class name (or other tag) for debugging purposes. 1090 * 1091 * @see WakeLock#acquire() 1092 * @see WakeLock#release() 1093 * @see #PARTIAL_WAKE_LOCK 1094 * @see #FULL_WAKE_LOCK 1095 * @see #SCREEN_DIM_WAKE_LOCK 1096 * @see #SCREEN_BRIGHT_WAKE_LOCK 1097 * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK 1098 * @see #ACQUIRE_CAUSES_WAKEUP 1099 * @see #ON_AFTER_RELEASE 1100 */ newWakeLock(int levelAndFlags, String tag)1101 public WakeLock newWakeLock(int levelAndFlags, String tag) { 1102 validateWakeLockParameters(levelAndFlags, tag); 1103 return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName()); 1104 } 1105 1106 /** @hide */ 1107 @UnsupportedAppUsage validateWakeLockParameters(int levelAndFlags, String tag)1108 public static void validateWakeLockParameters(int levelAndFlags, String tag) { 1109 switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) { 1110 case PARTIAL_WAKE_LOCK: 1111 case SCREEN_DIM_WAKE_LOCK: 1112 case SCREEN_BRIGHT_WAKE_LOCK: 1113 case FULL_WAKE_LOCK: 1114 case PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1115 case DOZE_WAKE_LOCK: 1116 case DRAW_WAKE_LOCK: 1117 break; 1118 default: 1119 throw new IllegalArgumentException("Must specify a valid wake lock level."); 1120 } 1121 if (tag == null) { 1122 throw new IllegalArgumentException("The tag must not be null."); 1123 } 1124 } 1125 1126 /** 1127 * Notifies the power manager that user activity happened. 1128 * <p> 1129 * Resets the auto-off timer and brightens the screen if the device 1130 * is not asleep. This is what happens normally when a key or the touch 1131 * screen is pressed or when some other user activity occurs. 1132 * This method does not wake up the device if it has been put to sleep. 1133 * </p><p> 1134 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1135 * </p> 1136 * 1137 * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()} 1138 * time base. This timestamp is used to correctly order the user activity request with 1139 * other power management functions. It should be set 1140 * to the timestamp of the input event that caused the user activity. 1141 * @param noChangeLights If true, does not cause the keyboard backlight to turn on 1142 * because of this event. This is set when the power key is pressed. 1143 * We want the device to stay on while the button is down, but we're about 1144 * to turn off the screen so we don't want the keyboard backlight to turn on again. 1145 * Otherwise the lights flash on and then off and it looks weird. 1146 * 1147 * @see #wakeUp 1148 * @see #goToSleep 1149 * 1150 * @removed Requires signature or system permission. 1151 * @deprecated Use {@link #userActivity(long, int, int)}. 1152 */ 1153 @Deprecated userActivity(long when, boolean noChangeLights)1154 public void userActivity(long when, boolean noChangeLights) { 1155 userActivity(when, USER_ACTIVITY_EVENT_OTHER, 1156 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0); 1157 } 1158 1159 /** 1160 * Notifies the power manager that user activity happened. 1161 * <p> 1162 * Resets the auto-off timer and brightens the screen if the device 1163 * is not asleep. This is what happens normally when a key or the touch 1164 * screen is pressed or when some other user activity occurs. 1165 * This method does not wake up the device if it has been put to sleep. 1166 * </p><p> 1167 * Requires the {@link android.Manifest.permission#DEVICE_POWER} or 1168 * {@link android.Manifest.permission#USER_ACTIVITY} permission. 1169 * </p> 1170 * 1171 * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()} 1172 * time base. This timestamp is used to correctly order the user activity request with 1173 * other power management functions. It should be set 1174 * to the timestamp of the input event that caused the user activity. 1175 * @param event The user activity event. 1176 * @param flags Optional user activity flags. 1177 * 1178 * @see #wakeUp 1179 * @see #goToSleep 1180 * 1181 * @hide Requires signature or system permission. 1182 */ 1183 @SystemApi 1184 @RequiresPermission(anyOf = { 1185 android.Manifest.permission.DEVICE_POWER, 1186 android.Manifest.permission.USER_ACTIVITY 1187 }) userActivity(long when, int event, int flags)1188 public void userActivity(long when, int event, int flags) { 1189 try { 1190 mService.userActivity(when, event, flags); 1191 } catch (RemoteException e) { 1192 throw e.rethrowFromSystemServer(); 1193 } 1194 } 1195 1196 /** 1197 * Forces the device to go to sleep. 1198 * <p> 1199 * Overrides all the wake locks that are held. 1200 * This is what happens when the power key is pressed to turn off the screen. 1201 * </p><p> 1202 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1203 * </p> 1204 * 1205 * @param time The time when the request to go to sleep was issued, in the 1206 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1207 * order the go to sleep request with other power management functions. It should be set 1208 * to the timestamp of the input event that caused the request to go to sleep. 1209 * 1210 * @see #userActivity 1211 * @see #wakeUp 1212 * 1213 * @removed Requires signature permission. 1214 */ goToSleep(long time)1215 public void goToSleep(long time) { 1216 goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0); 1217 } 1218 1219 /** 1220 * Forces the device to go to sleep. 1221 * <p> 1222 * Overrides all the wake locks that are held. 1223 * This is what happens when the power key is pressed to turn off the screen. 1224 * </p><p> 1225 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1226 * </p> 1227 * 1228 * @param time The time when the request to go to sleep was issued, in the 1229 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1230 * order the go to sleep request with other power management functions. It should be set 1231 * to the timestamp of the input event that caused the request to go to sleep. 1232 * @param reason The reason the device is going to sleep. 1233 * @param flags Optional flags to apply when going to sleep. 1234 * 1235 * @see #userActivity 1236 * @see #wakeUp 1237 * 1238 * @hide Requires signature permission. 1239 */ 1240 @UnsupportedAppUsage goToSleep(long time, int reason, int flags)1241 public void goToSleep(long time, int reason, int flags) { 1242 try { 1243 mService.goToSleep(time, reason, flags); 1244 } catch (RemoteException e) { 1245 throw e.rethrowFromSystemServer(); 1246 } 1247 } 1248 1249 /** 1250 * Forces the device to wake up from sleep. 1251 * <p> 1252 * If the device is currently asleep, wakes it up, otherwise does nothing. 1253 * This is what happens when the power key is pressed to turn on the screen. 1254 * </p><p> 1255 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1256 * </p> 1257 * 1258 * @param time The time when the request to wake up was issued, in the 1259 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1260 * order the wake up request with other power management functions. It should be set 1261 * to the timestamp of the input event that caused the request to wake up. 1262 * 1263 * @see #userActivity 1264 * @see #goToSleep 1265 * 1266 * @deprecated Use {@link #wakeUp(long, int, String)} instead. 1267 * @removed Requires signature permission. 1268 */ 1269 @Deprecated wakeUp(long time)1270 public void wakeUp(long time) { 1271 wakeUp(time, WAKE_REASON_UNKNOWN, "wakeUp"); 1272 } 1273 1274 /** 1275 * Forces the device to wake up from sleep. 1276 * <p> 1277 * If the device is currently asleep, wakes it up, otherwise does nothing. 1278 * This is what happens when the power key is pressed to turn on the screen. 1279 * </p><p> 1280 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1281 * </p> 1282 * 1283 * @param time The time when the request to wake up was issued, in the 1284 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1285 * order the wake up request with other power management functions. It should be set 1286 * to the timestamp of the input event that caused the request to wake up. 1287 * 1288 * @param details A free form string to explain the specific details behind the wake up for 1289 * debugging purposes. 1290 * 1291 * @see #userActivity 1292 * @see #goToSleep 1293 * 1294 * @deprecated Use {@link #wakeUp(long, int, String)} instead. 1295 * @hide 1296 */ 1297 @UnsupportedAppUsage 1298 @Deprecated wakeUp(long time, String details)1299 public void wakeUp(long time, String details) { 1300 wakeUp(time, WAKE_REASON_UNKNOWN, details); 1301 } 1302 1303 /** 1304 * Forces the device to wake up from sleep. 1305 * <p> 1306 * If the device is currently asleep, wakes it up, otherwise does nothing. 1307 * This is what happens when the power key is pressed to turn on the screen. 1308 * </p><p> 1309 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1310 * </p> 1311 * 1312 * @param time The time when the request to wake up was issued, in the 1313 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1314 * order the wake up request with other power management functions. It should be set 1315 * to the timestamp of the input event that caused the request to wake up. 1316 * 1317 * @param reason The reason for the wake up. 1318 * 1319 * @param details A free form string to explain the specific details behind the wake up for 1320 * debugging purposes. 1321 * 1322 * @see #userActivity 1323 * @see #goToSleep 1324 * @hide 1325 */ wakeUp(long time, @WakeReason int reason, String details)1326 public void wakeUp(long time, @WakeReason int reason, String details) { 1327 try { 1328 mService.wakeUp(time, reason, details, mContext.getOpPackageName()); 1329 } catch (RemoteException e) { 1330 throw e.rethrowFromSystemServer(); 1331 } 1332 } 1333 1334 /** 1335 * Forces the device to start napping. 1336 * <p> 1337 * If the device is currently awake, starts dreaming, otherwise does nothing. 1338 * When the dream ends or if the dream cannot be started, the device will 1339 * either wake up or go to sleep depending on whether there has been recent 1340 * user activity. 1341 * </p><p> 1342 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1343 * </p> 1344 * 1345 * @param time The time when the request to nap was issued, in the 1346 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1347 * order the nap request with other power management functions. It should be set 1348 * to the timestamp of the input event that caused the request to nap. 1349 * 1350 * @see #wakeUp 1351 * @see #goToSleep 1352 * 1353 * @hide Requires signature permission. 1354 */ nap(long time)1355 public void nap(long time) { 1356 try { 1357 mService.nap(time); 1358 } catch (RemoteException e) { 1359 throw e.rethrowFromSystemServer(); 1360 } 1361 } 1362 1363 /** 1364 * Requests the device to start dreaming. 1365 * <p> 1366 * If dream can not be started, for example if another {@link PowerManager} transition is in 1367 * progress, does nothing. Unlike {@link #nap(long)}, this does not put device to sleep when 1368 * dream ends. 1369 * </p><p> 1370 * Requires the {@link android.Manifest.permission#READ_DREAM_STATE} and 1371 * {@link android.Manifest.permission#WRITE_DREAM_STATE} permissions. 1372 * </p> 1373 * 1374 * @param time The time when the request to nap was issued, in the 1375 * {@link SystemClock#uptimeMillis()} time base. This timestamp may be used to correctly 1376 * order the dream request with other power management functions. It should be set 1377 * to the timestamp of the input event that caused the request to dream. 1378 * 1379 * @hide 1380 */ 1381 @SystemApi 1382 @RequiresPermission(allOf = { 1383 android.Manifest.permission.READ_DREAM_STATE, 1384 android.Manifest.permission.WRITE_DREAM_STATE }) dream(long time)1385 public void dream(long time) { 1386 Sandman.startDreamByUserRequest(mContext); 1387 } 1388 1389 /** 1390 * Boosts the brightness of the screen to maximum for a predetermined 1391 * period of time. This is used to make the screen more readable in bright 1392 * daylight for a short duration. 1393 * <p> 1394 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 1395 * </p> 1396 * 1397 * @param time The time when the request to boost was issued, in the 1398 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly 1399 * order the boost request with other power management functions. It should be set 1400 * to the timestamp of the input event that caused the request to boost. 1401 * 1402 * @hide Requires signature permission. 1403 */ boostScreenBrightness(long time)1404 public void boostScreenBrightness(long time) { 1405 try { 1406 mService.boostScreenBrightness(time); 1407 } catch (RemoteException e) { 1408 throw e.rethrowFromSystemServer(); 1409 } 1410 } 1411 1412 /** 1413 * Returns true if the specified wake lock level is supported. 1414 * 1415 * @param level The wake lock level to check. 1416 * @return True if the specified wake lock level is supported. 1417 */ isWakeLockLevelSupported(int level)1418 public boolean isWakeLockLevelSupported(int level) { 1419 try { 1420 return mService.isWakeLockLevelSupported(level); 1421 } catch (RemoteException e) { 1422 throw e.rethrowFromSystemServer(); 1423 } 1424 } 1425 1426 /** 1427 * Returns true if the device is in an interactive state. 1428 * <p> 1429 * For historical reasons, the name of this method refers to the power state of 1430 * the screen but it actually describes the overall interactive state of 1431 * the device. This method has been replaced by {@link #isInteractive}. 1432 * </p><p> 1433 * The value returned by this method only indicates whether the device is 1434 * in an interactive state which may have nothing to do with the screen being 1435 * on or off. To determine the actual state of the screen, 1436 * use {@link android.view.Display#getState}. 1437 * </p> 1438 * 1439 * @return True if the device is in an interactive state. 1440 * 1441 * @deprecated Use {@link #isInteractive} instead. 1442 */ 1443 @Deprecated isScreenOn()1444 public boolean isScreenOn() { 1445 return isInteractive(); 1446 } 1447 1448 /** 1449 * Returns true if the device is in an interactive state. 1450 * <p> 1451 * When this method returns true, the device is awake and ready to interact 1452 * with the user (although this is not a guarantee that the user is actively 1453 * interacting with the device just this moment). The main screen is usually 1454 * turned on while in this state. Certain features, such as the proximity 1455 * sensor, may temporarily turn off the screen while still leaving the device in an 1456 * interactive state. Note in particular that the device is still considered 1457 * to be interactive while dreaming (since dreams can be interactive) but not 1458 * when it is dozing or asleep. 1459 * </p><p> 1460 * When this method returns false, the device is dozing or asleep and must 1461 * be awoken before it will become ready to interact with the user again. The 1462 * main screen is usually turned off while in this state. Certain features, 1463 * such as "ambient mode" may cause the main screen to remain on (albeit in a 1464 * low power state) to display system-provided content while the device dozes. 1465 * </p><p> 1466 * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on} 1467 * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast 1468 * whenever the interactive state of the device changes. For historical reasons, 1469 * the names of these broadcasts refer to the power state of the screen 1470 * but they are actually sent in response to changes in the overall interactive 1471 * state of the device, as described by this method. 1472 * </p><p> 1473 * Services may use the non-interactive state as a hint to conserve power 1474 * since the user is not present. 1475 * </p> 1476 * 1477 * @return True if the device is in an interactive state. 1478 * 1479 * @see android.content.Intent#ACTION_SCREEN_ON 1480 * @see android.content.Intent#ACTION_SCREEN_OFF 1481 */ isInteractive()1482 public boolean isInteractive() { 1483 return mInteractiveCache.query(null); 1484 } 1485 1486 1487 /** 1488 * Returns {@code true} if this device supports rebooting userspace. 1489 * 1490 * <p>This method exists solely for the sake of re-using same logic between {@code PowerManager} 1491 * and {@code PowerManagerService}. 1492 * 1493 * @hide 1494 */ isRebootingUserspaceSupportedImpl()1495 public static boolean isRebootingUserspaceSupportedImpl() { 1496 return InitProperties.is_userspace_reboot_supported().orElse(false); 1497 } 1498 1499 /** 1500 * Returns {@code true} if this device supports rebooting userspace. 1501 */ 1502 // TODO(b/138605180): add link to documentation once it's ready. isRebootingUserspaceSupported()1503 public boolean isRebootingUserspaceSupported() { 1504 return isRebootingUserspaceSupportedImpl(); 1505 } 1506 1507 /** 1508 * Reboot the device. Will not return if the reboot is successful. 1509 * <p> 1510 * Requires the {@link android.Manifest.permission#REBOOT} permission. 1511 * </p> 1512 * 1513 * @param reason code to pass to the kernel (e.g., "recovery") to 1514 * request special boot modes, or null. 1515 * @throws UnsupportedOperationException if userspace reboot was requested on a device that 1516 * doesn't support it. 1517 */ 1518 @RequiresPermission(permission.REBOOT) reboot(@ullable String reason)1519 public void reboot(@Nullable String reason) { 1520 if (REBOOT_USERSPACE.equals(reason) && !isRebootingUserspaceSupported()) { 1521 throw new UnsupportedOperationException( 1522 "Attempted userspace reboot on a device that doesn't support it"); 1523 } 1524 try { 1525 mService.reboot(false, reason, true); 1526 } catch (RemoteException e) { 1527 throw e.rethrowFromSystemServer(); 1528 } 1529 } 1530 1531 /** 1532 * Reboot the device. Will not return if the reboot is successful. 1533 * <p> 1534 * Requires the {@link android.Manifest.permission#REBOOT} permission. 1535 * </p> 1536 * @hide 1537 */ 1538 @RequiresPermission(permission.REBOOT) rebootSafeMode()1539 public void rebootSafeMode() { 1540 try { 1541 mService.rebootSafeMode(false, true); 1542 } catch (RemoteException e) { 1543 throw e.rethrowFromSystemServer(); 1544 } 1545 } 1546 1547 /** 1548 * Returns true if the device is currently in power save mode. When in this mode, 1549 * applications should reduce their functionality in order to conserve battery as 1550 * much as possible. You can monitor for changes to this state with 1551 * {@link #ACTION_POWER_SAVE_MODE_CHANGED}. 1552 * 1553 * @return Returns true if currently in low power mode, else false. 1554 */ isPowerSaveMode()1555 public boolean isPowerSaveMode() { 1556 return mPowerSaveModeCache.query(null); 1557 } 1558 1559 /** 1560 * Set the current power save mode. 1561 * 1562 * @return True if the set was allowed. 1563 * 1564 * @hide 1565 * @see #isPowerSaveMode() 1566 */ 1567 @SystemApi 1568 @TestApi 1569 @RequiresPermission(anyOf = { 1570 android.Manifest.permission.DEVICE_POWER, 1571 android.Manifest.permission.POWER_SAVER 1572 }) setPowerSaveModeEnabled(boolean mode)1573 public boolean setPowerSaveModeEnabled(boolean mode) { 1574 try { 1575 return mService.setPowerSaveModeEnabled(mode); 1576 } catch (RemoteException e) { 1577 throw e.rethrowFromSystemServer(); 1578 } 1579 } 1580 1581 /** 1582 * Updates the current state of dynamic power savings and disable threshold. This is 1583 * a signal to the system which an app can update to serve as an indicator that 1584 * the user will be in a battery critical situation before being able to plug in. 1585 * Only apps with the {@link android.Manifest.permission#POWER_SAVER} permission may do this. 1586 * This is a device global state, not a per user setting. 1587 * 1588 * <p>When enabled, the system may enact various measures for reducing power consumption in 1589 * order to help ensure that the user will make it to their next charging point. The most 1590 * visible of these will be the automatic enabling of battery saver if the user has set 1591 * their battery saver mode to "automatic". Note 1592 * that this is NOT simply an on/off switch for features, but rather a hint for the 1593 * system to consider enacting these power saving features, some of which have additional 1594 * logic around when to activate based on this signal. 1595 * 1596 * <p>The provided threshold is the percentage the system should consider itself safe at given 1597 * the current state of the device. The value is an integer representing a battery level. 1598 * 1599 * <p>The threshold is meant to set an explicit stopping point for dynamic power savings 1600 * functionality so that the dynamic power savings itself remains a signal rather than becoming 1601 * an on/off switch for a subset of features. 1602 * @hide 1603 * 1604 * @param powerSaveHint A signal indicating to the system if it believes the 1605 * dynamic power savings behaviors should be activated. 1606 * @param disableThreshold When the suggesting app believes it would be safe to disable dynamic 1607 * power savings behaviors. 1608 * @return True if the update was allowed and succeeded. 1609 * 1610 * @hide 1611 */ 1612 @SystemApi 1613 @TestApi 1614 @RequiresPermission(permission.POWER_SAVER) setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold)1615 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) { 1616 try { 1617 return mService.setDynamicPowerSaveHint(powerSaveHint, disableThreshold); 1618 } catch (RemoteException e) { 1619 throw e.rethrowFromSystemServer(); 1620 } 1621 } 1622 1623 /** 1624 * Sets the policy for adaptive power save. 1625 * 1626 * @return true if there was an effectual change. If full battery saver is enabled or the 1627 * adaptive policy is not enabled, then this will return false. 1628 * 1629 * @hide 1630 */ 1631 @SystemApi 1632 @RequiresPermission(anyOf = { 1633 android.Manifest.permission.DEVICE_POWER, 1634 android.Manifest.permission.POWER_SAVER 1635 }) setAdaptivePowerSavePolicy(@onNull BatterySaverPolicyConfig config)1636 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) { 1637 try { 1638 return mService.setAdaptivePowerSavePolicy(config); 1639 } catch (RemoteException e) { 1640 throw e.rethrowFromSystemServer(); 1641 } 1642 } 1643 1644 /** 1645 * Enables or disables adaptive power save. 1646 * 1647 * @return true if there was an effectual change. If full battery saver is enabled, then this 1648 * will return false. 1649 * 1650 * @hide 1651 */ 1652 @SystemApi 1653 @RequiresPermission(anyOf = { 1654 android.Manifest.permission.DEVICE_POWER, 1655 android.Manifest.permission.POWER_SAVER 1656 }) setAdaptivePowerSaveEnabled(boolean enabled)1657 public boolean setAdaptivePowerSaveEnabled(boolean enabled) { 1658 try { 1659 return mService.setAdaptivePowerSaveEnabled(enabled); 1660 } catch (RemoteException e) { 1661 throw e.rethrowFromSystemServer(); 1662 } 1663 } 1664 1665 /** 1666 * Indicates automatic battery saver toggling by the system will be based on percentage. 1667 * 1668 * @see PowerManager#getPowerSaveModeTrigger() 1669 * 1670 * @hide 1671 */ 1672 @SystemApi 1673 @TestApi 1674 public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0; 1675 1676 /** 1677 * Indicates automatic battery saver toggling by the system will be based on the state 1678 * of the dynamic power savings signal. 1679 * 1680 * @see PowerManager#setDynamicPowerSaveHint(boolean, int) 1681 * @see PowerManager#getPowerSaveModeTrigger() 1682 * 1683 * @hide 1684 */ 1685 @SystemApi 1686 @TestApi 1687 public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1; 1688 1689 /** @hide */ 1690 @Retention(RetentionPolicy.SOURCE) 1691 @IntDef(value = { 1692 POWER_SAVE_MODE_TRIGGER_PERCENTAGE, 1693 POWER_SAVE_MODE_TRIGGER_DYNAMIC 1694 1695 }) 1696 public @interface AutoPowerSaveModeTriggers {} 1697 1698 1699 /** 1700 * Returns the current battery saver control mode. Values it may return are defined in 1701 * AutoPowerSaveModeTriggers. Note that this is a global device state, not a per user setting. 1702 * 1703 * @return The current value power saver mode for the system. 1704 * 1705 * @see AutoPowerSaveModeTriggers 1706 * @see PowerManager#getPowerSaveModeTrigger() 1707 * @hide 1708 */ 1709 @AutoPowerSaveModeTriggers 1710 @SystemApi 1711 @TestApi 1712 @RequiresPermission(android.Manifest.permission.POWER_SAVER) getPowerSaveModeTrigger()1713 public int getPowerSaveModeTrigger() { 1714 try { 1715 return mService.getPowerSaveModeTrigger(); 1716 } catch (RemoteException e) { 1717 throw e.rethrowFromSystemServer(); 1718 } 1719 } 1720 1721 /** 1722 * Get data about the battery saver mode for a specific service 1723 * @param serviceType unique key for the service, one of {@link ServiceType} 1724 * @return Battery saver state data. 1725 * 1726 * @hide 1727 * @see com.android.server.power.batterysaver.BatterySaverPolicy 1728 * @see PowerSaveState 1729 */ getPowerSaveState(@erviceType int serviceType)1730 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) { 1731 try { 1732 return mService.getPowerSaveState(serviceType); 1733 } catch (RemoteException e) { 1734 throw e.rethrowFromSystemServer(); 1735 } 1736 } 1737 1738 /** 1739 * Returns how location features should behave when battery saver is on. When battery saver 1740 * is off, this will always return {@link #LOCATION_MODE_NO_CHANGE}. 1741 * 1742 * <p>This API is normally only useful for components that provide location features. 1743 * 1744 * @see #isPowerSaveMode() 1745 * @see #ACTION_POWER_SAVE_MODE_CHANGED 1746 */ 1747 @LocationPowerSaveMode getLocationPowerSaveMode()1748 public int getLocationPowerSaveMode() { 1749 final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.LOCATION); 1750 if (!powerSaveState.batterySaverEnabled) { 1751 return LOCATION_MODE_NO_CHANGE; 1752 } 1753 return powerSaveState.locationMode; 1754 } 1755 1756 /** 1757 * Returns true if the device is currently in idle mode. This happens when a device 1758 * has been sitting unused and unmoving for a sufficiently long period of time, so that 1759 * it decides to go into a lower power-use state. This may involve things like turning 1760 * off network access to apps. You can monitor for changes to this state with 1761 * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}. 1762 * 1763 * @return Returns true if currently in active device idle mode, else false. This is 1764 * when idle mode restrictions are being actively applied; it will return false if the 1765 * device is in a long-term idle mode but currently running a maintenance window where 1766 * restrictions have been lifted. 1767 */ isDeviceIdleMode()1768 public boolean isDeviceIdleMode() { 1769 try { 1770 return mService.isDeviceIdleMode(); 1771 } catch (RemoteException e) { 1772 throw e.rethrowFromSystemServer(); 1773 } 1774 } 1775 1776 /** 1777 * Returns true if the device is currently in light idle mode. This happens when a device 1778 * has had its screen off for a short time, switching it into a batching mode where we 1779 * execute jobs, syncs, networking on a batching schedule. You can monitor for changes to 1780 * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}. 1781 * 1782 * @return Returns true if currently in active light device idle mode, else false. This is 1783 * when light idle mode restrictions are being actively applied; it will return false if the 1784 * device is in a long-term idle mode but currently running a maintenance window where 1785 * restrictions have been lifted. 1786 * @hide 1787 */ 1788 @UnsupportedAppUsage isLightDeviceIdleMode()1789 public boolean isLightDeviceIdleMode() { 1790 try { 1791 return mService.isLightDeviceIdleMode(); 1792 } catch (RemoteException e) { 1793 throw e.rethrowFromSystemServer(); 1794 } 1795 } 1796 1797 /** 1798 * Return whether the given application package name is on the device's power whitelist. 1799 * Apps can be placed on the whitelist through the settings UI invoked by 1800 * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}. 1801 */ isIgnoringBatteryOptimizations(String packageName)1802 public boolean isIgnoringBatteryOptimizations(String packageName) { 1803 return getPowerWhitelistManager().isWhitelisted(packageName, true); 1804 } 1805 1806 /** 1807 * Turn off the device. 1808 * 1809 * @param confirm If true, shows a shutdown confirmation dialog. 1810 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null. 1811 * @param wait If true, this call waits for the shutdown to complete and does not return. 1812 * 1813 * @hide 1814 */ shutdown(boolean confirm, String reason, boolean wait)1815 public void shutdown(boolean confirm, String reason, boolean wait) { 1816 try { 1817 mService.shutdown(confirm, reason, wait); 1818 } catch (RemoteException e) { 1819 throw e.rethrowFromSystemServer(); 1820 } 1821 } 1822 1823 /** 1824 * This function checks if the device has implemented Sustained Performance 1825 * Mode. This needs to be checked only once and is constant for a particular 1826 * device/release. 1827 * 1828 * Sustained Performance Mode is intended to provide a consistent level of 1829 * performance for prolonged amount of time. 1830 * 1831 * Applications should check if the device supports this mode, before using 1832 * {@link android.view.Window#setSustainedPerformanceMode}. 1833 * 1834 * @return Returns True if the device supports it, false otherwise. 1835 * 1836 * @see android.view.Window#setSustainedPerformanceMode 1837 */ isSustainedPerformanceModeSupported()1838 public boolean isSustainedPerformanceModeSupported() { 1839 return mContext.getResources().getBoolean( 1840 com.android.internal.R.bool.config_sustainedPerformanceModeSupported); 1841 } 1842 1843 /** 1844 * Thermal status code: Not under throttling. 1845 */ 1846 public static final int THERMAL_STATUS_NONE = Temperature.THROTTLING_NONE; 1847 1848 /** 1849 * Thermal status code: Light throttling where UX is not impacted. 1850 */ 1851 public static final int THERMAL_STATUS_LIGHT = Temperature.THROTTLING_LIGHT; 1852 1853 /** 1854 * Thermal status code: Moderate throttling where UX is not largely impacted. 1855 */ 1856 public static final int THERMAL_STATUS_MODERATE = Temperature.THROTTLING_MODERATE; 1857 1858 /** 1859 * Thermal status code: Severe throttling where UX is largely impacted. 1860 */ 1861 public static final int THERMAL_STATUS_SEVERE = Temperature.THROTTLING_SEVERE; 1862 1863 /** 1864 * Thermal status code: Platform has done everything to reduce power. 1865 */ 1866 public static final int THERMAL_STATUS_CRITICAL = Temperature.THROTTLING_CRITICAL; 1867 1868 /** 1869 * Thermal status code: Key components in platform are shutting down due to thermal condition. 1870 * Device functionalities will be limited. 1871 */ 1872 public static final int THERMAL_STATUS_EMERGENCY = Temperature.THROTTLING_EMERGENCY; 1873 1874 /** 1875 * Thermal status code: Need shutdown immediately. 1876 */ 1877 public static final int THERMAL_STATUS_SHUTDOWN = Temperature.THROTTLING_SHUTDOWN; 1878 1879 /** @hide */ 1880 @IntDef(prefix = { "THERMAL_STATUS_" }, value = { 1881 THERMAL_STATUS_NONE, 1882 THERMAL_STATUS_LIGHT, 1883 THERMAL_STATUS_MODERATE, 1884 THERMAL_STATUS_SEVERE, 1885 THERMAL_STATUS_CRITICAL, 1886 THERMAL_STATUS_EMERGENCY, 1887 THERMAL_STATUS_SHUTDOWN, 1888 }) 1889 @Retention(RetentionPolicy.SOURCE) 1890 public @interface ThermalStatus {} 1891 1892 /** 1893 * This function returns the current thermal status of the device. 1894 * 1895 * @return thermal status as int, {@link #THERMAL_STATUS_NONE} if device in not under 1896 * thermal throttling. 1897 */ getCurrentThermalStatus()1898 public @ThermalStatus int getCurrentThermalStatus() { 1899 try { 1900 return mThermalService.getCurrentThermalStatus(); 1901 } catch (RemoteException e) { 1902 throw e.rethrowFromSystemServer(); 1903 } 1904 } 1905 1906 /** 1907 * Listener passed to 1908 * {@link PowerManager#addThermalStatusListener} and 1909 * {@link PowerManager#removeThermalStatusListener} 1910 * to notify caller of thermal status has changed. 1911 */ 1912 public interface OnThermalStatusChangedListener { 1913 1914 /** 1915 * Called when overall thermal throttling status changed. 1916 * @param status defined in {@link android.os.Temperature}. 1917 */ onThermalStatusChanged(@hermalStatus int status)1918 void onThermalStatusChanged(@ThermalStatus int status); 1919 } 1920 1921 1922 /** 1923 * This function adds a listener for thermal status change, listen call back will be 1924 * enqueued tasks on the main thread 1925 * 1926 * @param listener listener to be added, 1927 */ addThermalStatusListener(@onNull OnThermalStatusChangedListener listener)1928 public void addThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) { 1929 Preconditions.checkNotNull(listener, "listener cannot be null"); 1930 this.addThermalStatusListener(mContext.getMainExecutor(), listener); 1931 } 1932 1933 /** 1934 * This function adds a listener for thermal status change. 1935 * 1936 * @param executor {@link Executor} to handle listener callback. 1937 * @param listener listener to be added. 1938 */ addThermalStatusListener(@onNull @allbackExecutor Executor executor, @NonNull OnThermalStatusChangedListener listener)1939 public void addThermalStatusListener(@NonNull @CallbackExecutor Executor executor, 1940 @NonNull OnThermalStatusChangedListener listener) { 1941 Preconditions.checkNotNull(listener, "listener cannot be null"); 1942 Preconditions.checkNotNull(executor, "executor cannot be null"); 1943 Preconditions.checkArgument(!mListenerMap.containsKey(listener), 1944 "Listener already registered: " + listener); 1945 IThermalStatusListener internalListener = new IThermalStatusListener.Stub() { 1946 @Override 1947 public void onStatusChange(int status) { 1948 final long token = Binder.clearCallingIdentity(); 1949 try { 1950 executor.execute(() -> { 1951 listener.onThermalStatusChanged(status); 1952 }); 1953 } finally { 1954 Binder.restoreCallingIdentity(token); 1955 } 1956 } 1957 }; 1958 try { 1959 if (mThermalService.registerThermalStatusListener(internalListener)) { 1960 mListenerMap.put(listener, internalListener); 1961 } else { 1962 throw new RuntimeException("Listener failed to set"); 1963 } 1964 } catch (RemoteException e) { 1965 throw e.rethrowFromSystemServer(); 1966 } 1967 } 1968 1969 /** 1970 * This function removes a listener for thermal status change 1971 * 1972 * @param listener listener to be removed 1973 */ removeThermalStatusListener(@onNull OnThermalStatusChangedListener listener)1974 public void removeThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) { 1975 Preconditions.checkNotNull(listener, "listener cannot be null"); 1976 IThermalStatusListener internalListener = mListenerMap.get(listener); 1977 Preconditions.checkArgument(internalListener != null, "Listener was not added"); 1978 try { 1979 if (mThermalService.unregisterThermalStatusListener(internalListener)) { 1980 mListenerMap.remove(listener); 1981 } else { 1982 throw new RuntimeException("Listener failed to remove"); 1983 } 1984 } catch (RemoteException e) { 1985 throw e.rethrowFromSystemServer(); 1986 } 1987 } 1988 1989 @CurrentTimeMillisLong 1990 private final AtomicLong mLastHeadroomUpdate = new AtomicLong(0L); 1991 private static final int MINIMUM_HEADROOM_TIME_MILLIS = 500; 1992 1993 /** 1994 * Provides an estimate of how much thermal headroom the device currently has before hitting 1995 * severe throttling. 1996 * 1997 * Note that this only attempts to track the headroom of slow-moving sensors, such as the skin 1998 * temperature sensor. This means that there is no benefit to calling this function more 1999 * frequently than about once per second, and attempts to call significantly more frequently may 2000 * result in the function returning {@code NaN}. 2001 * <p> 2002 * In addition, in order to be able to provide an accurate forecast, the system does not attempt 2003 * to forecast until it has multiple temperature samples from which to extrapolate. This should 2004 * only take a few seconds from the time of the first call, but during this time, no forecasting 2005 * will occur, and the current headroom will be returned regardless of the value of 2006 * {@code forecastSeconds}. 2007 * <p> 2008 * The value returned is a non-negative float that represents how much of the thermal envelope 2009 * is in use (or is forecasted to be in use). A value of 1.0 indicates that the device is (or 2010 * will be) throttled at {@link #THERMAL_STATUS_SEVERE}. Such throttling can affect the CPU, 2011 * GPU, and other subsystems. Values may exceed 1.0, but there is no implied mapping to specific 2012 * thermal status levels beyond that point. This means that values greater than 1.0 may 2013 * correspond to {@link #THERMAL_STATUS_SEVERE}, but may also represent heavier throttling. 2014 * <p> 2015 * A value of 0.0 corresponds to a fixed distance from 1.0, but does not correspond to any 2016 * particular thermal status or temperature. Values on (0.0, 1.0] may be expected to scale 2017 * linearly with temperature, though temperature changes over time are typically not linear. 2018 * Negative values will be clamped to 0.0 before returning. 2019 * 2020 * @param forecastSeconds how many seconds in the future to forecast. Given that device 2021 * conditions may change at any time, forecasts from further in the 2022 * future will likely be less accurate than forecasts in the near future. 2023 * @return a value greater than or equal to 0.0 where 1.0 indicates the SEVERE throttling 2024 * threshold, as described above. Returns NaN if the device does not support this 2025 * functionality or if this function is called significantly faster than once per 2026 * second. 2027 */ getThermalHeadroom(@ntRangefrom = 0, to = 60) int forecastSeconds)2028 public float getThermalHeadroom(@IntRange(from = 0, to = 60) int forecastSeconds) { 2029 // Rate-limit calls into the thermal service 2030 long now = SystemClock.elapsedRealtime(); 2031 long timeSinceLastUpdate = now - mLastHeadroomUpdate.get(); 2032 if (timeSinceLastUpdate < MINIMUM_HEADROOM_TIME_MILLIS) { 2033 return Float.NaN; 2034 } 2035 2036 try { 2037 float forecast = mThermalService.getThermalHeadroom(forecastSeconds); 2038 mLastHeadroomUpdate.set(SystemClock.elapsedRealtime()); 2039 return forecast; 2040 } catch (RemoteException e) { 2041 throw e.rethrowFromSystemServer(); 2042 } 2043 } 2044 2045 /** 2046 * If true, the doze component is not started until after the screen has been 2047 * turned off and the screen off animation has been performed. 2048 * @hide 2049 */ setDozeAfterScreenOff(boolean dozeAfterScreenOf)2050 public void setDozeAfterScreenOff(boolean dozeAfterScreenOf) { 2051 try { 2052 mService.setDozeAfterScreenOff(dozeAfterScreenOf); 2053 } catch (RemoteException e) { 2054 throw e.rethrowFromSystemServer(); 2055 } 2056 } 2057 2058 /** 2059 * Returns true if ambient display is available on the device. 2060 * @hide 2061 */ 2062 @SystemApi 2063 @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE) isAmbientDisplayAvailable()2064 public boolean isAmbientDisplayAvailable() { 2065 try { 2066 return mService.isAmbientDisplayAvailable(); 2067 } catch (RemoteException e) { 2068 throw e.rethrowFromSystemServer(); 2069 } 2070 } 2071 2072 /** 2073 * If true, suppresses the current ambient display configuration and disables ambient display. 2074 * 2075 * <p>This method has no effect if {@link #isAmbientDisplayAvailable()} is false. 2076 * 2077 * @param token A persistable identifier for the ambient display suppression that is unique 2078 * within the calling application. 2079 * @param suppress If set to {@code true}, ambient display will be suppressed. If set to 2080 * {@code false}, ambient display will no longer be suppressed for the given 2081 * token. 2082 * @hide 2083 */ 2084 @SystemApi 2085 @RequiresPermission(android.Manifest.permission.WRITE_DREAM_STATE) suppressAmbientDisplay(@onNull String token, boolean suppress)2086 public void suppressAmbientDisplay(@NonNull String token, boolean suppress) { 2087 try { 2088 mService.suppressAmbientDisplay(token, suppress); 2089 } catch (RemoteException e) { 2090 throw e.rethrowFromSystemServer(); 2091 } 2092 } 2093 2094 /** 2095 * Returns true if ambient display is suppressed by the calling app with the given 2096 * {@code token}. 2097 * 2098 * <p>This method will return false if {@link #isAmbientDisplayAvailable()} is false. 2099 * 2100 * @param token The identifier of the ambient display suppression. 2101 * @hide 2102 */ 2103 @SystemApi 2104 @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE) isAmbientDisplaySuppressedForToken(@onNull String token)2105 public boolean isAmbientDisplaySuppressedForToken(@NonNull String token) { 2106 try { 2107 return mService.isAmbientDisplaySuppressedForToken(token); 2108 } catch (RemoteException e) { 2109 throw e.rethrowFromSystemServer(); 2110 } 2111 } 2112 2113 /** 2114 * Returns true if ambient display is suppressed by <em>any</em> app with <em>any</em> token. 2115 * 2116 * <p>This method will return false if {@link #isAmbientDisplayAvailable()} is false. 2117 * @hide 2118 */ 2119 @SystemApi 2120 @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE) isAmbientDisplaySuppressed()2121 public boolean isAmbientDisplaySuppressed() { 2122 try { 2123 return mService.isAmbientDisplaySuppressed(); 2124 } catch (RemoteException e) { 2125 throw e.rethrowFromSystemServer(); 2126 } 2127 } 2128 2129 /** 2130 * Returns the reason the phone was last shutdown. Calling app must have the 2131 * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information. 2132 * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could 2133 * not be accessed. 2134 * @hide 2135 */ 2136 @ShutdownReason getLastShutdownReason()2137 public int getLastShutdownReason() { 2138 try { 2139 return mService.getLastShutdownReason(); 2140 } catch (RemoteException e) { 2141 throw e.rethrowFromSystemServer(); 2142 } 2143 } 2144 2145 /** 2146 * Returns the reason the device last went to sleep (i.e. the last value of 2147 * the second argument of {@link #goToSleep(long, int, int) goToSleep}). 2148 * 2149 * @return One of the {@code GO_TO_SLEEP_REASON_*} constants. 2150 * 2151 * @hide 2152 */ getLastSleepReason()2153 public int getLastSleepReason() { 2154 try { 2155 return mService.getLastSleepReason(); 2156 } catch (RemoteException e) { 2157 throw e.rethrowFromSystemServer(); 2158 } 2159 } 2160 2161 /** 2162 * Forces the device to go to suspend, even if there are currently wakelocks being held. 2163 * <b>Caution</b> 2164 * This is a very dangerous command as it puts the device to sleep immediately. Apps and parts 2165 * of the system will not be notified and will not have an opportunity to save state prior to 2166 * the device going to suspend. 2167 * This method should only be used in very rare circumstances where the device is intended 2168 * to appear as completely off to the user and they have a well understood, reliable way of 2169 * re-enabling it. 2170 * </p><p> 2171 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission. 2172 * </p> 2173 * 2174 * @return true on success, false otherwise. 2175 * @hide 2176 */ 2177 @SystemApi 2178 @RequiresPermission(android.Manifest.permission.DEVICE_POWER) forceSuspend()2179 public boolean forceSuspend() { 2180 try { 2181 return mService.forceSuspend(); 2182 } catch (RemoteException e) { 2183 throw e.rethrowFromSystemServer(); 2184 } 2185 } 2186 2187 /** 2188 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes. 2189 * This broadcast is only sent to registered receivers. 2190 */ 2191 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2192 public static final String ACTION_POWER_SAVE_MODE_CHANGED 2193 = "android.os.action.POWER_SAVE_MODE_CHANGED"; 2194 2195 /** 2196 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes. 2197 * @hide 2198 */ 2199 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2200 public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL 2201 = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL"; 2202 2203 /** 2204 * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes. 2205 * This broadcast is only sent to registered receivers. 2206 */ 2207 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2208 public static final String ACTION_DEVICE_IDLE_MODE_CHANGED 2209 = "android.os.action.DEVICE_IDLE_MODE_CHANGED"; 2210 2211 /** 2212 * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes. 2213 * This broadcast is only sent to registered receivers. 2214 * @hide 2215 */ 2216 @UnsupportedAppUsage 2217 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2218 public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED 2219 = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED"; 2220 2221 /** 2222 * @hide Intent that is broadcast when the set of power save whitelist apps has changed. 2223 * This broadcast is only sent to registered receivers. 2224 */ 2225 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2226 public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED 2227 = "android.os.action.POWER_SAVE_WHITELIST_CHANGED"; 2228 2229 /** 2230 * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed. 2231 * This broadcast is only sent to registered receivers. 2232 */ 2233 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2234 public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED 2235 = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED"; 2236 2237 /** 2238 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change. 2239 * This broadcast is only sent to registered receivers. 2240 * 2241 * @deprecated This is sent at the same time as {@link #ACTION_POWER_SAVE_MODE_CHANGED} so it 2242 * does not provide advanced warning. As such it will be removed in future Android versions. 2243 * Use {@link #ACTION_POWER_SAVE_MODE_CHANGED} and {@link #isPowerSaveMode()} instead. 2244 * 2245 * @hide 2246 */ 2247 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, 2248 publicAlternatives = "Use {@link #ACTION_POWER_SAVE_MODE_CHANGED} instead.") 2249 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) 2250 @Deprecated 2251 public static final String ACTION_POWER_SAVE_MODE_CHANGING 2252 = "android.os.action.POWER_SAVE_MODE_CHANGING"; 2253 2254 /** 2255 * @deprecated Use {@link #isPowerSaveMode()} instead. 2256 * 2257 * @hide 2258 */ 2259 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.Q, 2260 publicAlternatives = "Use {@link #isPowerSaveMode()} instead.") 2261 @Deprecated 2262 public static final String EXTRA_POWER_SAVE_MODE = "mode"; 2263 2264 /** 2265 * Constant for PreIdleTimeout normal mode (default mode, not short nor extend timeout) . 2266 * @hide 2267 */ 2268 public static final int PRE_IDLE_TIMEOUT_MODE_NORMAL = 0; 2269 2270 /** 2271 * Constant for PreIdleTimeout long mode (extend timeout to keep in inactive mode 2272 * longer). 2273 * @hide 2274 */ 2275 public static final int PRE_IDLE_TIMEOUT_MODE_LONG = 1; 2276 2277 /** 2278 * Constant for PreIdleTimeout short mode (short timeout to go to doze mode quickly) 2279 * @hide 2280 */ 2281 public static final int PRE_IDLE_TIMEOUT_MODE_SHORT = 2; 2282 2283 /** 2284 * A wake lock is a mechanism to indicate that your application needs 2285 * to have the device stay on. 2286 * <p> 2287 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK} 2288 * permission in an {@code <uses-permission>} element of the application's manifest. 2289 * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}. 2290 * </p><p> 2291 * Call {@link #acquire()} to acquire the wake lock and force the device to stay 2292 * on at the level that was requested when the wake lock was created. 2293 * </p><p> 2294 * Call {@link #release()} when you are done and don't need the lock anymore. 2295 * It is very important to do this as soon as possible to avoid running down the 2296 * device's battery excessively. 2297 * </p> 2298 */ 2299 public final class WakeLock { 2300 @UnsupportedAppUsage 2301 private int mFlags; 2302 @UnsupportedAppUsage 2303 private String mTag; 2304 private final String mPackageName; 2305 private final IBinder mToken; 2306 private int mInternalCount; 2307 private int mExternalCount; 2308 private boolean mRefCounted = true; 2309 private boolean mHeld; 2310 private WorkSource mWorkSource; 2311 private String mHistoryTag; 2312 private final String mTraceName; 2313 2314 private final Runnable mReleaser = new Runnable() { 2315 public void run() { 2316 release(RELEASE_FLAG_TIMEOUT); 2317 } 2318 }; 2319 WakeLock(int flags, String tag, String packageName)2320 WakeLock(int flags, String tag, String packageName) { 2321 mFlags = flags; 2322 mTag = tag; 2323 mPackageName = packageName; 2324 mToken = new Binder(); 2325 mTraceName = "WakeLock (" + mTag + ")"; 2326 } 2327 2328 @Override finalize()2329 protected void finalize() throws Throwable { 2330 synchronized (mToken) { 2331 if (mHeld) { 2332 Log.wtf(TAG, "WakeLock finalized while still held: " + mTag); 2333 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 2334 try { 2335 mService.releaseWakeLock(mToken, 0); 2336 } catch (RemoteException e) { 2337 throw e.rethrowFromSystemServer(); 2338 } 2339 } 2340 } 2341 } 2342 2343 /** 2344 * Sets whether this WakeLock is reference counted. 2345 * <p> 2346 * Wake locks are reference counted by default. If a wake lock is 2347 * reference counted, then each call to {@link #acquire()} must be 2348 * balanced by an equal number of calls to {@link #release()}. If a wake 2349 * lock is not reference counted, then one call to {@link #release()} is 2350 * sufficient to undo the effect of all previous calls to {@link #acquire()}. 2351 * </p> 2352 * 2353 * @param value True to make the wake lock reference counted, false to 2354 * make the wake lock non-reference counted. 2355 */ setReferenceCounted(boolean value)2356 public void setReferenceCounted(boolean value) { 2357 synchronized (mToken) { 2358 mRefCounted = value; 2359 } 2360 } 2361 2362 /** 2363 * Acquires the wake lock. 2364 * <p> 2365 * Ensures that the device is on at the level requested when 2366 * the wake lock was created. 2367 * </p> 2368 */ acquire()2369 public void acquire() { 2370 synchronized (mToken) { 2371 acquireLocked(); 2372 } 2373 } 2374 2375 /** 2376 * Acquires the wake lock with a timeout. 2377 * <p> 2378 * Ensures that the device is on at the level requested when 2379 * the wake lock was created. The lock will be released after the given timeout 2380 * expires. 2381 * </p> 2382 * 2383 * @param timeout The timeout after which to release the wake lock, in milliseconds. 2384 */ acquire(long timeout)2385 public void acquire(long timeout) { 2386 synchronized (mToken) { 2387 acquireLocked(); 2388 mHandler.postDelayed(mReleaser, timeout); 2389 } 2390 } 2391 acquireLocked()2392 private void acquireLocked() { 2393 mInternalCount++; 2394 mExternalCount++; 2395 if (!mRefCounted || mInternalCount == 1) { 2396 // Do this even if the wake lock is already thought to be held (mHeld == true) 2397 // because non-reference counted wake locks are not always properly released. 2398 // For example, the keyguard's wake lock might be forcibly released by the 2399 // power manager without the keyguard knowing. A subsequent call to acquire 2400 // should immediately acquire the wake lock once again despite never having 2401 // been explicitly released by the keyguard. 2402 mHandler.removeCallbacks(mReleaser); 2403 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0); 2404 try { 2405 mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource, 2406 mHistoryTag); 2407 } catch (RemoteException e) { 2408 throw e.rethrowFromSystemServer(); 2409 } 2410 mHeld = true; 2411 } 2412 } 2413 2414 /** 2415 * Releases the wake lock. 2416 * <p> 2417 * This method releases your claim to the CPU or screen being on. 2418 * The screen may turn off shortly after you release the wake lock, or it may 2419 * not if there are other wake locks still held. 2420 * </p> 2421 */ release()2422 public void release() { 2423 release(0); 2424 } 2425 2426 /** 2427 * Releases the wake lock with flags to modify the release behavior. 2428 * <p> 2429 * This method releases your claim to the CPU or screen being on. 2430 * The screen may turn off shortly after you release the wake lock, or it may 2431 * not if there are other wake locks still held. 2432 * </p> 2433 * 2434 * @param flags Combination of flag values to modify the release behavior. 2435 * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported. 2436 * Passing 0 is equivalent to calling {@link #release()}. 2437 */ release(int flags)2438 public void release(int flags) { 2439 synchronized (mToken) { 2440 if (mInternalCount > 0) { 2441 // internal count must only be decreased if it is > 0 or state of 2442 // the WakeLock object is broken. 2443 mInternalCount--; 2444 } 2445 if ((flags & RELEASE_FLAG_TIMEOUT) == 0) { 2446 mExternalCount--; 2447 } 2448 if (!mRefCounted || mInternalCount == 0) { 2449 mHandler.removeCallbacks(mReleaser); 2450 if (mHeld) { 2451 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 2452 try { 2453 mService.releaseWakeLock(mToken, flags); 2454 } catch (RemoteException e) { 2455 throw e.rethrowFromSystemServer(); 2456 } 2457 mHeld = false; 2458 } 2459 } 2460 if (mRefCounted && mExternalCount < 0) { 2461 throw new RuntimeException("WakeLock under-locked " + mTag); 2462 } 2463 } 2464 } 2465 2466 /** 2467 * Returns true if the wake lock has been acquired but not yet released. 2468 * 2469 * @return True if the wake lock is held. 2470 */ isHeld()2471 public boolean isHeld() { 2472 synchronized (mToken) { 2473 return mHeld; 2474 } 2475 } 2476 2477 /** 2478 * Sets the work source associated with the wake lock. 2479 * <p> 2480 * The work source is used to determine on behalf of which application 2481 * the wake lock is being held. This is useful in the case where a 2482 * service is performing work on behalf of an application so that the 2483 * cost of that work can be accounted to the application. 2484 * </p> 2485 * 2486 * <p> 2487 * Make sure to follow the tag naming convention when using WorkSource 2488 * to make it easier for app developers to understand wake locks 2489 * attributed to them. See {@link PowerManager#newWakeLock(int, String)} 2490 * documentation. 2491 * </p> 2492 * 2493 * @param ws The work source, or null if none. 2494 */ setWorkSource(WorkSource ws)2495 public void setWorkSource(WorkSource ws) { 2496 synchronized (mToken) { 2497 if (ws != null && ws.isEmpty()) { 2498 ws = null; 2499 } 2500 2501 final boolean changed; 2502 if (ws == null) { 2503 changed = mWorkSource != null; 2504 mWorkSource = null; 2505 } else if (mWorkSource == null) { 2506 changed = true; 2507 mWorkSource = new WorkSource(ws); 2508 } else { 2509 changed = !mWorkSource.equals(ws); 2510 if (changed) { 2511 mWorkSource.set(ws); 2512 } 2513 } 2514 2515 if (changed && mHeld) { 2516 try { 2517 mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag); 2518 } catch (RemoteException e) { 2519 throw e.rethrowFromSystemServer(); 2520 } 2521 } 2522 } 2523 } 2524 2525 /** @hide */ setTag(String tag)2526 public void setTag(String tag) { 2527 mTag = tag; 2528 } 2529 2530 /** @hide */ getTag()2531 public String getTag() { 2532 return mTag; 2533 } 2534 2535 /** @hide */ setHistoryTag(String tag)2536 public void setHistoryTag(String tag) { 2537 mHistoryTag = tag; 2538 } 2539 2540 /** @hide */ setUnimportantForLogging(boolean state)2541 public void setUnimportantForLogging(boolean state) { 2542 if (state) mFlags |= UNIMPORTANT_FOR_LOGGING; 2543 else mFlags &= ~UNIMPORTANT_FOR_LOGGING; 2544 } 2545 2546 @Override toString()2547 public String toString() { 2548 synchronized (mToken) { 2549 return "WakeLock{" 2550 + Integer.toHexString(System.identityHashCode(this)) 2551 + " held=" + mHeld + ", refCount=" + mInternalCount + "}"; 2552 } 2553 } 2554 2555 /** @hide */ dumpDebug(ProtoOutputStream proto, long fieldId)2556 public void dumpDebug(ProtoOutputStream proto, long fieldId) { 2557 synchronized (mToken) { 2558 final long token = proto.start(fieldId); 2559 proto.write(PowerManagerProto.WakeLock.TAG, mTag); 2560 proto.write(PowerManagerProto.WakeLock.PACKAGE_NAME, mPackageName); 2561 proto.write(PowerManagerProto.WakeLock.HELD, mHeld); 2562 proto.write(PowerManagerProto.WakeLock.INTERNAL_COUNT, mInternalCount); 2563 if (mWorkSource != null) { 2564 mWorkSource.dumpDebug(proto, PowerManagerProto.WakeLock.WORK_SOURCE); 2565 } 2566 proto.end(token); 2567 } 2568 } 2569 2570 /** 2571 * Wraps a Runnable such that this method immediately acquires the wake lock and then 2572 * once the Runnable is done the wake lock is released. 2573 * 2574 * <p>Example: 2575 * 2576 * <pre> 2577 * mHandler.post(mWakeLock.wrap(() -> { 2578 * // do things on handler, lock is held while we're waiting for this 2579 * // to get scheduled and until the runnable is done executing. 2580 * }); 2581 * </pre> 2582 * 2583 * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll 2584 * leak the wakelock! 2585 * 2586 * @hide 2587 */ wrap(Runnable r)2588 public Runnable wrap(Runnable r) { 2589 acquire(); 2590 return () -> { 2591 try { 2592 r.run(); 2593 } finally { 2594 release(); 2595 } 2596 }; 2597 } 2598 } 2599 2600 /** 2601 * @hide 2602 */ 2603 public static void invalidatePowerSaveModeCaches() { 2604 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_IS_POWER_SAVE_MODE_PROPERTY); 2605 } 2606 2607 /** 2608 * @hide 2609 */ 2610 public static void invalidateIsInteractiveCaches() { 2611 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_IS_INTERACTIVE_PROPERTY); 2612 } 2613 } 2614