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.annotation.IntDef;
     20 import android.annotation.RequiresPermission;
     21 import android.annotation.SdkConstant;
     22 import android.annotation.SystemApi;
     23 import android.annotation.SystemService;
     24 import android.content.Context;
     25 import android.util.Log;
     26 import java.lang.annotation.Retention;
     27 import java.lang.annotation.RetentionPolicy;
     28 
     29 /**
     30  * This class gives you control of the power state of the device.
     31  *
     32  * <p>
     33  * <b>Device battery life will be significantly affected by the use of this API.</b>
     34  * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
     35  * possible, and be sure to release them as soon as possible.
     36  * </p><p>
     37  * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
     38  * This will create a {@link PowerManager.WakeLock} object.  You can then use methods
     39  * on the wake lock object to control the power state of the device.
     40  * </p><p>
     41  * In practice it's quite simple:
     42  * {@samplecode
     43  * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
     44  * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
     45  * wl.acquire();
     46  *   ..screen will stay on during this section..
     47  * wl.release();
     48  * }
     49  * </p><p>
     50  * The following wake lock levels are defined, with varying effects on system power.
     51  * <i>These levels are mutually exclusive - you may only specify one of them.</i>
     52  *
     53  * <table>
     54  *     <tr><th>Flag Value</th>
     55  *     <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
     56  *
     57  *     <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
     58  *         <td>On*</td> <td>Off</td> <td>Off</td>
     59  *     </tr>
     60  *
     61  *     <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
     62  *         <td>On</td> <td>Dim</td> <td>Off</td>
     63  *     </tr>
     64  *
     65  *     <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
     66  *         <td>On</td> <td>Bright</td> <td>Off</td>
     67  *     </tr>
     68  *
     69  *     <tr><td>{@link #FULL_WAKE_LOCK}</td>
     70  *         <td>On</td> <td>Bright</td> <td>Bright</td>
     71  *     </tr>
     72  * </table>
     73  * </p><p>
     74  * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
     75  * display timeouts or the state of the screen and even after the user presses the power button.
     76  * In all other wake locks, the CPU will run, but the user can still put the device to sleep
     77  * using the power button.</i>
     78  * </p><p>
     79  * In addition, you can add two more flags, which affect behavior of the screen only.
     80  * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
     81  *
     82  * <table>
     83  *     <tr><th>Flag Value</th> <th>Description</th></tr>
     84  *
     85  *     <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
     86  *         <td>Normal wake locks don't actually turn on the illumination.  Instead, they cause
     87  *         the illumination to remain on once it turns on (e.g. from user activity).  This flag
     88  *         will force the screen and/or keyboard to turn on immediately, when the WakeLock is
     89  *         acquired.  A typical use would be for notifications which are important for the user to
     90  *         see immediately.</td>
     91  *     </tr>
     92  *
     93  *     <tr><td>{@link #ON_AFTER_RELEASE}</td>
     94  *         <td>If this flag is set, the user activity timer will be reset when the WakeLock is
     95  *         released, causing the illumination to remain on a bit longer.  This can be used to
     96  *         reduce flicker if you are cycling between wake lock conditions.</td>
     97  *     </tr>
     98  * </table>
     99  * <p>
    100  * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
    101  * permission in an {@code <uses-permission>} element of the application's manifest.
    102  * </p>
    103  */
    104 @SystemService(Context.POWER_SERVICE)
    105 public final class PowerManager {
    106     private static final String TAG = "PowerManager";
    107 
    108     /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
    109      * combinations were actually supported so the bit field was removed.  This explains
    110      * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
    111      * value can be used.
    112      */
    113 
    114     /**
    115      * Wake lock level: Ensures that the CPU is running; the screen and keyboard
    116      * backlight will be allowed to go off.
    117      * <p>
    118      * If the user presses the power button, then the screen will be turned off
    119      * but the CPU will be kept on until all partial wake locks have been released.
    120      * </p>
    121      */
    122     public static final int PARTIAL_WAKE_LOCK = 0x00000001;
    123 
    124     /**
    125      * Wake lock level: Ensures that the screen is on (but may be dimmed);
    126      * the keyboard backlight will be allowed to go off.
    127      * <p>
    128      * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
    129      * implicitly released by the system, causing both the screen and the CPU to be turned off.
    130      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
    131      * </p>
    132      *
    133      * @deprecated Most applications should use
    134      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
    135      * of this type of wake lock, as it will be correctly managed by the platform
    136      * as the user moves between applications and doesn't require a special permission.
    137      */
    138     @Deprecated
    139     public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;
    140 
    141     /**
    142      * Wake lock level: Ensures that the screen is on at full brightness;
    143      * the keyboard backlight will be allowed to go off.
    144      * <p>
    145      * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
    146      * implicitly released by the system, causing both the screen and the CPU to be turned off.
    147      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
    148      * </p>
    149      *
    150      * @deprecated Most applications should use
    151      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
    152      * of this type of wake lock, as it will be correctly managed by the platform
    153      * as the user moves between applications and doesn't require a special permission.
    154      */
    155     @Deprecated
    156     public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a;
    157 
    158     /**
    159      * Wake lock level: Ensures that the screen and keyboard backlight are on at
    160      * full brightness.
    161      * <p>
    162      * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
    163      * implicitly released by the system, causing both the screen and the CPU to be turned off.
    164      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
    165      * </p>
    166      *
    167      * @deprecated Most applications should use
    168      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
    169      * of this type of wake lock, as it will be correctly managed by the platform
    170      * as the user moves between applications and doesn't require a special permission.
    171      */
    172     @Deprecated
    173     public static final int FULL_WAKE_LOCK = 0x0000001a;
    174 
    175     /**
    176      * Wake lock level: Turns the screen off when the proximity sensor activates.
    177      * <p>
    178      * If the proximity sensor detects that an object is nearby, the screen turns off
    179      * immediately.  Shortly after the object moves away, the screen turns on again.
    180      * </p><p>
    181      * A proximity wake lock does not prevent the device from falling asleep
    182      * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
    183      * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
    184      * wake locks are held, then the device will fall asleep (and lock) as usual.
    185      * However, the device will not fall asleep while the screen has been turned off
    186      * by the proximity sensor because it effectively counts as ongoing user activity.
    187      * </p><p>
    188      * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
    189      * to determine whether this wake lock level is supported.
    190      * </p><p>
    191      * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
    192      * </p>
    193      */
    194     public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020;
    195 
    196     /**
    197      * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
    198      * if no other wake locks are held.
    199      * <p>
    200      * This is used by the dream manager to implement doze mode.  It currently
    201      * has no effect unless the power manager is in the dozing state.
    202      * </p><p>
    203      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    204      * </p>
    205      *
    206      * {@hide}
    207      */
    208     public static final int DOZE_WAKE_LOCK = 0x00000040;
    209 
    210     /**
    211      * Wake lock level: Keep the device awake enough to allow drawing to occur.
    212      * <p>
    213      * This is used by the window manager to allow applications to draw while the
    214      * system is dozing.  It currently has no effect unless the power manager is in
    215      * 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 DRAW_WAKE_LOCK = 0x00000080;
    223 
    224     /**
    225      * Mask for the wake lock level component of a combined wake lock level and flags integer.
    226      *
    227      * @hide
    228      */
    229     public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
    230 
    231     /**
    232      * Wake lock flag: Turn the screen on when the wake lock is acquired.
    233      * <p>
    234      * Normally wake locks don't actually wake the device, they just cause
    235      * the screen to remain on once it's already on.  Think of the video player
    236      * application as the normal behavior.  Notifications that pop up and want
    237      * the device to be on are the exception; use this flag to be like them.
    238      * </p><p>
    239      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
    240      * </p>
    241      */
    242     public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
    243 
    244     /**
    245      * Wake lock flag: When this wake lock is released, poke the user activity timer
    246      * so the screen stays on for a little longer.
    247      * <p>
    248      * Will not turn the screen on if it is not already on.
    249      * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
    250      * </p><p>
    251      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
    252      * </p>
    253      */
    254     public static final int ON_AFTER_RELEASE = 0x20000000;
    255 
    256     /**
    257      * Wake lock flag: This wake lock is not important for logging events.  If a later
    258      * wake lock is acquired that is important, it will be considered the one to log.
    259      * @hide
    260      */
    261     public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
    262 
    263     /**
    264      * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
    265      * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
    266      * indicates that an object is not in close proximity.
    267      */
    268     public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
    269 
    270     /**
    271      * Brightness value for fully on.
    272      * @hide
    273      */
    274     public static final int BRIGHTNESS_ON = 255;
    275 
    276     /**
    277      * Brightness value for fully off.
    278      * @hide
    279      */
    280     public static final int BRIGHTNESS_OFF = 0;
    281 
    282     /**
    283      * Brightness value for default policy handling by the system.
    284      * @hide
    285      */
    286     public static final int BRIGHTNESS_DEFAULT = -1;
    287 
    288     // Note: Be sure to update android.os.BatteryStats and PowerManager.h
    289     // if adding or modifying user activity event constants.
    290 
    291     /**
    292      * User activity event type: Unspecified event type.
    293      * @hide
    294      */
    295     @SystemApi
    296     public static final int USER_ACTIVITY_EVENT_OTHER = 0;
    297 
    298     /**
    299      * User activity event type: Button or key pressed or released.
    300      * @hide
    301      */
    302     @SystemApi
    303     public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
    304 
    305     /**
    306      * User activity event type: Touch down, move or up.
    307      * @hide
    308      */
    309     @SystemApi
    310     public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
    311 
    312     /**
    313      * User activity event type: Accessibility taking action on behalf of user.
    314      * @hide
    315      */
    316     @SystemApi
    317     public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
    318 
    319     /**
    320      * User activity flag: If already dimmed, extend the dim timeout
    321      * but do not brighten.  This flag is useful for keeping the screen on
    322      * a little longer without causing a visible change such as when
    323      * the power key is pressed.
    324      * @hide
    325      */
    326     @SystemApi
    327     public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
    328 
    329     /**
    330      * User activity flag: Note the user activity as usual but do not
    331      * reset the user activity timeout.  This flag is useful for applying
    332      * user activity power hints when interacting with the device indirectly
    333      * on a secondary screen while allowing the primary screen to go to sleep.
    334      * @hide
    335      */
    336     @SystemApi
    337     public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
    338 
    339     /**
    340      * Go to sleep reason code: Going to sleep due by application request.
    341      * @hide
    342      */
    343     public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
    344 
    345     /**
    346      * Go to sleep reason code: Going to sleep due by request of the
    347      * device administration policy.
    348      * @hide
    349      */
    350     public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
    351 
    352     /**
    353      * Go to sleep reason code: Going to sleep due to a screen timeout.
    354      * @hide
    355      */
    356     public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
    357 
    358     /**
    359      * Go to sleep reason code: Going to sleep due to the lid switch being closed.
    360      * @hide
    361      */
    362     public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
    363 
    364     /**
    365      * Go to sleep reason code: Going to sleep due to the power button being pressed.
    366      * @hide
    367      */
    368     public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
    369 
    370     /**
    371      * Go to sleep reason code: Going to sleep due to HDMI.
    372      * @hide
    373      */
    374     public static final int GO_TO_SLEEP_REASON_HDMI = 5;
    375 
    376     /**
    377      * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
    378      * @hide
    379      */
    380     public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
    381 
    382     /**
    383      * Go to sleep flag: Skip dozing state and directly go to full sleep.
    384      * @hide
    385      */
    386     public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
    387 
    388     /**
    389      * The value to pass as the 'reason' argument to reboot() to reboot into
    390      * recovery mode for tasks other than applying system updates, such as
    391      * doing factory resets.
    392      * <p>
    393      * Requires the {@link android.Manifest.permission#RECOVERY}
    394      * permission (in addition to
    395      * {@link android.Manifest.permission#REBOOT}).
    396      * </p>
    397      * @hide
    398      */
    399     public static final String REBOOT_RECOVERY = "recovery";
    400 
    401     /**
    402      * The value to pass as the 'reason' argument to reboot() to reboot into
    403      * recovery mode for applying system updates.
    404      * <p>
    405      * Requires the {@link android.Manifest.permission#RECOVERY}
    406      * permission (in addition to
    407      * {@link android.Manifest.permission#REBOOT}).
    408      * </p>
    409      * @hide
    410      */
    411     public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
    412 
    413     /**
    414      * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
    415      * the device.
    416      * @hide
    417      */
    418     public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
    419 
    420     /**
    421      * The 'reason' value used when rebooting in safe mode
    422      * @hide
    423      */
    424     public static final String REBOOT_SAFE_MODE = "safemode";
    425 
    426     /**
    427      * The 'reason' value used when rebooting the device without turning on the screen.
    428      * @hide
    429      */
    430     public static final String REBOOT_QUIESCENT = "quiescent";
    431 
    432     /**
    433      * The value to pass as the 'reason' argument to android_reboot().
    434      * @hide
    435      */
    436     public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
    437 
    438     /**
    439      * @hide
    440      */
    441     @Retention(RetentionPolicy.SOURCE)
    442     @IntDef({
    443             SHUTDOWN_REASON_UNKNOWN,
    444             SHUTDOWN_REASON_SHUTDOWN,
    445             SHUTDOWN_REASON_REBOOT,
    446             SHUTDOWN_REASON_USER_REQUESTED,
    447             SHUTDOWN_REASON_THERMAL_SHUTDOWN
    448     })
    449     public @interface ShutdownReason {}
    450 
    451     /**
    452      * constant for shutdown reason being unknown.
    453      * @hide
    454      */
    455     public static final int SHUTDOWN_REASON_UNKNOWN = 0;
    456 
    457     /**
    458      * constant for shutdown reason being normal shutdown.
    459      * @hide
    460      */
    461     public static final int SHUTDOWN_REASON_SHUTDOWN = 1;
    462 
    463     /**
    464      * constant for shutdown reason being reboot.
    465      * @hide
    466      */
    467     public static final int SHUTDOWN_REASON_REBOOT = 2;
    468 
    469     /**
    470      * constant for shutdown reason being user requested.
    471      * @hide
    472      */
    473     public static final int SHUTDOWN_REASON_USER_REQUESTED = 3;
    474 
    475     /**
    476      * constant for shutdown reason being overheating.
    477      * @hide
    478      */
    479     public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4;
    480 
    481     final Context mContext;
    482     final IPowerManager mService;
    483     final Handler mHandler;
    484 
    485     IDeviceIdleController mIDeviceIdleController;
    486 
    487     /**
    488      * {@hide}
    489      */
    490     public PowerManager(Context context, IPowerManager service, Handler handler) {
    491         mContext = context;
    492         mService = service;
    493         mHandler = handler;
    494     }
    495 
    496     /**
    497      * Gets the minimum supported screen brightness setting.
    498      * The screen may be allowed to become dimmer than this value but
    499      * this is the minimum value that can be set by the user.
    500      * @hide
    501      */
    502     public int getMinimumScreenBrightnessSetting() {
    503         return mContext.getResources().getInteger(
    504                 com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
    505     }
    506 
    507     /**
    508      * Gets the maximum supported screen brightness setting.
    509      * The screen may be allowed to become dimmer than this value but
    510      * this is the maximum value that can be set by the user.
    511      * @hide
    512      */
    513     public int getMaximumScreenBrightnessSetting() {
    514         return mContext.getResources().getInteger(
    515                 com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
    516     }
    517 
    518     /**
    519      * Gets the default screen brightness setting.
    520      * @hide
    521      */
    522     public int getDefaultScreenBrightnessSetting() {
    523         return mContext.getResources().getInteger(
    524                 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
    525     }
    526 
    527     /**
    528      * Gets the minimum supported screen brightness setting for VR Mode.
    529      * @hide
    530      */
    531     public int getMinimumScreenBrightnessForVrSetting() {
    532         return mContext.getResources().getInteger(
    533                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum);
    534     }
    535 
    536     /**
    537      * Gets the maximum supported screen brightness setting for VR Mode.
    538      * The screen may be allowed to become dimmer than this value but
    539      * this is the maximum value that can be set by the user.
    540      * @hide
    541      */
    542     public int getMaximumScreenBrightnessForVrSetting() {
    543         return mContext.getResources().getInteger(
    544                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum);
    545     }
    546 
    547     /**
    548      * Gets the default screen brightness for VR setting.
    549      * @hide
    550      */
    551     public int getDefaultScreenBrightnessForVrSetting() {
    552         return mContext.getResources().getInteger(
    553                 com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
    554     }
    555 
    556     /**
    557      * Creates a new wake lock with the specified level and flags.
    558      * <p>
    559      * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
    560      * combined using the logical OR operator.
    561      * </p><p>
    562      * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
    563      * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
    564      * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
    565      * specified as part of the {@code levelAndFlags} parameter.
    566      * </p><p>
    567      * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
    568      * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
    569      * {@code levelAndFlags} parameters.
    570      * </p><p>
    571      * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
    572      * wake lock, and {@link WakeLock#release release()} when you are done.
    573      * </p><p>
    574      * {@samplecode
    575      * PowerManager pm = (PowerManager)mContext.getSystemService(
    576      *                                          Context.POWER_SERVICE);
    577      * PowerManager.WakeLock wl = pm.newWakeLock(
    578      *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
    579      *                                      | PowerManager.ON_AFTER_RELEASE,
    580      *                                      TAG);
    581      * wl.acquire();
    582      * // ... do work...
    583      * wl.release();
    584      * }
    585      * </p><p>
    586      * Although a wake lock can be created without special permissions,
    587      * the {@link android.Manifest.permission#WAKE_LOCK} permission is
    588      * required to actually acquire or release the wake lock that is returned.
    589      * </p><p class="note">
    590      * If using this to keep the screen on, you should strongly consider using
    591      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
    592      * This window flag will be correctly managed by the platform
    593      * as the user moves between applications and doesn't require a special permission.
    594      * </p>
    595      *
    596      * @param levelAndFlags Combination of wake lock level and flag values defining
    597      * the requested behavior of the WakeLock.
    598      * @param tag Your class name (or other tag) for debugging purposes.
    599      *
    600      * @see WakeLock#acquire()
    601      * @see WakeLock#release()
    602      * @see #PARTIAL_WAKE_LOCK
    603      * @see #FULL_WAKE_LOCK
    604      * @see #SCREEN_DIM_WAKE_LOCK
    605      * @see #SCREEN_BRIGHT_WAKE_LOCK
    606      * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
    607      * @see #ACQUIRE_CAUSES_WAKEUP
    608      * @see #ON_AFTER_RELEASE
    609      */
    610     public WakeLock newWakeLock(int levelAndFlags, String tag) {
    611         validateWakeLockParameters(levelAndFlags, tag);
    612         return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
    613     }
    614 
    615     /** @hide */
    616     public static void validateWakeLockParameters(int levelAndFlags, String tag) {
    617         switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
    618             case PARTIAL_WAKE_LOCK:
    619             case SCREEN_DIM_WAKE_LOCK:
    620             case SCREEN_BRIGHT_WAKE_LOCK:
    621             case FULL_WAKE_LOCK:
    622             case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
    623             case DOZE_WAKE_LOCK:
    624             case DRAW_WAKE_LOCK:
    625                 break;
    626             default:
    627                 throw new IllegalArgumentException("Must specify a valid wake lock level.");
    628         }
    629         if (tag == null) {
    630             throw new IllegalArgumentException("The tag must not be null.");
    631         }
    632     }
    633 
    634     /**
    635      * Notifies the power manager that user activity happened.
    636      * <p>
    637      * Resets the auto-off timer and brightens the screen if the device
    638      * is not asleep.  This is what happens normally when a key or the touch
    639      * screen is pressed or when some other user activity occurs.
    640      * This method does not wake up the device if it has been put to sleep.
    641      * </p><p>
    642      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    643      * </p>
    644      *
    645      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
    646      * time base.  This timestamp is used to correctly order the user activity request with
    647      * other power management functions.  It should be set
    648      * to the timestamp of the input event that caused the user activity.
    649      * @param noChangeLights If true, does not cause the keyboard backlight to turn on
    650      * because of this event.  This is set when the power key is pressed.
    651      * We want the device to stay on while the button is down, but we're about
    652      * to turn off the screen so we don't want the keyboard backlight to turn on again.
    653      * Otherwise the lights flash on and then off and it looks weird.
    654      *
    655      * @see #wakeUp
    656      * @see #goToSleep
    657      *
    658      * @removed Requires signature or system permission.
    659      * @deprecated Use {@link #userActivity(long, int, int)}.
    660      */
    661     @Deprecated
    662     public void userActivity(long when, boolean noChangeLights) {
    663         userActivity(when, USER_ACTIVITY_EVENT_OTHER,
    664                 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
    665     }
    666 
    667     /**
    668      * Notifies the power manager that user activity happened.
    669      * <p>
    670      * Resets the auto-off timer and brightens the screen if the device
    671      * is not asleep.  This is what happens normally when a key or the touch
    672      * screen is pressed or when some other user activity occurs.
    673      * This method does not wake up the device if it has been put to sleep.
    674      * </p><p>
    675      * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
    676      * {@link android.Manifest.permission#USER_ACTIVITY} permission.
    677      * </p>
    678      *
    679      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
    680      * time base.  This timestamp is used to correctly order the user activity request with
    681      * other power management functions.  It should be set
    682      * to the timestamp of the input event that caused the user activity.
    683      * @param event The user activity event.
    684      * @param flags Optional user activity flags.
    685      *
    686      * @see #wakeUp
    687      * @see #goToSleep
    688      *
    689      * @hide Requires signature or system permission.
    690      */
    691     @SystemApi
    692     @RequiresPermission(anyOf = {
    693             android.Manifest.permission.DEVICE_POWER,
    694             android.Manifest.permission.USER_ACTIVITY
    695     })
    696     public void userActivity(long when, int event, int flags) {
    697         try {
    698             mService.userActivity(when, event, flags);
    699         } catch (RemoteException e) {
    700             throw e.rethrowFromSystemServer();
    701         }
    702     }
    703 
    704    /**
    705      * Forces the device to go to sleep.
    706      * <p>
    707      * Overrides all the wake locks that are held.
    708      * This is what happens when the power key is pressed to turn off the screen.
    709      * </p><p>
    710      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    711      * </p>
    712      *
    713      * @param time The time when the request to go to sleep was issued, in the
    714      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
    715      * order the go to sleep request with other power management functions.  It should be set
    716      * to the timestamp of the input event that caused the request to go to sleep.
    717      *
    718      * @see #userActivity
    719      * @see #wakeUp
    720      *
    721      * @removed Requires signature permission.
    722      */
    723     public void goToSleep(long time) {
    724         goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
    725     }
    726 
    727     /**
    728      * Forces the device to go to sleep.
    729      * <p>
    730      * Overrides all the wake locks that are held.
    731      * This is what happens when the power key is pressed to turn off the screen.
    732      * </p><p>
    733      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    734      * </p>
    735      *
    736      * @param time The time when the request to go to sleep was issued, in the
    737      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
    738      * order the go to sleep request with other power management functions.  It should be set
    739      * to the timestamp of the input event that caused the request to go to sleep.
    740      * @param reason The reason the device is going to sleep.
    741      * @param flags Optional flags to apply when going to sleep.
    742      *
    743      * @see #userActivity
    744      * @see #wakeUp
    745      *
    746      * @hide Requires signature permission.
    747      */
    748     public void goToSleep(long time, int reason, int flags) {
    749         try {
    750             mService.goToSleep(time, reason, flags);
    751         } catch (RemoteException e) {
    752             throw e.rethrowFromSystemServer();
    753         }
    754     }
    755 
    756     /**
    757      * Forces the device to wake up from sleep.
    758      * <p>
    759      * If the device is currently asleep, wakes it up, otherwise does nothing.
    760      * This is what happens when the power key is pressed to turn on the screen.
    761      * </p><p>
    762      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    763      * </p>
    764      *
    765      * @param time The time when the request to wake up was issued, in the
    766      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
    767      * order the wake up request with other power management functions.  It should be set
    768      * to the timestamp of the input event that caused the request to wake up.
    769      *
    770      * @see #userActivity
    771      * @see #goToSleep
    772      *
    773      * @removed Requires signature permission.
    774      */
    775     public void wakeUp(long time) {
    776         try {
    777             mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
    778         } catch (RemoteException e) {
    779             throw e.rethrowFromSystemServer();
    780         }
    781     }
    782 
    783     /**
    784      * @hide
    785      */
    786     public void wakeUp(long time, String reason) {
    787         try {
    788             mService.wakeUp(time, reason, mContext.getOpPackageName());
    789         } catch (RemoteException e) {
    790             throw e.rethrowFromSystemServer();
    791         }
    792     }
    793 
    794     /**
    795      * Forces the device to start napping.
    796      * <p>
    797      * If the device is currently awake, starts dreaming, otherwise does nothing.
    798      * When the dream ends or if the dream cannot be started, the device will
    799      * either wake up or go to sleep depending on whether there has been recent
    800      * user activity.
    801      * </p><p>
    802      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    803      * </p>
    804      *
    805      * @param time The time when the request to nap was issued, in the
    806      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
    807      * order the nap request with other power management functions.  It should be set
    808      * to the timestamp of the input event that caused the request to nap.
    809      *
    810      * @see #wakeUp
    811      * @see #goToSleep
    812      *
    813      * @hide Requires signature permission.
    814      */
    815     public void nap(long time) {
    816         try {
    817             mService.nap(time);
    818         } catch (RemoteException e) {
    819             throw e.rethrowFromSystemServer();
    820         }
    821     }
    822 
    823     /**
    824      * Boosts the brightness of the screen to maximum for a predetermined
    825      * period of time.  This is used to make the screen more readable in bright
    826      * daylight for a short duration.
    827      * <p>
    828      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    829      * </p>
    830      *
    831      * @param time The time when the request to boost was issued, in the
    832      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
    833      * order the boost request with other power management functions.  It should be set
    834      * to the timestamp of the input event that caused the request to boost.
    835      *
    836      * @hide Requires signature permission.
    837      */
    838     public void boostScreenBrightness(long time) {
    839         try {
    840             mService.boostScreenBrightness(time);
    841         } catch (RemoteException e) {
    842             throw e.rethrowFromSystemServer();
    843         }
    844     }
    845 
    846     /**
    847      * Returns whether the screen brightness is currently boosted to maximum, caused by a call
    848      * to {@link #boostScreenBrightness(long)}.
    849      * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
    850      *
    851      * @hide
    852      */
    853     @SystemApi
    854     public boolean isScreenBrightnessBoosted() {
    855         try {
    856             return mService.isScreenBrightnessBoosted();
    857         } catch (RemoteException e) {
    858             throw e.rethrowFromSystemServer();
    859         }
    860     }
    861 
    862     /**
    863      * Sets the brightness of the backlights (screen, keyboard, button).
    864      * <p>
    865      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
    866      * </p>
    867      *
    868      * @param brightness The brightness value from 0 to 255.
    869      *
    870      * @hide Requires signature permission.
    871      */
    872     public void setBacklightBrightness(int brightness) {
    873         try {
    874             mService.setTemporaryScreenBrightnessSettingOverride(brightness);
    875         } catch (RemoteException e) {
    876             throw e.rethrowFromSystemServer();
    877         }
    878     }
    879 
    880    /**
    881      * Returns true if the specified wake lock level is supported.
    882      *
    883      * @param level The wake lock level to check.
    884      * @return True if the specified wake lock level is supported.
    885      */
    886     public boolean isWakeLockLevelSupported(int level) {
    887         try {
    888             return mService.isWakeLockLevelSupported(level);
    889         } catch (RemoteException e) {
    890             throw e.rethrowFromSystemServer();
    891         }
    892     }
    893 
    894     /**
    895       * Returns true if the device is in an interactive state.
    896       * <p>
    897       * For historical reasons, the name of this method refers to the power state of
    898       * the screen but it actually describes the overall interactive state of
    899       * the device.  This method has been replaced by {@link #isInteractive}.
    900       * </p><p>
    901       * The value returned by this method only indicates whether the device is
    902       * in an interactive state which may have nothing to do with the screen being
    903       * on or off.  To determine the actual state of the screen,
    904       * use {@link android.view.Display#getState}.
    905       * </p>
    906       *
    907       * @return True if the device is in an interactive state.
    908       *
    909       * @deprecated Use {@link #isInteractive} instead.
    910       */
    911     @Deprecated
    912     public boolean isScreenOn() {
    913         return isInteractive();
    914     }
    915 
    916     /**
    917      * Returns true if the device is in an interactive state.
    918      * <p>
    919      * When this method returns true, the device is awake and ready to interact
    920      * with the user (although this is not a guarantee that the user is actively
    921      * interacting with the device just this moment).  The main screen is usually
    922      * turned on while in this state.  Certain features, such as the proximity
    923      * sensor, may temporarily turn off the screen while still leaving the device in an
    924      * interactive state.  Note in particular that the device is still considered
    925      * to be interactive while dreaming (since dreams can be interactive) but not
    926      * when it is dozing or asleep.
    927      * </p><p>
    928      * When this method returns false, the device is dozing or asleep and must
    929      * be awoken before it will become ready to interact with the user again.  The
    930      * main screen is usually turned off while in this state.  Certain features,
    931      * such as "ambient mode" may cause the main screen to remain on (albeit in a
    932      * low power state) to display system-provided content while the device dozes.
    933      * </p><p>
    934      * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
    935      * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
    936      * whenever the interactive state of the device changes.  For historical reasons,
    937      * the names of these broadcasts refer to the power state of the screen
    938      * but they are actually sent in response to changes in the overall interactive
    939      * state of the device, as described by this method.
    940      * </p><p>
    941      * Services may use the non-interactive state as a hint to conserve power
    942      * since the user is not present.
    943      * </p>
    944      *
    945      * @return True if the device is in an interactive state.
    946      *
    947      * @see android.content.Intent#ACTION_SCREEN_ON
    948      * @see android.content.Intent#ACTION_SCREEN_OFF
    949      */
    950     public boolean isInteractive() {
    951         try {
    952             return mService.isInteractive();
    953         } catch (RemoteException e) {
    954             throw e.rethrowFromSystemServer();
    955         }
    956     }
    957 
    958     /**
    959      * Reboot the device.  Will not return if the reboot is successful.
    960      * <p>
    961      * Requires the {@link android.Manifest.permission#REBOOT} permission.
    962      * </p>
    963      *
    964      * @param reason code to pass to the kernel (e.g., "recovery") to
    965      *               request special boot modes, or null.
    966      */
    967     public void reboot(String reason) {
    968         try {
    969             mService.reboot(false, reason, true);
    970         } catch (RemoteException e) {
    971             throw e.rethrowFromSystemServer();
    972         }
    973     }
    974 
    975     /**
    976      * Reboot the device. Will not return if the reboot is successful.
    977      * <p>
    978      * Requires the {@link android.Manifest.permission#REBOOT} permission.
    979      * </p>
    980      * @hide
    981      */
    982     public void rebootSafeMode() {
    983         try {
    984             mService.rebootSafeMode(false, true);
    985         } catch (RemoteException e) {
    986             throw e.rethrowFromSystemServer();
    987         }
    988     }
    989 
    990     /**
    991      * Returns true if the device is currently in power save mode.  When in this mode,
    992      * applications should reduce their functionality in order to conserve battery as
    993      * much as possible.  You can monitor for changes to this state with
    994      * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
    995      *
    996      * @return Returns true if currently in low power mode, else false.
    997      */
    998     public boolean isPowerSaveMode() {
    999         try {
   1000             return mService.isPowerSaveMode();
   1001         } catch (RemoteException e) {
   1002             throw e.rethrowFromSystemServer();
   1003         }
   1004     }
   1005 
   1006     /**
   1007      * Set the current power save mode.
   1008      *
   1009      * @return True if the set was allowed.
   1010      *
   1011      * @see #isPowerSaveMode()
   1012      *
   1013      * @hide
   1014      */
   1015     public boolean setPowerSaveMode(boolean mode) {
   1016         try {
   1017             return mService.setPowerSaveMode(mode);
   1018         } catch (RemoteException e) {
   1019             throw e.rethrowFromSystemServer();
   1020         }
   1021     }
   1022 
   1023     /**
   1024      * Get data about the battery saver mode for a specific service
   1025      * @param serviceType unique key for the service, one of
   1026      *             {@link com.android.server.power.BatterySaverPolicy.ServiceType}
   1027      * @return Battery saver state data.
   1028      *
   1029      * @hide
   1030      * @see com.android.server.power.BatterySaverPolicy
   1031      * @see PowerSaveState
   1032      */
   1033     public PowerSaveState getPowerSaveState(int serviceType) {
   1034         try {
   1035             return mService.getPowerSaveState(serviceType);
   1036         } catch (RemoteException e) {
   1037             throw e.rethrowFromSystemServer();
   1038         }
   1039     }
   1040 
   1041     /**
   1042      * Returns true if the device is currently in idle mode.  This happens when a device
   1043      * has been sitting unused and unmoving for a sufficiently long period of time, so that
   1044      * it decides to go into a lower power-use state.  This may involve things like turning
   1045      * off network access to apps.  You can monitor for changes to this state with
   1046      * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
   1047      *
   1048      * @return Returns true if currently in active device idle mode, else false.  This is
   1049      * when idle mode restrictions are being actively applied; it will return false if the
   1050      * device is in a long-term idle mode but currently running a maintenance window where
   1051      * restrictions have been lifted.
   1052      */
   1053     public boolean isDeviceIdleMode() {
   1054         try {
   1055             return mService.isDeviceIdleMode();
   1056         } catch (RemoteException e) {
   1057             throw e.rethrowFromSystemServer();
   1058         }
   1059     }
   1060 
   1061     /**
   1062      * Returns true if the device is currently in light idle mode.  This happens when a device
   1063      * has had its screen off for a short time, switching it into a batching mode where we
   1064      * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
   1065      * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
   1066      *
   1067      * @return Returns true if currently in active light device idle mode, else false.  This is
   1068      * when light idle mode restrictions are being actively applied; it will return false if the
   1069      * device is in a long-term idle mode but currently running a maintenance window where
   1070      * restrictions have been lifted.
   1071      * @hide
   1072      */
   1073     public boolean isLightDeviceIdleMode() {
   1074         try {
   1075             return mService.isLightDeviceIdleMode();
   1076         } catch (RemoteException e) {
   1077             throw e.rethrowFromSystemServer();
   1078         }
   1079     }
   1080 
   1081     /**
   1082      * Return whether the given application package name is on the device's power whitelist.
   1083      * Apps can be placed on the whitelist through the settings UI invoked by
   1084      * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
   1085      */
   1086     public boolean isIgnoringBatteryOptimizations(String packageName) {
   1087         synchronized (this) {
   1088             if (mIDeviceIdleController == null) {
   1089                 mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
   1090                         ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
   1091             }
   1092         }
   1093         try {
   1094             return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
   1095         } catch (RemoteException e) {
   1096             throw e.rethrowFromSystemServer();
   1097         }
   1098     }
   1099 
   1100     /**
   1101      * Turn off the device.
   1102      *
   1103      * @param confirm If true, shows a shutdown confirmation dialog.
   1104      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
   1105      * @param wait If true, this call waits for the shutdown to complete and does not return.
   1106      *
   1107      * @hide
   1108      */
   1109     public void shutdown(boolean confirm, String reason, boolean wait) {
   1110         try {
   1111             mService.shutdown(confirm, reason, wait);
   1112         } catch (RemoteException e) {
   1113             throw e.rethrowFromSystemServer();
   1114         }
   1115     }
   1116 
   1117     /**
   1118      * This function checks if the device has implemented Sustained Performance
   1119      * Mode. This needs to be checked only once and is constant for a particular
   1120      * device/release.
   1121      *
   1122      * Sustained Performance Mode is intended to provide a consistent level of
   1123      * performance for prolonged amount of time.
   1124      *
   1125      * Applications should check if the device supports this mode, before using
   1126      * {@link android.view.Window#setSustainedPerformanceMode}.
   1127      *
   1128      * @return Returns True if the device supports it, false otherwise.
   1129      *
   1130      * @see android.view.Window#setSustainedPerformanceMode
   1131      */
   1132     public boolean isSustainedPerformanceModeSupported() {
   1133         return mContext.getResources().getBoolean(
   1134                 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
   1135     }
   1136 
   1137     /**
   1138      * Returns the reason the phone was last shutdown. Calling app must have the
   1139      * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information.
   1140      * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could
   1141      * not be accessed.
   1142      * @hide
   1143      */
   1144     @ShutdownReason
   1145     public int getLastShutdownReason() {
   1146         try {
   1147             return mService.getLastShutdownReason();
   1148         } catch (RemoteException e) {
   1149             throw e.rethrowFromSystemServer();
   1150         }
   1151     }
   1152 
   1153     /**
   1154      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
   1155      * This broadcast is only sent to registered receivers.
   1156      */
   1157     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1158     public static final String ACTION_POWER_SAVE_MODE_CHANGED
   1159             = "android.os.action.POWER_SAVE_MODE_CHANGED";
   1160 
   1161     /**
   1162      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
   1163      * @hide
   1164      */
   1165     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1166     public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
   1167             = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
   1168 
   1169     /**
   1170      * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
   1171      * This broadcast is only sent to registered receivers.
   1172      */
   1173     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1174     public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
   1175             = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
   1176 
   1177     /**
   1178      * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
   1179      * This broadcast is only sent to registered receivers.
   1180      * @hide
   1181      */
   1182     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1183     public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
   1184             = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
   1185 
   1186     /**
   1187      * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
   1188      * This broadcast is only sent to registered receivers.
   1189      */
   1190     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1191     public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
   1192             = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
   1193 
   1194     /**
   1195      * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
   1196      * This broadcast is only sent to registered receivers.
   1197      */
   1198     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1199     public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
   1200             = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
   1201 
   1202     /**
   1203      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
   1204      * This broadcast is only sent to registered receivers.
   1205      *
   1206      * @hide
   1207      */
   1208     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
   1209     public static final String ACTION_POWER_SAVE_MODE_CHANGING
   1210             = "android.os.action.POWER_SAVE_MODE_CHANGING";
   1211 
   1212     /** @hide */
   1213     public static final String EXTRA_POWER_SAVE_MODE = "mode";
   1214 
   1215     /**
   1216      * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
   1217      * This broadcast is only sent to registered receivers.
   1218      *
   1219      * @hide
   1220      **/
   1221     @SystemApi
   1222     public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
   1223             = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
   1224 
   1225     /**
   1226      * A wake lock is a mechanism to indicate that your application needs
   1227      * to have the device stay on.
   1228      * <p>
   1229      * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
   1230      * permission in an {@code <uses-permission>} element of the application's manifest.
   1231      * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
   1232      * </p><p>
   1233      * Call {@link #acquire()} to acquire the wake lock and force the device to stay
   1234      * on at the level that was requested when the wake lock was created.
   1235      * </p><p>
   1236      * Call {@link #release()} when you are done and don't need the lock anymore.
   1237      * It is very important to do this as soon as possible to avoid running down the
   1238      * device's battery excessively.
   1239      * </p>
   1240      */
   1241     public final class WakeLock {
   1242         private int mFlags;
   1243         private String mTag;
   1244         private final String mPackageName;
   1245         private final IBinder mToken;
   1246         private int mCount;
   1247         private boolean mRefCounted = true;
   1248         private boolean mHeld;
   1249         private WorkSource mWorkSource;
   1250         private String mHistoryTag;
   1251         private final String mTraceName;
   1252 
   1253         private final Runnable mReleaser = new Runnable() {
   1254             public void run() {
   1255                 release();
   1256             }
   1257         };
   1258 
   1259         WakeLock(int flags, String tag, String packageName) {
   1260             mFlags = flags;
   1261             mTag = tag;
   1262             mPackageName = packageName;
   1263             mToken = new Binder();
   1264             mTraceName = "WakeLock (" + mTag + ")";
   1265         }
   1266 
   1267         @Override
   1268         protected void finalize() throws Throwable {
   1269             synchronized (mToken) {
   1270                 if (mHeld) {
   1271                     Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
   1272                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
   1273                     try {
   1274                         mService.releaseWakeLock(mToken, 0);
   1275                     } catch (RemoteException e) {
   1276                         throw e.rethrowFromSystemServer();
   1277                     }
   1278                 }
   1279             }
   1280         }
   1281 
   1282         /**
   1283          * Sets whether this WakeLock is reference counted.
   1284          * <p>
   1285          * Wake locks are reference counted by default.  If a wake lock is
   1286          * reference counted, then each call to {@link #acquire()} must be
   1287          * balanced by an equal number of calls to {@link #release()}.  If a wake
   1288          * lock is not reference counted, then one call to {@link #release()} is
   1289          * sufficient to undo the effect of all previous calls to {@link #acquire()}.
   1290          * </p>
   1291          *
   1292          * @param value True to make the wake lock reference counted, false to
   1293          * make the wake lock non-reference counted.
   1294          */
   1295         public void setReferenceCounted(boolean value) {
   1296             synchronized (mToken) {
   1297                 mRefCounted = value;
   1298             }
   1299         }
   1300 
   1301         /**
   1302          * Acquires the wake lock.
   1303          * <p>
   1304          * Ensures that the device is on at the level requested when
   1305          * the wake lock was created.
   1306          * </p>
   1307          */
   1308         public void acquire() {
   1309             synchronized (mToken) {
   1310                 acquireLocked();
   1311             }
   1312         }
   1313 
   1314         /**
   1315          * Acquires the wake lock with a timeout.
   1316          * <p>
   1317          * Ensures that the device is on at the level requested when
   1318          * the wake lock was created.  The lock will be released after the given timeout
   1319          * expires.
   1320          * </p>
   1321          *
   1322          * @param timeout The timeout after which to release the wake lock, in milliseconds.
   1323          */
   1324         public void acquire(long timeout) {
   1325             synchronized (mToken) {
   1326                 acquireLocked();
   1327                 mHandler.postDelayed(mReleaser, timeout);
   1328             }
   1329         }
   1330 
   1331         private void acquireLocked() {
   1332             if (!mRefCounted || mCount++ == 0) {
   1333                 // Do this even if the wake lock is already thought to be held (mHeld == true)
   1334                 // because non-reference counted wake locks are not always properly released.
   1335                 // For example, the keyguard's wake lock might be forcibly released by the
   1336                 // power manager without the keyguard knowing.  A subsequent call to acquire
   1337                 // should immediately acquire the wake lock once again despite never having
   1338                 // been explicitly released by the keyguard.
   1339                 mHandler.removeCallbacks(mReleaser);
   1340                 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
   1341                 try {
   1342                     mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
   1343                             mHistoryTag);
   1344                 } catch (RemoteException e) {
   1345                     throw e.rethrowFromSystemServer();
   1346                 }
   1347                 mHeld = true;
   1348             }
   1349         }
   1350 
   1351         /**
   1352          * Releases the wake lock.
   1353          * <p>
   1354          * This method releases your claim to the CPU or screen being on.
   1355          * The screen may turn off shortly after you release the wake lock, or it may
   1356          * not if there are other wake locks still held.
   1357          * </p>
   1358          */
   1359         public void release() {
   1360             release(0);
   1361         }
   1362 
   1363         /**
   1364          * Releases the wake lock with flags to modify the release behavior.
   1365          * <p>
   1366          * This method releases your claim to the CPU or screen being on.
   1367          * The screen may turn off shortly after you release the wake lock, or it may
   1368          * not if there are other wake locks still held.
   1369          * </p>
   1370          *
   1371          * @param flags Combination of flag values to modify the release behavior.
   1372          * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
   1373          * Passing 0 is equivalent to calling {@link #release()}.
   1374          */
   1375         public void release(int flags) {
   1376             synchronized (mToken) {
   1377                 if (!mRefCounted || --mCount == 0) {
   1378                     mHandler.removeCallbacks(mReleaser);
   1379                     if (mHeld) {
   1380                         Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
   1381                         try {
   1382                             mService.releaseWakeLock(mToken, flags);
   1383                         } catch (RemoteException e) {
   1384                             throw e.rethrowFromSystemServer();
   1385                         }
   1386                         mHeld = false;
   1387                     }
   1388                 }
   1389                 if (mCount < 0) {
   1390                     throw new RuntimeException("WakeLock under-locked " + mTag);
   1391                 }
   1392             }
   1393         }
   1394 
   1395         /**
   1396          * Returns true if the wake lock has been acquired but not yet released.
   1397          *
   1398          * @return True if the wake lock is held.
   1399          */
   1400         public boolean isHeld() {
   1401             synchronized (mToken) {
   1402                 return mHeld;
   1403             }
   1404         }
   1405 
   1406         /**
   1407          * Sets the work source associated with the wake lock.
   1408          * <p>
   1409          * The work source is used to determine on behalf of which application
   1410          * the wake lock is being held.  This is useful in the case where a
   1411          * service is performing work on behalf of an application so that the
   1412          * cost of that work can be accounted to the application.
   1413          * </p>
   1414          *
   1415          * @param ws The work source, or null if none.
   1416          */
   1417         public void setWorkSource(WorkSource ws) {
   1418             synchronized (mToken) {
   1419                 if (ws != null && ws.size() == 0) {
   1420                     ws = null;
   1421                 }
   1422 
   1423                 final boolean changed;
   1424                 if (ws == null) {
   1425                     changed = mWorkSource != null;
   1426                     mWorkSource = null;
   1427                 } else if (mWorkSource == null) {
   1428                     changed = true;
   1429                     mWorkSource = new WorkSource(ws);
   1430                 } else {
   1431                     changed = mWorkSource.diff(ws);
   1432                     if (changed) {
   1433                         mWorkSource.set(ws);
   1434                     }
   1435                 }
   1436 
   1437                 if (changed && mHeld) {
   1438                     try {
   1439                         mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
   1440                     } catch (RemoteException e) {
   1441                         throw e.rethrowFromSystemServer();
   1442                     }
   1443                 }
   1444             }
   1445         }
   1446 
   1447         /** @hide */
   1448         public void setTag(String tag) {
   1449             mTag = tag;
   1450         }
   1451 
   1452         /** @hide */
   1453         public String getTag() {
   1454             return mTag;
   1455         }
   1456 
   1457         /** @hide */
   1458         public void setHistoryTag(String tag) {
   1459             mHistoryTag = tag;
   1460         }
   1461 
   1462         /** @hide */
   1463         public void setUnimportantForLogging(boolean state) {
   1464             if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
   1465             else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
   1466         }
   1467 
   1468         @Override
   1469         public String toString() {
   1470             synchronized (mToken) {
   1471                 return "WakeLock{"
   1472                     + Integer.toHexString(System.identityHashCode(this))
   1473                     + " held=" + mHeld + ", refCount=" + mCount + "}";
   1474             }
   1475         }
   1476 
   1477         /**
   1478          * Wraps a Runnable such that this method immediately acquires the wake lock and then
   1479          * once the Runnable is done the wake lock is released.
   1480          *
   1481          * <p>Example:
   1482          *
   1483          * <pre>
   1484          * mHandler.post(mWakeLock.wrap(() -> {
   1485          *     // do things on handler, lock is held while we're waiting for this
   1486          *     // to get scheduled and until the runnable is done executing.
   1487          * });
   1488          * </pre>
   1489          *
   1490          * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
   1491          *    leak the wakelock!
   1492          *
   1493          * @hide
   1494          */
   1495         public Runnable wrap(Runnable r) {
   1496             acquire();
   1497             return () -> {
   1498                 try {
   1499                     r.run();
   1500                 } finally {
   1501                     release();
   1502                 }
   1503             };
   1504         }
   1505     }
   1506 }
   1507