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