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