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