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