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