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