PowerManager.java revision 08c47a5dece977a55d250d98bda9e2a8df8b6ed0
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
17package android.os;
18
19import android.annotation.SdkConstant;
20import android.annotation.SystemApi;
21import android.content.Context;
22import 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 &lt;uses-permission&gt;} element of the application's manifest.
100 * </p>
101 */
102public 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 flag: If already dimmed, extend the dim timeout
311     * but do not brighten.  This flag is useful for keeping the screen on
312     * a little longer without causing a visible change such as when
313     * the power key is pressed.
314     * @hide
315     */
316    @SystemApi
317    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
318
319    /**
320     * User activity flag: Note the user activity as usual but do not
321     * reset the user activity timeout.  This flag is useful for applying
322     * user activity power hints when interacting with the device indirectly
323     * on a secondary screen while allowing the primary screen to go to sleep.
324     * @hide
325     */
326    @SystemApi
327    public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
328
329    /**
330     * Go to sleep reason code: Going to sleep due by application request.
331     * @hide
332     */
333    public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
334
335    /**
336     * Go to sleep reason code: Going to sleep due by request of the
337     * device administration policy.
338     * @hide
339     */
340    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
341
342    /**
343     * Go to sleep reason code: Going to sleep due to a screen timeout.
344     * @hide
345     */
346    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
347
348    /**
349     * Go to sleep reason code: Going to sleep due to the lid switch being closed.
350     * @hide
351     */
352    public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
353
354    /**
355     * Go to sleep reason code: Going to sleep due to the power button being pressed.
356     * @hide
357     */
358    public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
359
360    /**
361     * Go to sleep reason code: Going to sleep due to HDMI.
362     * @hide
363     */
364    public static final int GO_TO_SLEEP_REASON_HDMI = 5;
365
366    /**
367     * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
368     * @hide
369     */
370    public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
371
372    /**
373     * Go to sleep flag: Skip dozing state and directly go to full sleep.
374     * @hide
375     */
376    public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
377
378    /**
379     * The value to pass as the 'reason' argument to reboot() to
380     * reboot into recovery mode (for applying system updates, doing
381     * factory resets, etc.).
382     * <p>
383     * Requires the {@link android.Manifest.permission#RECOVERY}
384     * permission (in addition to
385     * {@link android.Manifest.permission#REBOOT}).
386     * </p>
387     * @hide
388     */
389    public static final String REBOOT_RECOVERY = "recovery";
390
391    /**
392     * The value to pass as the 'reason' argument to android_reboot().
393     * @hide
394     */
395    public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
396
397    final Context mContext;
398    final IPowerManager mService;
399    final Handler mHandler;
400
401    IDeviceIdleController mIDeviceIdleController;
402
403    /**
404     * {@hide}
405     */
406    public PowerManager(Context context, IPowerManager service, Handler handler) {
407        mContext = context;
408        mService = service;
409        mHandler = handler;
410    }
411
412    /**
413     * Gets the minimum supported screen brightness setting.
414     * The screen may be allowed to become dimmer than this value but
415     * this is the minimum value that can be set by the user.
416     * @hide
417     */
418    public int getMinimumScreenBrightnessSetting() {
419        return mContext.getResources().getInteger(
420                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
421    }
422
423    /**
424     * Gets the maximum supported screen brightness setting.
425     * The screen may be allowed to become dimmer than this value but
426     * this is the maximum value that can be set by the user.
427     * @hide
428     */
429    public int getMaximumScreenBrightnessSetting() {
430        return mContext.getResources().getInteger(
431                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
432    }
433
434    /**
435     * Gets the default screen brightness setting.
436     * @hide
437     */
438    public int getDefaultScreenBrightnessSetting() {
439        return mContext.getResources().getInteger(
440                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
441    }
442
443    /**
444     * Returns true if the twilight service should be used to adjust screen brightness
445     * policy.  This setting is experimental and disabled by default.
446     * @hide
447     */
448    public static boolean useTwilightAdjustmentFeature() {
449        return SystemProperties.getBoolean("persist.power.usetwilightadj", false);
450    }
451
452    /**
453     * Creates a new wake lock with the specified level and flags.
454     * <p>
455     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
456     * combined using the logical OR operator.
457     * </p><p>
458     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
459     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
460     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
461     * specified as part of the {@code levelAndFlags} parameter.
462     * </p><p>
463     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
464     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
465     * {@code levelAndFlags} parameters.
466     * </p><p>
467     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
468     * wake lock, and {@link WakeLock#release release()} when you are done.
469     * </p><p>
470     * {@samplecode
471     * PowerManager pm = (PowerManager)mContext.getSystemService(
472     *                                          Context.POWER_SERVICE);
473     * PowerManager.WakeLock wl = pm.newWakeLock(
474     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
475     *                                      | PowerManager.ON_AFTER_RELEASE,
476     *                                      TAG);
477     * wl.acquire();
478     * // ... do work...
479     * wl.release();
480     * }
481     * </p><p>
482     * Although a wake lock can be created without special permissions,
483     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
484     * required to actually acquire or release the wake lock that is returned.
485     * </p><p class="note">
486     * If using this to keep the screen on, you should strongly consider using
487     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
488     * This window flag will be correctly managed by the platform
489     * as the user moves between applications and doesn't require a special permission.
490     * </p>
491     *
492     * @param levelAndFlags Combination of wake lock level and flag values defining
493     * the requested behavior of the WakeLock.
494     * @param tag Your class name (or other tag) for debugging purposes.
495     *
496     * @see WakeLock#acquire()
497     * @see WakeLock#release()
498     * @see #PARTIAL_WAKE_LOCK
499     * @see #FULL_WAKE_LOCK
500     * @see #SCREEN_DIM_WAKE_LOCK
501     * @see #SCREEN_BRIGHT_WAKE_LOCK
502     * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
503     * @see #ACQUIRE_CAUSES_WAKEUP
504     * @see #ON_AFTER_RELEASE
505     */
506    public WakeLock newWakeLock(int levelAndFlags, String tag) {
507        validateWakeLockParameters(levelAndFlags, tag);
508        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
509    }
510
511    /** @hide */
512    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
513        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
514            case PARTIAL_WAKE_LOCK:
515            case SCREEN_DIM_WAKE_LOCK:
516            case SCREEN_BRIGHT_WAKE_LOCK:
517            case FULL_WAKE_LOCK:
518            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
519            case DOZE_WAKE_LOCK:
520            case DRAW_WAKE_LOCK:
521                break;
522            default:
523                throw new IllegalArgumentException("Must specify a valid wake lock level.");
524        }
525        if (tag == null) {
526            throw new IllegalArgumentException("The tag must not be null.");
527        }
528    }
529
530    /**
531     * Notifies the power manager that user activity happened.
532     * <p>
533     * Resets the auto-off timer and brightens the screen if the device
534     * is not asleep.  This is what happens normally when a key or the touch
535     * screen is pressed or when some other user activity occurs.
536     * This method does not wake up the device if it has been put to sleep.
537     * </p><p>
538     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
539     * </p>
540     *
541     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
542     * time base.  This timestamp is used to correctly order the user activity request with
543     * other power management functions.  It should be set
544     * to the timestamp of the input event that caused the user activity.
545     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
546     * because of this event.  This is set when the power key is pressed.
547     * We want the device to stay on while the button is down, but we're about
548     * to turn off the screen so we don't want the keyboard backlight to turn on again.
549     * Otherwise the lights flash on and then off and it looks weird.
550     *
551     * @see #wakeUp
552     * @see #goToSleep
553     *
554     * @removed Requires signature or system permission.
555     * @deprecated Use {@link #userActivity(long, int, int)}.
556     */
557    @Deprecated
558    public void userActivity(long when, boolean noChangeLights) {
559        userActivity(when, USER_ACTIVITY_EVENT_OTHER,
560                noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
561    }
562
563    /**
564     * Notifies the power manager that user activity happened.
565     * <p>
566     * Resets the auto-off timer and brightens the screen if the device
567     * is not asleep.  This is what happens normally when a key or the touch
568     * screen is pressed or when some other user activity occurs.
569     * This method does not wake up the device if it has been put to sleep.
570     * </p><p>
571     * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
572     * {@link android.Manifest.permission#USER_ACTIVITY} permission.
573     * </p>
574     *
575     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
576     * time base.  This timestamp is used to correctly order the user activity request with
577     * other power management functions.  It should be set
578     * to the timestamp of the input event that caused the user activity.
579     * @param event The user activity event.
580     * @param flags Optional user activity flags.
581     *
582     * @see #wakeUp
583     * @see #goToSleep
584     *
585     * @hide Requires signature or system permission.
586     */
587    @SystemApi
588    public void userActivity(long when, int event, int flags) {
589        try {
590            mService.userActivity(when, event, flags);
591        } catch (RemoteException e) {
592        }
593    }
594
595   /**
596     * Forces the device to go to sleep.
597     * <p>
598     * Overrides all the wake locks that are held.
599     * This is what happens when the power key is pressed to turn off the screen.
600     * </p><p>
601     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
602     * </p>
603     *
604     * @param time The time when the request to go to sleep was issued, in the
605     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
606     * order the go to sleep request with other power management functions.  It should be set
607     * to the timestamp of the input event that caused the request to go to sleep.
608     *
609     * @see #userActivity
610     * @see #wakeUp
611     *
612     * @removed Requires signature permission.
613     */
614    public void goToSleep(long time) {
615        goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
616    }
617
618    /**
619     * Forces the device to go to sleep.
620     * <p>
621     * Overrides all the wake locks that are held.
622     * This is what happens when the power key is pressed to turn off the screen.
623     * </p><p>
624     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
625     * </p>
626     *
627     * @param time The time when the request to go to sleep was issued, in the
628     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
629     * order the go to sleep request with other power management functions.  It should be set
630     * to the timestamp of the input event that caused the request to go to sleep.
631     * @param reason The reason the device is going to sleep.
632     * @param flags Optional flags to apply when going to sleep.
633     *
634     * @see #userActivity
635     * @see #wakeUp
636     *
637     * @hide Requires signature permission.
638     */
639    public void goToSleep(long time, int reason, int flags) {
640        try {
641            mService.goToSleep(time, reason, flags);
642        } catch (RemoteException e) {
643        }
644    }
645
646    /**
647     * Forces the device to wake up from sleep.
648     * <p>
649     * If the device is currently asleep, wakes it up, otherwise does nothing.
650     * This is what happens when the power key is pressed to turn on the screen.
651     * </p><p>
652     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
653     * </p>
654     *
655     * @param time The time when the request to wake up was issued, in the
656     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
657     * order the wake up request with other power management functions.  It should be set
658     * to the timestamp of the input event that caused the request to wake up.
659     *
660     * @see #userActivity
661     * @see #goToSleep
662     *
663     * @removed Requires signature permission.
664     */
665    public void wakeUp(long time) {
666        try {
667            mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
668        } catch (RemoteException e) {
669        }
670    }
671
672    /**
673     * @hide
674     */
675    public void wakeUp(long time, String reason) {
676        try {
677            mService.wakeUp(time, reason, mContext.getOpPackageName());
678        } catch (RemoteException e) {
679        }
680    }
681
682    /**
683     * Forces the device to start napping.
684     * <p>
685     * If the device is currently awake, starts dreaming, otherwise does nothing.
686     * When the dream ends or if the dream cannot be started, the device will
687     * either wake up or go to sleep depending on whether there has been recent
688     * user activity.
689     * </p><p>
690     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
691     * </p>
692     *
693     * @param time The time when the request to nap was issued, in the
694     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
695     * order the nap request with other power management functions.  It should be set
696     * to the timestamp of the input event that caused the request to nap.
697     *
698     * @see #wakeUp
699     * @see #goToSleep
700     *
701     * @hide Requires signature permission.
702     */
703    public void nap(long time) {
704        try {
705            mService.nap(time);
706        } catch (RemoteException e) {
707        }
708    }
709
710    /**
711     * Boosts the brightness of the screen to maximum for a predetermined
712     * period of time.  This is used to make the screen more readable in bright
713     * daylight for a short duration.
714     * <p>
715     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
716     * </p>
717     *
718     * @param time The time when the request to boost was issued, in the
719     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
720     * order the boost request with other power management functions.  It should be set
721     * to the timestamp of the input event that caused the request to boost.
722     *
723     * @hide Requires signature permission.
724     */
725    public void boostScreenBrightness(long time) {
726        try {
727            mService.boostScreenBrightness(time);
728        } catch (RemoteException e) {
729        }
730    }
731
732    /**
733     * Returns whether the screen brightness is currently boosted to maximum, caused by a call
734     * to {@link #boostScreenBrightness(long)}.
735     * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
736     *
737     * @hide
738     */
739    @SystemApi
740    public boolean isScreenBrightnessBoosted() {
741        try {
742            return mService.isScreenBrightnessBoosted();
743        } catch (RemoteException e) {
744            return false;
745        }
746    }
747
748    /**
749     * Sets the brightness of the backlights (screen, keyboard, button).
750     * <p>
751     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
752     * </p>
753     *
754     * @param brightness The brightness value from 0 to 255.
755     *
756     * @hide Requires signature permission.
757     */
758    public void setBacklightBrightness(int brightness) {
759        try {
760            mService.setTemporaryScreenBrightnessSettingOverride(brightness);
761        } catch (RemoteException e) {
762        }
763    }
764
765   /**
766     * Returns true if the specified wake lock level is supported.
767     *
768     * @param level The wake lock level to check.
769     * @return True if the specified wake lock level is supported.
770     */
771    public boolean isWakeLockLevelSupported(int level) {
772        try {
773            return mService.isWakeLockLevelSupported(level);
774        } catch (RemoteException e) {
775            return false;
776        }
777    }
778
779    /**
780      * Returns true if the device is in an interactive state.
781      * <p>
782      * For historical reasons, the name of this method refers to the power state of
783      * the screen but it actually describes the overall interactive state of
784      * the device.  This method has been replaced by {@link #isInteractive}.
785      * </p><p>
786      * The value returned by this method only indicates whether the device is
787      * in an interactive state which may have nothing to do with the screen being
788      * on or off.  To determine the actual state of the screen,
789      * use {@link android.view.Display#getState}.
790      * </p>
791      *
792      * @return True if the device is in an interactive state.
793      *
794      * @deprecated Use {@link #isInteractive} instead.
795      */
796    @Deprecated
797    public boolean isScreenOn() {
798        return isInteractive();
799    }
800
801    /**
802     * Returns true if the device is in an interactive state.
803     * <p>
804     * When this method returns true, the device is awake and ready to interact
805     * with the user (although this is not a guarantee that the user is actively
806     * interacting with the device just this moment).  The main screen is usually
807     * turned on while in this state.  Certain features, such as the proximity
808     * sensor, may temporarily turn off the screen while still leaving the device in an
809     * interactive state.  Note in particular that the device is still considered
810     * to be interactive while dreaming (since dreams can be interactive) but not
811     * when it is dozing or asleep.
812     * </p><p>
813     * When this method returns false, the device is dozing or asleep and must
814     * be awoken before it will become ready to interact with the user again.  The
815     * main screen is usually turned off while in this state.  Certain features,
816     * such as "ambient mode" may cause the main screen to remain on (albeit in a
817     * low power state) to display system-provided content while the device dozes.
818     * </p><p>
819     * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
820     * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
821     * whenever the interactive state of the device changes.  For historical reasons,
822     * the names of these broadcasts refer to the power state of the screen
823     * but they are actually sent in response to changes in the overall interactive
824     * state of the device, as described by this method.
825     * </p><p>
826     * Services may use the non-interactive state as a hint to conserve power
827     * since the user is not present.
828     * </p>
829     *
830     * @return True if the device is in an interactive state.
831     *
832     * @see android.content.Intent#ACTION_SCREEN_ON
833     * @see android.content.Intent#ACTION_SCREEN_OFF
834     */
835    public boolean isInteractive() {
836        try {
837            return mService.isInteractive();
838        } catch (RemoteException e) {
839            return false;
840        }
841    }
842
843    /**
844     * Reboot the device.  Will not return if the reboot is successful.
845     * <p>
846     * Requires the {@link android.Manifest.permission#REBOOT} permission.
847     * </p>
848     *
849     * @param reason code to pass to the kernel (e.g., "recovery") to
850     *               request special boot modes, or null.
851     */
852    public void reboot(String reason) {
853        try {
854            mService.reboot(false, reason, true);
855        } catch (RemoteException e) {
856        }
857    }
858
859    /**
860     * Returns true if the device is currently in power save mode.  When in this mode,
861     * applications should reduce their functionality in order to conserve battery as
862     * much as possible.  You can monitor for changes to this state with
863     * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
864     *
865     * @return Returns true if currently in low power mode, else false.
866     */
867    public boolean isPowerSaveMode() {
868        try {
869            return mService.isPowerSaveMode();
870        } catch (RemoteException e) {
871            return false;
872        }
873    }
874
875    /**
876     * Set the current power save mode.
877     *
878     * @return True if the set was allowed.
879     *
880     * @see #isPowerSaveMode()
881     *
882     * @hide
883     */
884    public boolean setPowerSaveMode(boolean mode) {
885        try {
886            return mService.setPowerSaveMode(mode);
887        } catch (RemoteException e) {
888            return false;
889        }
890    }
891
892    /**
893     * Returns true if the device is currently in idle mode.  This happens when a device
894     * has been sitting unused and unmoving for a sufficiently long period of time, so that
895     * it decides to go into a lower power-use state.  This may involve things like turning
896     * off network access to apps.  You can monitor for changes to this state with
897     * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
898     *
899     * @return Returns true if currently in active device idle mode, else false.  This is
900     * when idle mode restrictions are being actively applied; it will return false if the
901     * device is in a long-term idle mode but currently running a maintenance window where
902     * restrictions have been lifted.
903     */
904    public boolean isDeviceIdleMode() {
905        try {
906            return mService.isDeviceIdleMode();
907        } catch (RemoteException e) {
908            return false;
909        }
910    }
911
912    /**
913     * Returns true if the device is currently in light idle mode.  This happens when a device
914     * has had its screen off for a short time, switching it into a batching mode where we
915     * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
916     * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
917     *
918     * @return Returns true if currently in active light device idle mode, else false.  This is
919     * when light idle mode restrictions are being actively applied; it will return false if the
920     * device is in a long-term idle mode but currently running a maintenance window where
921     * restrictions have been lifted.
922     * @hide
923     */
924    public boolean isLightDeviceIdleMode() {
925        try {
926            return mService.isLightDeviceIdleMode();
927        } catch (RemoteException e) {
928            return false;
929        }
930    }
931
932    /**
933     * Return whether the given application package name is on the device's power whitelist.
934     * Apps can be placed on the whitelist through the settings UI invoked by
935     * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
936     */
937    public boolean isIgnoringBatteryOptimizations(String packageName) {
938        synchronized (this) {
939            if (mIDeviceIdleController == null) {
940                mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
941                        ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
942            }
943        }
944        try {
945            return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
946        } catch (RemoteException e) {
947            return false;
948        }
949    }
950
951    /**
952     * Turn off the device.
953     *
954     * @param confirm If true, shows a shutdown confirmation dialog.
955     * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
956     * @param wait If true, this call waits for the shutdown to complete and does not return.
957     *
958     * @hide
959     */
960    public void shutdown(boolean confirm, String reason, boolean wait) {
961        try {
962            mService.shutdown(confirm, reason, wait);
963        } catch (RemoteException e) {
964        }
965    }
966
967    /**
968     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
969     * This broadcast is only sent to registered receivers.
970     */
971    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
972    public static final String ACTION_POWER_SAVE_MODE_CHANGED
973            = "android.os.action.POWER_SAVE_MODE_CHANGED";
974
975    /**
976     * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
977     * This broadcast is only sent to registered receivers.
978     */
979    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
980    public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
981            = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
982
983    /**
984     * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
985     * This broadcast is only sent to registered receivers.
986     * @hide
987     */
988    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
989    public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
990            = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
991
992    /**
993     * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
994     * This broadcast is only sent to registered receivers.
995     */
996    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
997    public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
998            = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
999
1000    /**
1001     * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1002     * This broadcast is only sent to registered receivers.
1003     */
1004    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1005    public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
1006            = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
1007
1008    /**
1009     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
1010     * This broadcast is only sent to registered receivers.
1011     *
1012     * @hide
1013     */
1014    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1015    public static final String ACTION_POWER_SAVE_MODE_CHANGING
1016            = "android.os.action.POWER_SAVE_MODE_CHANGING";
1017
1018    /** @hide */
1019    public static final String EXTRA_POWER_SAVE_MODE = "mode";
1020
1021    /**
1022     * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
1023     * This broadcast is only sent to registered receivers.
1024     *
1025     * @hide
1026     **/
1027    @SystemApi
1028    public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
1029            = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
1030
1031    /**
1032     * A wake lock is a mechanism to indicate that your application needs
1033     * to have the device stay on.
1034     * <p>
1035     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
1036     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
1037     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
1038     * </p><p>
1039     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
1040     * on at the level that was requested when the wake lock was created.
1041     * </p><p>
1042     * Call {@link #release()} when you are done and don't need the lock anymore.
1043     * It is very important to do this as soon as possible to avoid running down the
1044     * device's battery excessively.
1045     * </p>
1046     */
1047    public final class WakeLock {
1048        private int mFlags;
1049        private String mTag;
1050        private final String mPackageName;
1051        private final IBinder mToken;
1052        private int mCount;
1053        private boolean mRefCounted = true;
1054        private boolean mHeld;
1055        private WorkSource mWorkSource;
1056        private String mHistoryTag;
1057        private final String mTraceName;
1058
1059        private final Runnable mReleaser = new Runnable() {
1060            public void run() {
1061                release();
1062            }
1063        };
1064
1065        WakeLock(int flags, String tag, String packageName) {
1066            mFlags = flags;
1067            mTag = tag;
1068            mPackageName = packageName;
1069            mToken = new Binder();
1070            mTraceName = "WakeLock (" + mTag + ")";
1071        }
1072
1073        @Override
1074        protected void finalize() throws Throwable {
1075            synchronized (mToken) {
1076                if (mHeld) {
1077                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
1078                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1079                    try {
1080                        mService.releaseWakeLock(mToken, 0);
1081                    } catch (RemoteException e) {
1082                    }
1083                }
1084            }
1085        }
1086
1087        /**
1088         * Sets whether this WakeLock is reference counted.
1089         * <p>
1090         * Wake locks are reference counted by default.  If a wake lock is
1091         * reference counted, then each call to {@link #acquire()} must be
1092         * balanced by an equal number of calls to {@link #release()}.  If a wake
1093         * lock is not reference counted, then one call to {@link #release()} is
1094         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
1095         * </p>
1096         *
1097         * @param value True to make the wake lock reference counted, false to
1098         * make the wake lock non-reference counted.
1099         */
1100        public void setReferenceCounted(boolean value) {
1101            synchronized (mToken) {
1102                mRefCounted = value;
1103            }
1104        }
1105
1106        /**
1107         * Acquires the wake lock.
1108         * <p>
1109         * Ensures that the device is on at the level requested when
1110         * the wake lock was created.
1111         * </p>
1112         */
1113        public void acquire() {
1114            synchronized (mToken) {
1115                acquireLocked();
1116            }
1117        }
1118
1119        /**
1120         * Acquires the wake lock with a timeout.
1121         * <p>
1122         * Ensures that the device is on at the level requested when
1123         * the wake lock was created.  The lock will be released after the given timeout
1124         * expires.
1125         * </p>
1126         *
1127         * @param timeout The timeout after which to release the wake lock, in milliseconds.
1128         */
1129        public void acquire(long timeout) {
1130            synchronized (mToken) {
1131                acquireLocked();
1132                mHandler.postDelayed(mReleaser, timeout);
1133            }
1134        }
1135
1136        private void acquireLocked() {
1137            if (!mRefCounted || mCount++ == 0) {
1138                // Do this even if the wake lock is already thought to be held (mHeld == true)
1139                // because non-reference counted wake locks are not always properly released.
1140                // For example, the keyguard's wake lock might be forcibly released by the
1141                // power manager without the keyguard knowing.  A subsequent call to acquire
1142                // should immediately acquire the wake lock once again despite never having
1143                // been explicitly released by the keyguard.
1144                mHandler.removeCallbacks(mReleaser);
1145                Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
1146                try {
1147                    mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
1148                            mHistoryTag);
1149                } catch (RemoteException e) {
1150                }
1151                mHeld = true;
1152            }
1153        }
1154
1155        /**
1156         * Releases the wake lock.
1157         * <p>
1158         * This method releases your claim to the CPU or screen being on.
1159         * The screen may turn off shortly after you release the wake lock, or it may
1160         * not if there are other wake locks still held.
1161         * </p>
1162         */
1163        public void release() {
1164            release(0);
1165        }
1166
1167        /**
1168         * Releases the wake lock with flags to modify the release behavior.
1169         * <p>
1170         * This method releases your claim to the CPU or screen being on.
1171         * The screen may turn off shortly after you release the wake lock, or it may
1172         * not if there are other wake locks still held.
1173         * </p>
1174         *
1175         * @param flags Combination of flag values to modify the release behavior.
1176         * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
1177         * Passing 0 is equivalent to calling {@link #release()}.
1178         */
1179        public void release(int flags) {
1180            synchronized (mToken) {
1181                if (!mRefCounted || --mCount == 0) {
1182                    mHandler.removeCallbacks(mReleaser);
1183                    if (mHeld) {
1184                        Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1185                        try {
1186                            mService.releaseWakeLock(mToken, flags);
1187                        } catch (RemoteException e) {
1188                        }
1189                        mHeld = false;
1190                    }
1191                }
1192                if (mCount < 0) {
1193                    throw new RuntimeException("WakeLock under-locked " + mTag);
1194                }
1195            }
1196        }
1197
1198        /**
1199         * Returns true if the wake lock has been acquired but not yet released.
1200         *
1201         * @return True if the wake lock is held.
1202         */
1203        public boolean isHeld() {
1204            synchronized (mToken) {
1205                return mHeld;
1206            }
1207        }
1208
1209        /**
1210         * Sets the work source associated with the wake lock.
1211         * <p>
1212         * The work source is used to determine on behalf of which application
1213         * the wake lock is being held.  This is useful in the case where a
1214         * service is performing work on behalf of an application so that the
1215         * cost of that work can be accounted to the application.
1216         * </p>
1217         *
1218         * @param ws The work source, or null if none.
1219         */
1220        public void setWorkSource(WorkSource ws) {
1221            synchronized (mToken) {
1222                if (ws != null && ws.size() == 0) {
1223                    ws = null;
1224                }
1225
1226                final boolean changed;
1227                if (ws == null) {
1228                    changed = mWorkSource != null;
1229                    mWorkSource = null;
1230                } else if (mWorkSource == null) {
1231                    changed = true;
1232                    mWorkSource = new WorkSource(ws);
1233                } else {
1234                    changed = mWorkSource.diff(ws);
1235                    if (changed) {
1236                        mWorkSource.set(ws);
1237                    }
1238                }
1239
1240                if (changed && mHeld) {
1241                    try {
1242                        mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
1243                    } catch (RemoteException e) {
1244                    }
1245                }
1246            }
1247        }
1248
1249        /** @hide */
1250        public void setTag(String tag) {
1251            mTag = tag;
1252        }
1253
1254        /** @hide */
1255        public void setHistoryTag(String tag) {
1256            mHistoryTag = tag;
1257        }
1258
1259        /** @hide */
1260        public void setUnimportantForLogging(boolean state) {
1261            if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
1262            else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
1263        }
1264
1265        @Override
1266        public String toString() {
1267            synchronized (mToken) {
1268                return "WakeLock{"
1269                    + Integer.toHexString(System.identityHashCode(this))
1270                    + " held=" + mHeld + ", refCount=" + mCount + "}";
1271            }
1272        }
1273    }
1274}
1275