2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.annotation.SdkConstant;
20 import android.annotation.SystemApi;
21 import android.content.Context;
22 import android.util.Log;
25 * This class gives you control of the power state of the device.
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.
32 * You can obtain an instance of this class by calling
33 * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
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.
39 * In practice it's quite simple:
41 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
42 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
44 * ..screen will stay on during this section..
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>
52 * <tr><th>Flag Value</th>
53 * <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
55 * <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
56 * <td>On*</td> <td>Off</td> <td>Off</td>
59 * <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
60 * <td>On</td> <td>Dim</td> <td>Off</td>
63 * <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
64 * <td>On</td> <td>Bright</td> <td>Off</td>
67 * <tr><td>{@link #FULL_WAKE_LOCK}</td>
68 * <td>On</td> <td>Bright</td> <td>Bright</td>
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>
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>
81 * <tr><th>Flag Value</th> <th>Description</th></tr>
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>
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>
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.
102 public final class PowerManager {
103 private static final String TAG = "PowerManager";
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
112 * Wake lock level: Ensures that the CPU is running; the screen and keyboard
113 * backlight will be allowed to go off.
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.
119 public static final int PARTIAL_WAKE_LOCK = 0x00000001;
122 * Wake lock level: Ensures that the screen is on (but may be dimmed);
123 * the keyboard backlight will be allowed to go off.
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}.
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.
136 public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;
139 * Wake lock level: Ensures that the screen is on at full brightness;
140 * the keyboard backlight will be allowed to go off.
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}.
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.
153 public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a;
156 * Wake lock level: Ensures that the screen and keyboard backlight are on at
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}.
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.
170 public static final int FULL_WAKE_LOCK = 0x0000001a;
173 * Wake lock level: Turns the screen off when the proximity sensor activates.
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.
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.
185 * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
186 * to determine whether this wake lock level is supported.
188 * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
191 public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020;
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.
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.
200 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
205 public static final int DOZE_WAKE_LOCK = 0x00000040;
208 * Wake lock level: Keep the device awake enough to allow drawing to occur.
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
214 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
219 public static final int DRAW_WAKE_LOCK = 0x00000080;
222 * Mask for the wake lock level component of a combined wake lock level and flags integer.
226 public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
229 * Wake lock flag: Turn the screen on when the wake lock is acquired.
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.
236 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
239 public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
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.
245 * Will not turn the screen on if it is not already on.
246 * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
248 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
251 public static final int ON_AFTER_RELEASE = 0x20000000;
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.
258 public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
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.
265 public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
268 * Brightness value for fully on.
271 public static final int BRIGHTNESS_ON = 255;
274 * Brightness value for fully off.
277 public static final int BRIGHTNESS_OFF = 0;
280 * Brightness value for default policy handling by the system.
283 public static final int BRIGHTNESS_DEFAULT = -1;
285 // Note: Be sure to update android.os.BatteryStats and PowerManager.h
286 // if adding or modifying user activity event constants.
289 * User activity event type: Unspecified event type.
293 public static final int USER_ACTIVITY_EVENT_OTHER = 0;
296 * User activity event type: Button or key pressed or released.
300 public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
303 * User activity event type: Touch down, move or up.
307 public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
310 * User activity event type: Accessibility taking action on behalf of user.
314 public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
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.
324 public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
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.
334 public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
337 * Go to sleep reason code: Going to sleep due by application request.
340 public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
343 * Go to sleep reason code: Going to sleep due by request of the
344 * device administration policy.
347 public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
350 * Go to sleep reason code: Going to sleep due to a screen timeout.
353 public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
356 * Go to sleep reason code: Going to sleep due to the lid switch being closed.
359 public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
362 * Go to sleep reason code: Going to sleep due to the power button being pressed.
365 public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
368 * Go to sleep reason code: Going to sleep due to HDMI.
371 public static final int GO_TO_SLEEP_REASON_HDMI = 5;
374 * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
377 public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
380 * Go to sleep flag: Skip dozing state and directly go to full sleep.
383 public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
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.
390 * Requires the {@link android.Manifest.permission#RECOVERY}
391 * permission (in addition to
392 * {@link android.Manifest.permission#REBOOT}).
396 public static final String REBOOT_RECOVERY = "recovery";
399 * The value to pass as the 'reason' argument to reboot() to reboot into
400 * recovery mode for applying system updates.
402 * Requires the {@link android.Manifest.permission#RECOVERY}
403 * permission (in addition to
404 * {@link android.Manifest.permission#REBOOT}).
408 public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
411 * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
415 public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
418 * The 'reason' value used when rebooting in safe mode
421 public static final String REBOOT_SAFE_MODE = "safemode";
424 * The value to pass as the 'reason' argument to android_reboot().
427 public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
429 final Context mContext;
430 final IPowerManager mService;
431 final Handler mHandler;
433 IDeviceIdleController mIDeviceIdleController;
438 public PowerManager(Context context, IPowerManager service, Handler handler) {
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.
450 public int getMinimumScreenBrightnessSetting() {
451 return mContext.getResources().getInteger(
452 com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
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.
461 public int getMaximumScreenBrightnessSetting() {
462 return mContext.getResources().getInteger(
463 com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
467 * Gets the default screen brightness setting.
470 public int getDefaultScreenBrightnessSetting() {
471 return mContext.getResources().getInteger(
472 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
476 * Returns true if the twilight service should be used to adjust screen brightness
477 * policy. This setting is experimental and disabled by default.
480 public static boolean useTwilightAdjustmentFeature() {
481 return SystemProperties.getBoolean("persist.power.usetwilightadj", false);
485 * Creates a new wake lock with the specified level and flags.
487 * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
488 * combined using the logical OR operator.
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.
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.
499 * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
500 * wake lock, and {@link WakeLock#release release()} when you are done.
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,
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.
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.
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
538 public WakeLock newWakeLock(int levelAndFlags, String tag) {
539 validateWakeLockParameters(levelAndFlags, tag);
540 return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
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:
550 case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
555 throw new IllegalArgumentException("Must specify a valid wake lock level.");
558 throw new IllegalArgumentException("The tag must not be null.");
563 * Notifies the power manager that user activity happened.
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.
570 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
586 * @removed Requires signature or system permission.
587 * @deprecated Use {@link #userActivity(long, int, int)}.
590 public void userActivity(long when, boolean noChangeLights) {
591 userActivity(when, USER_ACTIVITY_EVENT_OTHER,
592 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
596 * Notifies the power manager that user activity happened.
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.
603 * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
604 * {@link android.Manifest.permission#USER_ACTIVITY} permission.
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.
617 * @hide Requires signature or system permission.
620 public void userActivity(long when, int event, int flags) {
622 mService.userActivity(when, event, flags);
623 } catch (RemoteException e) {
624 throw e.rethrowFromSystemServer();
629 * Forces the device to go to sleep.
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.
634 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
645 * @removed Requires signature permission.
647 public void goToSleep(long time) {
648 goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
652 * Forces the device to go to sleep.
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.
657 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
670 * @hide Requires signature permission.
672 public void goToSleep(long time, int reason, int flags) {
674 mService.goToSleep(time, reason, flags);
675 } catch (RemoteException e) {
676 throw e.rethrowFromSystemServer();
681 * Forces the device to wake up from sleep.
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.
686 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
697 * @removed Requires signature permission.
699 public void wakeUp(long time) {
701 mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
702 } catch (RemoteException e) {
703 throw e.rethrowFromSystemServer();
710 public void wakeUp(long time, String reason) {
712 mService.wakeUp(time, reason, mContext.getOpPackageName());
713 } catch (RemoteException e) {
714 throw e.rethrowFromSystemServer();
719 * Forces the device to start napping.
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
726 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
737 * @hide Requires signature permission.
739 public void nap(long time) {
742 } catch (RemoteException e) {
743 throw e.rethrowFromSystemServer();
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.
752 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
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.
760 * @hide Requires signature permission.
762 public void boostScreenBrightness(long time) {
764 mService.boostScreenBrightness(time);
765 } catch (RemoteException e) {
766 throw e.rethrowFromSystemServer();
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.
778 public boolean isScreenBrightnessBoosted() {
780 return mService.isScreenBrightnessBoosted();
781 } catch (RemoteException e) {
782 throw e.rethrowFromSystemServer();
787 * Sets the brightness of the backlights (screen, keyboard, button).
789 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
792 * @param brightness The brightness value from 0 to 255.
794 * @hide Requires signature permission.
796 public void setBacklightBrightness(int brightness) {
798 mService.setTemporaryScreenBrightnessSettingOverride(brightness);
799 } catch (RemoteException e) {
800 throw e.rethrowFromSystemServer();
805 * Returns true if the specified wake lock level is supported.
807 * @param level The wake lock level to check.
808 * @return True if the specified wake lock level is supported.
810 public boolean isWakeLockLevelSupported(int level) {
812 return mService.isWakeLockLevelSupported(level);
813 } catch (RemoteException e) {
814 throw e.rethrowFromSystemServer();
819 * Returns true if the device is in an interactive state.
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}.
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}.
831 * @return True if the device is in an interactive state.
833 * @deprecated Use {@link #isInteractive} instead.
836 public boolean isScreenOn() {
837 return isInteractive();
841 * Returns true if the device is in an interactive state.
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.
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.
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.
865 * Services may use the non-interactive state as a hint to conserve power
866 * since the user is not present.
869 * @return True if the device is in an interactive state.
871 * @see android.content.Intent#ACTION_SCREEN_ON
872 * @see android.content.Intent#ACTION_SCREEN_OFF
874 public boolean isInteractive() {
876 return mService.isInteractive();
877 } catch (RemoteException e) {
878 throw e.rethrowFromSystemServer();
883 * Reboot the device. Will not return if the reboot is successful.
885 * Requires the {@link android.Manifest.permission#REBOOT} permission.
888 * @param reason code to pass to the kernel (e.g., "recovery") to
889 * request special boot modes, or null.
891 public void reboot(String reason) {
893 mService.reboot(false, reason, true);
894 } catch (RemoteException e) {
895 throw e.rethrowFromSystemServer();
900 * Reboot the device. Will not return if the reboot is successful.
902 * Requires the {@link android.Manifest.permission#REBOOT} permission.
906 public void rebootSafeMode() {
908 mService.rebootSafeMode(false, true);
909 } catch (RemoteException e) {
910 throw e.rethrowFromSystemServer();
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}.
920 * @return Returns true if currently in low power mode, else false.
922 public boolean isPowerSaveMode() {
924 return mService.isPowerSaveMode();
925 } catch (RemoteException e) {
926 throw e.rethrowFromSystemServer();
931 * Set the current power save mode.
933 * @return True if the set was allowed.
935 * @see #isPowerSaveMode()
939 public boolean setPowerSaveMode(boolean mode) {
941 return mService.setPowerSaveMode(mode);
942 } catch (RemoteException e) {
943 throw e.rethrowFromSystemServer();
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}.
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.
959 public boolean isDeviceIdleMode() {
961 return mService.isDeviceIdleMode();
962 } catch (RemoteException e) {
963 throw e.rethrowFromSystemServer();
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}.
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.
979 public boolean isLightDeviceIdleMode() {
981 return mService.isLightDeviceIdleMode();
982 } catch (RemoteException e) {
983 throw e.rethrowFromSystemServer();
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}.
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));
1000 return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
1001 } catch (RemoteException e) {
1002 throw e.rethrowFromSystemServer();
1007 * Turn off the device.
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.
1015 public void shutdown(boolean confirm, String reason, boolean wait) {
1017 mService.shutdown(confirm, reason, wait);
1018 } catch (RemoteException e) {
1019 throw e.rethrowFromSystemServer();
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
1028 * Sustained Performance Mode is intended to provide a consistent level of
1029 * performance for prolonged amount of time.
1031 * Applications should check if the device supports this mode, before using
1032 * {@link android.view.Window#setSustainedPerformanceMode}.
1034 * @return Returns True if the device supports it, false otherwise.
1036 * @see android.view.Window#setSustainedPerformanceMode
1038 public boolean isSustainedPerformanceModeSupported() {
1039 return mContext.getResources().getBoolean(
1040 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
1044 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1045 * This broadcast is only sent to registered receivers.
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";
1052 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
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";
1060 * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1061 * This broadcast is only sent to registered receivers.
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";
1068 * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1069 * This broadcast is only sent to registered receivers.
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";
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.
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";
1085 * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1086 * This broadcast is only sent to registered receivers.
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";
1093 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
1094 * This broadcast is only sent to registered receivers.
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";
1103 public static final String EXTRA_POWER_SAVE_MODE = "mode";
1106 * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
1107 * This broadcast is only sent to registered receivers.
1112 public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
1113 = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
1116 * A wake lock is a mechanism to indicate that your application needs
1117 * to have the device stay on.
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)}.
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.
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.
1131 public final class WakeLock {
1133 private String mTag;
1134 private final String mPackageName;
1135 private final IBinder mToken;
1137 private boolean mRefCounted = true;
1138 private boolean mHeld;
1139 private WorkSource mWorkSource;
1140 private String mHistoryTag;
1141 private final String mTraceName;
1143 private final Runnable mReleaser = new Runnable() {
1149 WakeLock(int flags, String tag, String packageName) {
1152 mPackageName = packageName;
1153 mToken = new Binder();
1154 mTraceName = "WakeLock (" + mTag + ")";
1158 protected void finalize() throws Throwable {
1159 synchronized (mToken) {
1161 Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
1162 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1164 mService.releaseWakeLock(mToken, 0);
1165 } catch (RemoteException e) {
1166 throw e.rethrowFromSystemServer();
1173 * Sets whether this WakeLock is reference counted.
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()}.
1182 * @param value True to make the wake lock reference counted, false to
1183 * make the wake lock non-reference counted.
1185 public void setReferenceCounted(boolean value) {
1186 synchronized (mToken) {
1187 mRefCounted = value;
1192 * Acquires the wake lock.
1194 * Ensures that the device is on at the level requested when
1195 * the wake lock was created.
1198 public void acquire() {
1199 synchronized (mToken) {
1205 * Acquires the wake lock with a timeout.
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
1212 * @param timeout The timeout after which to release the wake lock, in milliseconds.
1214 public void acquire(long timeout) {
1215 synchronized (mToken) {
1217 mHandler.postDelayed(mReleaser, timeout);
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);
1232 mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
1234 } catch (RemoteException e) {
1235 throw e.rethrowFromSystemServer();
1242 * Releases the wake lock.
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.
1249 public void release() {
1254 * Releases the wake lock with flags to modify the release behavior.
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.
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()}.
1265 public void release(int flags) {
1266 synchronized (mToken) {
1267 if (!mRefCounted || --mCount == 0) {
1268 mHandler.removeCallbacks(mReleaser);
1270 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1272 mService.releaseWakeLock(mToken, flags);
1273 } catch (RemoteException e) {
1274 throw e.rethrowFromSystemServer();
1280 throw new RuntimeException("WakeLock under-locked " + mTag);
1286 * Returns true if the wake lock has been acquired but not yet released.
1288 * @return True if the wake lock is held.
1290 public boolean isHeld() {
1291 synchronized (mToken) {
1297 * Sets the work source associated with the wake lock.
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.
1305 * @param ws The work source, or null if none.
1307 public void setWorkSource(WorkSource ws) {
1308 synchronized (mToken) {
1309 if (ws != null && ws.size() == 0) {
1313 final boolean changed;
1315 changed = mWorkSource != null;
1317 } else if (mWorkSource == null) {
1319 mWorkSource = new WorkSource(ws);
1321 changed = mWorkSource.diff(ws);
1323 mWorkSource.set(ws);
1327 if (changed && mHeld) {
1329 mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
1330 } catch (RemoteException e) {
1331 throw e.rethrowFromSystemServer();
1338 public void setTag(String tag) {
1343 public String getTag() {
1348 public void setHistoryTag(String tag) {
1353 public void setUnimportantForLogging(boolean state) {
1354 if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
1355 else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
1359 public String toString() {
1360 synchronized (mToken) {
1362 + Integer.toHexString(System.identityHashCode(this))
1363 + " held=" + mHeld + ", refCount=" + mCount + "}";
1368 * Wraps a Runnable such that this method immediately acquires the wake lock and then
1369 * once the Runnable is done the wake lock is released.
1374 * mHandler.post(mWakeLock.wrap(() -> {
1375 * // do things on handler, lock is held while we're waiting for this
1376 * // to get scheduled and until the runnable is done executing.
1380 * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
1381 * leak the wakelock!
1385 public Runnable wrap(Runnable r) {