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