• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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      */
PowerManager(Context context, IPowerManager service, Handler handler)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      */
getMinimumScreenBrightnessSetting()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      */
getMaximumScreenBrightnessSetting()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      */
getDefaultScreenBrightnessSetting()470     public int getDefaultScreenBrightnessSetting() {
471         return mContext.getResources().getInteger(
472                 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
473     }
474 
475     /**
476      * Gets the minimum supported screen brightness setting for VR Mode.
477      * @hide
478      */
getMinimumScreenBrightnessForVrSetting()479     public int getMinimumScreenBrightnessForVrSetting() {
480         return mContext.getResources().getInteger(
481                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum);
482     }
483 
484     /**
485      * Gets the maximum supported screen brightness setting for VR Mode.
486      * The screen may be allowed to become dimmer than this value but
487      * this is the maximum value that can be set by the user.
488      * @hide
489      */
getMaximumScreenBrightnessForVrSetting()490     public int getMaximumScreenBrightnessForVrSetting() {
491         return mContext.getResources().getInteger(
492                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum);
493     }
494 
495     /**
496      * Gets the default screen brightness for VR setting.
497      * @hide
498      */
getDefaultScreenBrightnessForVrSetting()499     public int getDefaultScreenBrightnessForVrSetting() {
500         return mContext.getResources().getInteger(
501                 com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
502     }
503 
504     /**
505      * Creates a new wake lock with the specified level and flags.
506      * <p>
507      * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
508      * combined using the logical OR operator.
509      * </p><p>
510      * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
511      * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
512      * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
513      * specified as part of the {@code levelAndFlags} parameter.
514      * </p><p>
515      * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
516      * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
517      * {@code levelAndFlags} parameters.
518      * </p><p>
519      * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
520      * wake lock, and {@link WakeLock#release release()} when you are done.
521      * </p><p>
522      * {@samplecode
523      * PowerManager pm = (PowerManager)mContext.getSystemService(
524      *                                          Context.POWER_SERVICE);
525      * PowerManager.WakeLock wl = pm.newWakeLock(
526      *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
527      *                                      | PowerManager.ON_AFTER_RELEASE,
528      *                                      TAG);
529      * wl.acquire();
530      * // ... do work...
531      * wl.release();
532      * }
533      * </p><p>
534      * Although a wake lock can be created without special permissions,
535      * the {@link android.Manifest.permission#WAKE_LOCK} permission is
536      * required to actually acquire or release the wake lock that is returned.
537      * </p><p class="note">
538      * If using this to keep the screen on, you should strongly consider using
539      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
540      * This window flag will be correctly managed by the platform
541      * as the user moves between applications and doesn't require a special permission.
542      * </p>
543      *
544      * @param levelAndFlags Combination of wake lock level and flag values defining
545      * the requested behavior of the WakeLock.
546      * @param tag Your class name (or other tag) for debugging purposes.
547      *
548      * @see WakeLock#acquire()
549      * @see WakeLock#release()
550      * @see #PARTIAL_WAKE_LOCK
551      * @see #FULL_WAKE_LOCK
552      * @see #SCREEN_DIM_WAKE_LOCK
553      * @see #SCREEN_BRIGHT_WAKE_LOCK
554      * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
555      * @see #ACQUIRE_CAUSES_WAKEUP
556      * @see #ON_AFTER_RELEASE
557      */
newWakeLock(int levelAndFlags, String tag)558     public WakeLock newWakeLock(int levelAndFlags, String tag) {
559         validateWakeLockParameters(levelAndFlags, tag);
560         return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
561     }
562 
563     /** @hide */
validateWakeLockParameters(int levelAndFlags, String tag)564     public static void validateWakeLockParameters(int levelAndFlags, String tag) {
565         switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
566             case PARTIAL_WAKE_LOCK:
567             case SCREEN_DIM_WAKE_LOCK:
568             case SCREEN_BRIGHT_WAKE_LOCK:
569             case FULL_WAKE_LOCK:
570             case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
571             case DOZE_WAKE_LOCK:
572             case DRAW_WAKE_LOCK:
573                 break;
574             default:
575                 throw new IllegalArgumentException("Must specify a valid wake lock level.");
576         }
577         if (tag == null) {
578             throw new IllegalArgumentException("The tag must not be null.");
579         }
580     }
581 
582     /**
583      * Notifies the power manager that user activity happened.
584      * <p>
585      * Resets the auto-off timer and brightens the screen if the device
586      * is not asleep.  This is what happens normally when a key or the touch
587      * screen is pressed or when some other user activity occurs.
588      * This method does not wake up the device if it has been put to sleep.
589      * </p><p>
590      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
591      * </p>
592      *
593      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
594      * time base.  This timestamp is used to correctly order the user activity request with
595      * other power management functions.  It should be set
596      * to the timestamp of the input event that caused the user activity.
597      * @param noChangeLights If true, does not cause the keyboard backlight to turn on
598      * because of this event.  This is set when the power key is pressed.
599      * We want the device to stay on while the button is down, but we're about
600      * to turn off the screen so we don't want the keyboard backlight to turn on again.
601      * Otherwise the lights flash on and then off and it looks weird.
602      *
603      * @see #wakeUp
604      * @see #goToSleep
605      *
606      * @removed Requires signature or system permission.
607      * @deprecated Use {@link #userActivity(long, int, int)}.
608      */
609     @Deprecated
userActivity(long when, boolean noChangeLights)610     public void userActivity(long when, boolean noChangeLights) {
611         userActivity(when, USER_ACTIVITY_EVENT_OTHER,
612                 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
613     }
614 
615     /**
616      * Notifies the power manager that user activity happened.
617      * <p>
618      * Resets the auto-off timer and brightens the screen if the device
619      * is not asleep.  This is what happens normally when a key or the touch
620      * screen is pressed or when some other user activity occurs.
621      * This method does not wake up the device if it has been put to sleep.
622      * </p><p>
623      * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
624      * {@link android.Manifest.permission#USER_ACTIVITY} permission.
625      * </p>
626      *
627      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
628      * time base.  This timestamp is used to correctly order the user activity request with
629      * other power management functions.  It should be set
630      * to the timestamp of the input event that caused the user activity.
631      * @param event The user activity event.
632      * @param flags Optional user activity flags.
633      *
634      * @see #wakeUp
635      * @see #goToSleep
636      *
637      * @hide Requires signature or system permission.
638      */
639     @SystemApi
userActivity(long when, int event, int flags)640     public void userActivity(long when, int event, int flags) {
641         try {
642             mService.userActivity(when, event, flags);
643         } catch (RemoteException e) {
644             throw e.rethrowFromSystemServer();
645         }
646     }
647 
648    /**
649      * Forces the device to go to sleep.
650      * <p>
651      * Overrides all the wake locks that are held.
652      * This is what happens when the power key is pressed to turn off the screen.
653      * </p><p>
654      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
655      * </p>
656      *
657      * @param time The time when the request to go to sleep was issued, in the
658      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
659      * order the go to sleep request with other power management functions.  It should be set
660      * to the timestamp of the input event that caused the request to go to sleep.
661      *
662      * @see #userActivity
663      * @see #wakeUp
664      *
665      * @removed Requires signature permission.
666      */
goToSleep(long time)667     public void goToSleep(long time) {
668         goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
669     }
670 
671     /**
672      * Forces the device to go to sleep.
673      * <p>
674      * Overrides all the wake locks that are held.
675      * This is what happens when the power key is pressed to turn off the screen.
676      * </p><p>
677      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
678      * </p>
679      *
680      * @param time The time when the request to go to sleep was issued, in the
681      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
682      * order the go to sleep request with other power management functions.  It should be set
683      * to the timestamp of the input event that caused the request to go to sleep.
684      * @param reason The reason the device is going to sleep.
685      * @param flags Optional flags to apply when going to sleep.
686      *
687      * @see #userActivity
688      * @see #wakeUp
689      *
690      * @hide Requires signature permission.
691      */
goToSleep(long time, int reason, int flags)692     public void goToSleep(long time, int reason, int flags) {
693         try {
694             mService.goToSleep(time, reason, flags);
695         } catch (RemoteException e) {
696             throw e.rethrowFromSystemServer();
697         }
698     }
699 
700     /**
701      * Forces the device to wake up from sleep.
702      * <p>
703      * If the device is currently asleep, wakes it up, otherwise does nothing.
704      * This is what happens when the power key is pressed to turn on the screen.
705      * </p><p>
706      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
707      * </p>
708      *
709      * @param time The time when the request to wake up was issued, in the
710      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
711      * order the wake up request with other power management functions.  It should be set
712      * to the timestamp of the input event that caused the request to wake up.
713      *
714      * @see #userActivity
715      * @see #goToSleep
716      *
717      * @removed Requires signature permission.
718      */
wakeUp(long time)719     public void wakeUp(long time) {
720         try {
721             mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
722         } catch (RemoteException e) {
723             throw e.rethrowFromSystemServer();
724         }
725     }
726 
727     /**
728      * @hide
729      */
wakeUp(long time, String reason)730     public void wakeUp(long time, String reason) {
731         try {
732             mService.wakeUp(time, reason, mContext.getOpPackageName());
733         } catch (RemoteException e) {
734             throw e.rethrowFromSystemServer();
735         }
736     }
737 
738     /**
739      * Forces the device to start napping.
740      * <p>
741      * If the device is currently awake, starts dreaming, otherwise does nothing.
742      * When the dream ends or if the dream cannot be started, the device will
743      * either wake up or go to sleep depending on whether there has been recent
744      * user activity.
745      * </p><p>
746      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
747      * </p>
748      *
749      * @param time The time when the request to nap was issued, in the
750      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
751      * order the nap request with other power management functions.  It should be set
752      * to the timestamp of the input event that caused the request to nap.
753      *
754      * @see #wakeUp
755      * @see #goToSleep
756      *
757      * @hide Requires signature permission.
758      */
nap(long time)759     public void nap(long time) {
760         try {
761             mService.nap(time);
762         } catch (RemoteException e) {
763             throw e.rethrowFromSystemServer();
764         }
765     }
766 
767     /**
768      * Boosts the brightness of the screen to maximum for a predetermined
769      * period of time.  This is used to make the screen more readable in bright
770      * daylight for a short duration.
771      * <p>
772      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
773      * </p>
774      *
775      * @param time The time when the request to boost was issued, in the
776      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
777      * order the boost request with other power management functions.  It should be set
778      * to the timestamp of the input event that caused the request to boost.
779      *
780      * @hide Requires signature permission.
781      */
boostScreenBrightness(long time)782     public void boostScreenBrightness(long time) {
783         try {
784             mService.boostScreenBrightness(time);
785         } catch (RemoteException e) {
786             throw e.rethrowFromSystemServer();
787         }
788     }
789 
790     /**
791      * Returns whether the screen brightness is currently boosted to maximum, caused by a call
792      * to {@link #boostScreenBrightness(long)}.
793      * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
794      *
795      * @hide
796      */
797     @SystemApi
isScreenBrightnessBoosted()798     public boolean isScreenBrightnessBoosted() {
799         try {
800             return mService.isScreenBrightnessBoosted();
801         } catch (RemoteException e) {
802             throw e.rethrowFromSystemServer();
803         }
804     }
805 
806     /**
807      * Sets the brightness of the backlights (screen, keyboard, button).
808      * <p>
809      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
810      * </p>
811      *
812      * @param brightness The brightness value from 0 to 255.
813      *
814      * @hide Requires signature permission.
815      */
setBacklightBrightness(int brightness)816     public void setBacklightBrightness(int brightness) {
817         try {
818             mService.setTemporaryScreenBrightnessSettingOverride(brightness);
819         } catch (RemoteException e) {
820             throw e.rethrowFromSystemServer();
821         }
822     }
823 
824    /**
825      * Returns true if the specified wake lock level is supported.
826      *
827      * @param level The wake lock level to check.
828      * @return True if the specified wake lock level is supported.
829      */
isWakeLockLevelSupported(int level)830     public boolean isWakeLockLevelSupported(int level) {
831         try {
832             return mService.isWakeLockLevelSupported(level);
833         } catch (RemoteException e) {
834             throw e.rethrowFromSystemServer();
835         }
836     }
837 
838     /**
839       * Returns true if the device is in an interactive state.
840       * <p>
841       * For historical reasons, the name of this method refers to the power state of
842       * the screen but it actually describes the overall interactive state of
843       * the device.  This method has been replaced by {@link #isInteractive}.
844       * </p><p>
845       * The value returned by this method only indicates whether the device is
846       * in an interactive state which may have nothing to do with the screen being
847       * on or off.  To determine the actual state of the screen,
848       * use {@link android.view.Display#getState}.
849       * </p>
850       *
851       * @return True if the device is in an interactive state.
852       *
853       * @deprecated Use {@link #isInteractive} instead.
854       */
855     @Deprecated
isScreenOn()856     public boolean isScreenOn() {
857         return isInteractive();
858     }
859 
860     /**
861      * Returns true if the device is in an interactive state.
862      * <p>
863      * When this method returns true, the device is awake and ready to interact
864      * with the user (although this is not a guarantee that the user is actively
865      * interacting with the device just this moment).  The main screen is usually
866      * turned on while in this state.  Certain features, such as the proximity
867      * sensor, may temporarily turn off the screen while still leaving the device in an
868      * interactive state.  Note in particular that the device is still considered
869      * to be interactive while dreaming (since dreams can be interactive) but not
870      * when it is dozing or asleep.
871      * </p><p>
872      * When this method returns false, the device is dozing or asleep and must
873      * be awoken before it will become ready to interact with the user again.  The
874      * main screen is usually turned off while in this state.  Certain features,
875      * such as "ambient mode" may cause the main screen to remain on (albeit in a
876      * low power state) to display system-provided content while the device dozes.
877      * </p><p>
878      * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
879      * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
880      * whenever the interactive state of the device changes.  For historical reasons,
881      * the names of these broadcasts refer to the power state of the screen
882      * but they are actually sent in response to changes in the overall interactive
883      * state of the device, as described by this method.
884      * </p><p>
885      * Services may use the non-interactive state as a hint to conserve power
886      * since the user is not present.
887      * </p>
888      *
889      * @return True if the device is in an interactive state.
890      *
891      * @see android.content.Intent#ACTION_SCREEN_ON
892      * @see android.content.Intent#ACTION_SCREEN_OFF
893      */
isInteractive()894     public boolean isInteractive() {
895         try {
896             return mService.isInteractive();
897         } catch (RemoteException e) {
898             throw e.rethrowFromSystemServer();
899         }
900     }
901 
902     /**
903      * Reboot the device.  Will not return if the reboot is successful.
904      * <p>
905      * Requires the {@link android.Manifest.permission#REBOOT} permission.
906      * </p>
907      *
908      * @param reason code to pass to the kernel (e.g., "recovery") to
909      *               request special boot modes, or null.
910      */
reboot(String reason)911     public void reboot(String reason) {
912         try {
913             mService.reboot(false, reason, true);
914         } catch (RemoteException e) {
915             throw e.rethrowFromSystemServer();
916         }
917     }
918 
919     /**
920      * Reboot the device. Will not return if the reboot is successful.
921      * <p>
922      * Requires the {@link android.Manifest.permission#REBOOT} permission.
923      * </p>
924      * @hide
925      */
rebootSafeMode()926     public void rebootSafeMode() {
927         try {
928             mService.rebootSafeMode(false, true);
929         } catch (RemoteException e) {
930             throw e.rethrowFromSystemServer();
931         }
932     }
933 
934     /**
935      * Returns true if the device is currently in power save mode.  When in this mode,
936      * applications should reduce their functionality in order to conserve battery as
937      * much as possible.  You can monitor for changes to this state with
938      * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
939      *
940      * @return Returns true if currently in low power mode, else false.
941      */
isPowerSaveMode()942     public boolean isPowerSaveMode() {
943         try {
944             return mService.isPowerSaveMode();
945         } catch (RemoteException e) {
946             throw e.rethrowFromSystemServer();
947         }
948     }
949 
950     /**
951      * Set the current power save mode.
952      *
953      * @return True if the set was allowed.
954      *
955      * @see #isPowerSaveMode()
956      *
957      * @hide
958      */
setPowerSaveMode(boolean mode)959     public boolean setPowerSaveMode(boolean mode) {
960         try {
961             return mService.setPowerSaveMode(mode);
962         } catch (RemoteException e) {
963             throw e.rethrowFromSystemServer();
964         }
965     }
966 
967     /**
968      * Returns true if the device is currently in idle mode.  This happens when a device
969      * has been sitting unused and unmoving for a sufficiently long period of time, so that
970      * it decides to go into a lower power-use state.  This may involve things like turning
971      * off network access to apps.  You can monitor for changes to this state with
972      * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
973      *
974      * @return Returns true if currently in active device idle mode, else false.  This is
975      * when idle mode restrictions are being actively applied; it will return false if the
976      * device is in a long-term idle mode but currently running a maintenance window where
977      * restrictions have been lifted.
978      */
isDeviceIdleMode()979     public boolean isDeviceIdleMode() {
980         try {
981             return mService.isDeviceIdleMode();
982         } catch (RemoteException e) {
983             throw e.rethrowFromSystemServer();
984         }
985     }
986 
987     /**
988      * Returns true if the device is currently in light idle mode.  This happens when a device
989      * has had its screen off for a short time, switching it into a batching mode where we
990      * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
991      * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
992      *
993      * @return Returns true if currently in active light device idle mode, else false.  This is
994      * when light idle mode restrictions are being actively applied; it will return false if the
995      * device is in a long-term idle mode but currently running a maintenance window where
996      * restrictions have been lifted.
997      * @hide
998      */
isLightDeviceIdleMode()999     public boolean isLightDeviceIdleMode() {
1000         try {
1001             return mService.isLightDeviceIdleMode();
1002         } catch (RemoteException e) {
1003             throw e.rethrowFromSystemServer();
1004         }
1005     }
1006 
1007     /**
1008      * Return whether the given application package name is on the device's power whitelist.
1009      * Apps can be placed on the whitelist through the settings UI invoked by
1010      * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
1011      */
isIgnoringBatteryOptimizations(String packageName)1012     public boolean isIgnoringBatteryOptimizations(String packageName) {
1013         synchronized (this) {
1014             if (mIDeviceIdleController == null) {
1015                 mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
1016                         ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
1017             }
1018         }
1019         try {
1020             return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
1021         } catch (RemoteException e) {
1022             throw e.rethrowFromSystemServer();
1023         }
1024     }
1025 
1026     /**
1027      * Turn off the device.
1028      *
1029      * @param confirm If true, shows a shutdown confirmation dialog.
1030      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
1031      * @param wait If true, this call waits for the shutdown to complete and does not return.
1032      *
1033      * @hide
1034      */
shutdown(boolean confirm, String reason, boolean wait)1035     public void shutdown(boolean confirm, String reason, boolean wait) {
1036         try {
1037             mService.shutdown(confirm, reason, wait);
1038         } catch (RemoteException e) {
1039             throw e.rethrowFromSystemServer();
1040         }
1041     }
1042 
1043     /**
1044      * This function checks if the device has implemented Sustained Performance
1045      * Mode. This needs to be checked only once and is constant for a particular
1046      * device/release.
1047      *
1048      * Sustained Performance Mode is intended to provide a consistent level of
1049      * performance for prolonged amount of time.
1050      *
1051      * Applications should check if the device supports this mode, before using
1052      * {@link android.view.Window#setSustainedPerformanceMode}.
1053      *
1054      * @return Returns True if the device supports it, false otherwise.
1055      *
1056      * @see android.view.Window#setSustainedPerformanceMode
1057      */
isSustainedPerformanceModeSupported()1058     public boolean isSustainedPerformanceModeSupported() {
1059         return mContext.getResources().getBoolean(
1060                 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
1061     }
1062 
1063     /**
1064      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1065      * This broadcast is only sent to registered receivers.
1066      */
1067     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1068     public static final String ACTION_POWER_SAVE_MODE_CHANGED
1069             = "android.os.action.POWER_SAVE_MODE_CHANGED";
1070 
1071     /**
1072      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1073      * @hide
1074      */
1075     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1076     public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
1077             = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
1078 
1079     /**
1080      * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1081      * This broadcast is only sent to registered receivers.
1082      */
1083     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1084     public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
1085             = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
1086 
1087     /**
1088      * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1089      * This broadcast is only sent to registered receivers.
1090      * @hide
1091      */
1092     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1093     public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
1094             = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
1095 
1096     /**
1097      * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
1098      * This broadcast is only sent to registered receivers.
1099      */
1100     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1101     public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
1102             = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
1103 
1104     /**
1105      * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1106      * This broadcast is only sent to registered receivers.
1107      */
1108     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1109     public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
1110             = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
1111 
1112     /**
1113      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
1114      * This broadcast is only sent to registered receivers.
1115      *
1116      * @hide
1117      */
1118     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1119     public static final String ACTION_POWER_SAVE_MODE_CHANGING
1120             = "android.os.action.POWER_SAVE_MODE_CHANGING";
1121 
1122     /** @hide */
1123     public static final String EXTRA_POWER_SAVE_MODE = "mode";
1124 
1125     /**
1126      * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
1127      * This broadcast is only sent to registered receivers.
1128      *
1129      * @hide
1130      **/
1131     @SystemApi
1132     public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
1133             = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
1134 
1135     /**
1136      * A wake lock is a mechanism to indicate that your application needs
1137      * to have the device stay on.
1138      * <p>
1139      * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
1140      * permission in an {@code <uses-permission>} element of the application's manifest.
1141      * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
1142      * </p><p>
1143      * Call {@link #acquire()} to acquire the wake lock and force the device to stay
1144      * on at the level that was requested when the wake lock was created.
1145      * </p><p>
1146      * Call {@link #release()} when you are done and don't need the lock anymore.
1147      * It is very important to do this as soon as possible to avoid running down the
1148      * device's battery excessively.
1149      * </p>
1150      */
1151     public final class WakeLock {
1152         private int mFlags;
1153         private String mTag;
1154         private final String mPackageName;
1155         private final IBinder mToken;
1156         private int mCount;
1157         private boolean mRefCounted = true;
1158         private boolean mHeld;
1159         private WorkSource mWorkSource;
1160         private String mHistoryTag;
1161         private final String mTraceName;
1162 
1163         private final Runnable mReleaser = new Runnable() {
1164             public void run() {
1165                 release();
1166             }
1167         };
1168 
WakeLock(int flags, String tag, String packageName)1169         WakeLock(int flags, String tag, String packageName) {
1170             mFlags = flags;
1171             mTag = tag;
1172             mPackageName = packageName;
1173             mToken = new Binder();
1174             mTraceName = "WakeLock (" + mTag + ")";
1175         }
1176 
1177         @Override
finalize()1178         protected void finalize() throws Throwable {
1179             synchronized (mToken) {
1180                 if (mHeld) {
1181                     Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
1182                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1183                     try {
1184                         mService.releaseWakeLock(mToken, 0);
1185                     } catch (RemoteException e) {
1186                         throw e.rethrowFromSystemServer();
1187                     }
1188                 }
1189             }
1190         }
1191 
1192         /**
1193          * Sets whether this WakeLock is reference counted.
1194          * <p>
1195          * Wake locks are reference counted by default.  If a wake lock is
1196          * reference counted, then each call to {@link #acquire()} must be
1197          * balanced by an equal number of calls to {@link #release()}.  If a wake
1198          * lock is not reference counted, then one call to {@link #release()} is
1199          * sufficient to undo the effect of all previous calls to {@link #acquire()}.
1200          * </p>
1201          *
1202          * @param value True to make the wake lock reference counted, false to
1203          * make the wake lock non-reference counted.
1204          */
setReferenceCounted(boolean value)1205         public void setReferenceCounted(boolean value) {
1206             synchronized (mToken) {
1207                 mRefCounted = value;
1208             }
1209         }
1210 
1211         /**
1212          * Acquires the wake lock.
1213          * <p>
1214          * Ensures that the device is on at the level requested when
1215          * the wake lock was created.
1216          * </p>
1217          */
acquire()1218         public void acquire() {
1219             synchronized (mToken) {
1220                 acquireLocked();
1221             }
1222         }
1223 
1224         /**
1225          * Acquires the wake lock with a timeout.
1226          * <p>
1227          * Ensures that the device is on at the level requested when
1228          * the wake lock was created.  The lock will be released after the given timeout
1229          * expires.
1230          * </p>
1231          *
1232          * @param timeout The timeout after which to release the wake lock, in milliseconds.
1233          */
acquire(long timeout)1234         public void acquire(long timeout) {
1235             synchronized (mToken) {
1236                 acquireLocked();
1237                 mHandler.postDelayed(mReleaser, timeout);
1238             }
1239         }
1240 
acquireLocked()1241         private void acquireLocked() {
1242             if (!mRefCounted || mCount++ == 0) {
1243                 // Do this even if the wake lock is already thought to be held (mHeld == true)
1244                 // because non-reference counted wake locks are not always properly released.
1245                 // For example, the keyguard's wake lock might be forcibly released by the
1246                 // power manager without the keyguard knowing.  A subsequent call to acquire
1247                 // should immediately acquire the wake lock once again despite never having
1248                 // been explicitly released by the keyguard.
1249                 mHandler.removeCallbacks(mReleaser);
1250                 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
1251                 try {
1252                     mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
1253                             mHistoryTag);
1254                 } catch (RemoteException e) {
1255                     throw e.rethrowFromSystemServer();
1256                 }
1257                 mHeld = true;
1258             }
1259         }
1260 
1261         /**
1262          * Releases the wake lock.
1263          * <p>
1264          * This method releases your claim to the CPU or screen being on.
1265          * The screen may turn off shortly after you release the wake lock, or it may
1266          * not if there are other wake locks still held.
1267          * </p>
1268          */
release()1269         public void release() {
1270             release(0);
1271         }
1272 
1273         /**
1274          * Releases the wake lock with flags to modify the release behavior.
1275          * <p>
1276          * This method releases your claim to the CPU or screen being on.
1277          * The screen may turn off shortly after you release the wake lock, or it may
1278          * not if there are other wake locks still held.
1279          * </p>
1280          *
1281          * @param flags Combination of flag values to modify the release behavior.
1282          * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
1283          * Passing 0 is equivalent to calling {@link #release()}.
1284          */
release(int flags)1285         public void release(int flags) {
1286             synchronized (mToken) {
1287                 if (!mRefCounted || --mCount == 0) {
1288                     mHandler.removeCallbacks(mReleaser);
1289                     if (mHeld) {
1290                         Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1291                         try {
1292                             mService.releaseWakeLock(mToken, flags);
1293                         } catch (RemoteException e) {
1294                             throw e.rethrowFromSystemServer();
1295                         }
1296                         mHeld = false;
1297                     }
1298                 }
1299                 if (mCount < 0) {
1300                     throw new RuntimeException("WakeLock under-locked " + mTag);
1301                 }
1302             }
1303         }
1304 
1305         /**
1306          * Returns true if the wake lock has been acquired but not yet released.
1307          *
1308          * @return True if the wake lock is held.
1309          */
isHeld()1310         public boolean isHeld() {
1311             synchronized (mToken) {
1312                 return mHeld;
1313             }
1314         }
1315 
1316         /**
1317          * Sets the work source associated with the wake lock.
1318          * <p>
1319          * The work source is used to determine on behalf of which application
1320          * the wake lock is being held.  This is useful in the case where a
1321          * service is performing work on behalf of an application so that the
1322          * cost of that work can be accounted to the application.
1323          * </p>
1324          *
1325          * @param ws The work source, or null if none.
1326          */
setWorkSource(WorkSource ws)1327         public void setWorkSource(WorkSource ws) {
1328             synchronized (mToken) {
1329                 if (ws != null && ws.size() == 0) {
1330                     ws = null;
1331                 }
1332 
1333                 final boolean changed;
1334                 if (ws == null) {
1335                     changed = mWorkSource != null;
1336                     mWorkSource = null;
1337                 } else if (mWorkSource == null) {
1338                     changed = true;
1339                     mWorkSource = new WorkSource(ws);
1340                 } else {
1341                     changed = mWorkSource.diff(ws);
1342                     if (changed) {
1343                         mWorkSource.set(ws);
1344                     }
1345                 }
1346 
1347                 if (changed && mHeld) {
1348                     try {
1349                         mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
1350                     } catch (RemoteException e) {
1351                         throw e.rethrowFromSystemServer();
1352                     }
1353                 }
1354             }
1355         }
1356 
1357         /** @hide */
setTag(String tag)1358         public void setTag(String tag) {
1359             mTag = tag;
1360         }
1361 
1362         /** @hide */
getTag()1363         public String getTag() {
1364             return mTag;
1365         }
1366 
1367         /** @hide */
setHistoryTag(String tag)1368         public void setHistoryTag(String tag) {
1369             mHistoryTag = tag;
1370         }
1371 
1372         /** @hide */
setUnimportantForLogging(boolean state)1373         public void setUnimportantForLogging(boolean state) {
1374             if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
1375             else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
1376         }
1377 
1378         @Override
toString()1379         public String toString() {
1380             synchronized (mToken) {
1381                 return "WakeLock{"
1382                     + Integer.toHexString(System.identityHashCode(this))
1383                     + " held=" + mHeld + ", refCount=" + mCount + "}";
1384             }
1385         }
1386 
1387         /**
1388          * Wraps a Runnable such that this method immediately acquires the wake lock and then
1389          * once the Runnable is done the wake lock is released.
1390          *
1391          * <p>Example:
1392          *
1393          * <pre>
1394          * mHandler.post(mWakeLock.wrap(() -> {
1395          *     // do things on handler, lock is held while we're waiting for this
1396          *     // to get scheduled and until the runnable is done executing.
1397          * });
1398          * </pre>
1399          *
1400          * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
1401          *    leak the wakelock!
1402          *
1403          * @hide
1404          */
wrap(Runnable r)1405         public Runnable wrap(Runnable r) {
1406             acquire();
1407             return () -> {
1408                 try {
1409                     r.run();
1410                 } finally {
1411                     release();
1412                 }
1413             };
1414         }
1415     }
1416 }
1417