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