PowerManager.java revision 3edf5272fb2185403dfe64b9722b9fc9b9de80f8
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.content.Context;
21import android.util.Log;
22
23/**
24 * This class gives you control of the power state of the device.
25 *
26 * <p>
27 * <b>Device battery life will be significantly affected by the use of this API.</b>
28 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
29 * possible, and be sure to release them as soon as possible.
30 * </p><p>
31 * You can obtain an instance of this class by calling
32 * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
33 * </p><p>
34 * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
35 * This will create a {@link PowerManager.WakeLock} object.  You can then use methods
36 * on the wake lock object to control the power state of the device.
37 * </p><p>
38 * In practice it's quite simple:
39 * {@samplecode
40 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
41 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
42 * wl.acquire();
43 *   ..screen will stay on during this section..
44 * wl.release();
45 * }
46 * </p><p>
47 * The following wake lock levels are defined, with varying effects on system power.
48 * <i>These levels are mutually exclusive - you may only specify one of them.</i>
49 *
50 * <table>
51 *     <tr><th>Flag Value</th>
52 *     <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
53 *
54 *     <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
55 *         <td>On*</td> <td>Off</td> <td>Off</td>
56 *     </tr>
57 *
58 *     <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
59 *         <td>On</td> <td>Dim</td> <td>Off</td>
60 *     </tr>
61 *
62 *     <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
63 *         <td>On</td> <td>Bright</td> <td>Off</td>
64 *     </tr>
65 *
66 *     <tr><td>{@link #FULL_WAKE_LOCK}</td>
67 *         <td>On</td> <td>Bright</td> <td>Bright</td>
68 *     </tr>
69 * </table>
70 * </p><p>
71 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
72 * display timeouts or the state of the screen and even after the user presses the power button.
73 * In all other wake locks, the CPU will run, but the user can still put the device to sleep
74 * using the power button.</i>
75 * </p><p>
76 * In addition, you can add two more flags, which affect behavior of the screen only.
77 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
78 *
79 * <table>
80 *     <tr><th>Flag Value</th> <th>Description</th></tr>
81 *
82 *     <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
83 *         <td>Normal wake locks don't actually turn on the illumination.  Instead, they cause
84 *         the illumination to remain on once it turns on (e.g. from user activity).  This flag
85 *         will force the screen and/or keyboard to turn on immediately, when the WakeLock is
86 *         acquired.  A typical use would be for notifications which are important for the user to
87 *         see immediately.</td>
88 *     </tr>
89 *
90 *     <tr><td>{@link #ON_AFTER_RELEASE}</td>
91 *         <td>If this flag is set, the user activity timer will be reset when the WakeLock is
92 *         released, causing the illumination to remain on a bit longer.  This can be used to
93 *         reduce flicker if you are cycling between wake lock conditions.</td>
94 *     </tr>
95 * </table>
96 * <p>
97 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
98 * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
99 * </p>
100 */
101public final class PowerManager {
102    private static final String TAG = "PowerManager";
103
104    /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
105     * combinations were actually supported so the bit field was removed.  This explains
106     * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
107     * value can be used.
108     */
109
110    /**
111     * Wake lock level: Ensures that the CPU is running; the screen and keyboard
112     * backlight will be allowed to go off.
113     * <p>
114     * If the user presses the power button, then the screen will be turned off
115     * but the CPU will be kept on until all partial wake locks have been released.
116     * </p>
117     */
118    public static final int PARTIAL_WAKE_LOCK = 0x00000001;
119
120    /**
121     * Wake lock level: Ensures that the screen is on (but may be dimmed);
122     * the keyboard backlight will be allowed to go off.
123     * <p>
124     * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
125     * implicitly released by the system, causing both the screen and the CPU to be turned off.
126     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
127     * </p>
128     *
129     * @deprecated Most applications should use
130     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
131     * of this type of wake lock, as it will be correctly managed by the platform
132     * as the user moves between applications and doesn't require a special permission.
133     */
134    @Deprecated
135    public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;
136
137    /**
138     * Wake lock level: Ensures that the screen is on at full brightness;
139     * the keyboard backlight will be allowed to go off.
140     * <p>
141     * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
142     * implicitly released by the system, causing both the screen and the CPU to be turned off.
143     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
144     * </p>
145     *
146     * @deprecated Most applications should use
147     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
148     * of this type of wake lock, as it will be correctly managed by the platform
149     * as the user moves between applications and doesn't require a special permission.
150     */
151    @Deprecated
152    public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a;
153
154    /**
155     * Wake lock level: Ensures that the screen and keyboard backlight are on at
156     * full brightness.
157     * <p>
158     * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
159     * implicitly released by the system, causing both the screen and the CPU to be turned off.
160     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
161     * </p>
162     *
163     * @deprecated Most applications should use
164     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
165     * of this type of wake lock, as it will be correctly managed by the platform
166     * as the user moves between applications and doesn't require a special permission.
167     */
168    @Deprecated
169    public static final int FULL_WAKE_LOCK = 0x0000001a;
170
171    /**
172     * Wake lock level: Turns the screen off when the proximity sensor activates.
173     * <p>
174     * If the proximity sensor detects that an object is nearby, the screen turns off
175     * immediately.  Shortly after the object moves away, the screen turns on again.
176     * </p><p>
177     * A proximity wake lock does not prevent the device from falling asleep
178     * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
179     * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
180     * wake locks are held, then the device will fall asleep (and lock) as usual.
181     * However, the device will not fall asleep while the screen has been turned off
182     * by the proximity sensor because it effectively counts as ongoing user activity.
183     * </p><p>
184     * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
185     * to determine whether this wake lock level is supported.
186     * </p><p>
187     * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
188     * </p>
189     *
190     * {@hide}
191     */
192    public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020;
193
194    /**
195     * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
196     * if no other wake locks are held.
197     * <p>
198     * This is used by the dream manager to implement doze mode.  It currently
199     * has no effect unless the power manager is in the dozing state.
200     * </p>
201     *
202     * {@hide}
203     */
204    public static final int DOZE_WAKE_LOCK = 0x00000040;
205
206    /**
207     * Mask for the wake lock level component of a combined wake lock level and flags integer.
208     *
209     * @hide
210     */
211    public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
212
213    /**
214     * Wake lock flag: Turn the screen on when the wake lock is acquired.
215     * <p>
216     * Normally wake locks don't actually wake the device, they just cause
217     * the screen to remain on once it's already on.  Think of the video player
218     * application as the normal behavior.  Notifications that pop up and want
219     * the device to be on are the exception; use this flag to be like them.
220     * </p><p>
221     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
222     * </p>
223     */
224    public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
225
226    /**
227     * Wake lock flag: When this wake lock is released, poke the user activity timer
228     * so the screen stays on for a little longer.
229     * <p>
230     * Will not turn the screen on if it is not already on.
231     * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
232     * </p><p>
233     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
234     * </p>
235     */
236    public static final int ON_AFTER_RELEASE = 0x20000000;
237
238    /**
239     * Wake lock flag: This wake lock is not important for logging events.  If a later
240     * wake lock is acquired that is important, it will be considered the one to log.
241     * @hide
242     */
243    public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
244
245    /**
246     * Flag for {@link WakeLock#release release(int)} to defer releasing a
247     * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor returns
248     * a negative value.
249     *
250     * {@hide}
251     */
252    public static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1;
253
254    /**
255     * Brightness value for fully on.
256     * @hide
257     */
258    public static final int BRIGHTNESS_ON = 255;
259
260    /**
261     * Brightness value for fully off.
262     * @hide
263     */
264    public static final int BRIGHTNESS_OFF = 0;
265
266    /**
267     * Brightness value for default policy handling by the system.
268     * @hide
269     */
270    public static final int BRIGHTNESS_DEFAULT = -1;
271
272    // Note: Be sure to update android.os.BatteryStats and PowerManager.h
273    // if adding or modifying user activity event constants.
274
275    /**
276     * User activity event type: Unspecified event type.
277     * @hide
278     */
279    public static final int USER_ACTIVITY_EVENT_OTHER = 0;
280
281    /**
282     * User activity event type: Button or key pressed or released.
283     * @hide
284     */
285    public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
286
287    /**
288     * User activity event type: Touch down, move or up.
289     * @hide
290     */
291    public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
292
293    /**
294     * User activity flag: Do not restart the user activity timeout or brighten
295     * the display in response to user activity if it is already dimmed.
296     * @hide
297     */
298    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
299
300    /**
301     * Go to sleep reason code: Going to sleep due by application request.
302     * @hide
303     */
304    public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
305
306    /**
307     * Go to sleep reason code: Going to sleep due by request of the
308     * device administration policy.
309     * @hide
310     */
311    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
312
313    /**
314     * Go to sleep reason code: Going to sleep due to a screen timeout.
315     * @hide
316     */
317    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
318
319    /**
320     * Go to sleep reason code: Going to sleep due to the lid switch being closed.
321     * @hide
322     */
323    public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
324
325    /**
326     * Go to sleep reason code: Going to sleep due to the power button being pressed.
327     * @hide
328     */
329    public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
330
331    /**
332     * Go to sleep reason code: Going to sleep due to HDMI.
333     * @hide
334     */
335    public static final int GO_TO_SLEEP_REASON_HDMI = 5;
336
337    /**
338     * The value to pass as the 'reason' argument to reboot() to
339     * reboot into recovery mode (for applying system updates, doing
340     * factory resets, etc.).
341     * <p>
342     * Requires the {@link android.Manifest.permission#RECOVERY}
343     * permission (in addition to
344     * {@link android.Manifest.permission#REBOOT}).
345     * </p>
346     * @hide
347     */
348    public static final String REBOOT_RECOVERY = "recovery";
349
350    /**
351     * Go to sleep flag: Skip dozing state and directly go to full sleep.
352     * @hide
353     */
354    public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
355
356    final Context mContext;
357    final IPowerManager mService;
358    final Handler mHandler;
359
360    /**
361     * {@hide}
362     */
363    public PowerManager(Context context, IPowerManager service, Handler handler) {
364        mContext = context;
365        mService = service;
366        mHandler = handler;
367    }
368
369    /**
370     * Gets the minimum supported screen brightness setting.
371     * The screen may be allowed to become dimmer than this value but
372     * this is the minimum value that can be set by the user.
373     * @hide
374     */
375    public int getMinimumScreenBrightnessSetting() {
376        return mContext.getResources().getInteger(
377                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
378    }
379
380    /**
381     * Gets the maximum supported screen brightness setting.
382     * The screen may be allowed to become dimmer than this value but
383     * this is the maximum value that can be set by the user.
384     * @hide
385     */
386    public int getMaximumScreenBrightnessSetting() {
387        return mContext.getResources().getInteger(
388                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
389    }
390
391    /**
392     * Gets the default screen brightness setting.
393     * @hide
394     */
395    public int getDefaultScreenBrightnessSetting() {
396        return mContext.getResources().getInteger(
397                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
398    }
399
400    /**
401     * Returns true if the twilight service should be used to adjust screen brightness
402     * policy.  This setting is experimental and disabled by default.
403     * @hide
404     */
405    public static boolean useTwilightAdjustmentFeature() {
406        return SystemProperties.getBoolean("persist.power.usetwilightadj", false);
407    }
408
409    /**
410     * Creates a new wake lock with the specified level and flags.
411     * <p>
412     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
413     * combined using the logical OR operator.
414     * </p><p>
415     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
416     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
417     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
418     * specified as part of the {@code levelAndFlags} parameter.
419     * </p><p>
420     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
421     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
422     * {@code levelAndFlags} parameters.
423     * </p><p>
424     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
425     * wake lock, and {@link WakeLock#release release()} when you are done.
426     * </p><p>
427     * {@samplecode
428     * PowerManager pm = (PowerManager)mContext.getSystemService(
429     *                                          Context.POWER_SERVICE);
430     * PowerManager.WakeLock wl = pm.newWakeLock(
431     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
432     *                                      | PowerManager.ON_AFTER_RELEASE,
433     *                                      TAG);
434     * wl.acquire();
435     * // ... do work...
436     * wl.release();
437     * }
438     * </p><p>
439     * Although a wake lock can be created without special permissions,
440     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
441     * required to actually acquire or release the wake lock that is returned.
442     * </p><p class="note">
443     * If using this to keep the screen on, you should strongly consider using
444     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
445     * This window flag will be correctly managed by the platform
446     * as the user moves between applications and doesn't require a special permission.
447     * </p>
448     *
449     * @param levelAndFlags Combination of wake lock level and flag values defining
450     * the requested behavior of the WakeLock.
451     * @param tag Your class name (or other tag) for debugging purposes.
452     *
453     * @see WakeLock#acquire()
454     * @see WakeLock#release()
455     * @see #PARTIAL_WAKE_LOCK
456     * @see #FULL_WAKE_LOCK
457     * @see #SCREEN_DIM_WAKE_LOCK
458     * @see #SCREEN_BRIGHT_WAKE_LOCK
459     * @see #ACQUIRE_CAUSES_WAKEUP
460     * @see #ON_AFTER_RELEASE
461     */
462    public WakeLock newWakeLock(int levelAndFlags, String tag) {
463        validateWakeLockParameters(levelAndFlags, tag);
464        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
465    }
466
467    /** @hide */
468    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
469        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
470            case PARTIAL_WAKE_LOCK:
471            case SCREEN_DIM_WAKE_LOCK:
472            case SCREEN_BRIGHT_WAKE_LOCK:
473            case FULL_WAKE_LOCK:
474            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
475            case DOZE_WAKE_LOCK:
476                break;
477            default:
478                throw new IllegalArgumentException("Must specify a valid wake lock level.");
479        }
480        if (tag == null) {
481            throw new IllegalArgumentException("The tag must not be null.");
482        }
483    }
484
485    /**
486     * Notifies the power manager that user activity happened.
487     * <p>
488     * Resets the auto-off timer and brightens the screen if the device
489     * is not asleep.  This is what happens normally when a key or the touch
490     * screen is pressed or when some other user activity occurs.
491     * This method does not wake up the device if it has been put to sleep.
492     * </p><p>
493     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
494     * </p>
495     *
496     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
497     * time base.  This timestamp is used to correctly order the user activity request with
498     * other power management functions.  It should be set
499     * to the timestamp of the input event that caused the user activity.
500     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
501     * because of this event.  This is set when the power key is pressed.
502     * We want the device to stay on while the button is down, but we're about
503     * to turn off the screen so we don't want the keyboard backlight to turn on again.
504     * Otherwise the lights flash on and then off and it looks weird.
505     *
506     * @see #wakeUp
507     * @see #goToSleep
508     */
509    public void userActivity(long when, boolean noChangeLights) {
510        try {
511            mService.userActivity(when, USER_ACTIVITY_EVENT_OTHER,
512                    noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
513        } catch (RemoteException e) {
514        }
515    }
516
517   /**
518     * Forces the device to go to sleep.
519     * <p>
520     * Overrides all the wake locks that are held.
521     * This is what happens when the power key is pressed to turn off the screen.
522     * </p><p>
523     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
524     * </p>
525     *
526     * @param time The time when the request to go to sleep was issued, in the
527     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
528     * order the go to sleep request with other power management functions.  It should be set
529     * to the timestamp of the input event that caused the request to go to sleep.
530     *
531     * @see #userActivity
532     * @see #wakeUp
533     */
534    public void goToSleep(long time) {
535        goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
536    }
537
538    /**
539     * @hide
540     */
541    public void goToSleep(long time, int reason, int flags) {
542        try {
543            mService.goToSleep(time, reason, flags);
544        } catch (RemoteException e) {
545        }
546    }
547
548    /**
549     * Forces the device to wake up from sleep.
550     * <p>
551     * If the device is currently asleep, wakes it up, otherwise does nothing.
552     * This is what happens when the power key is pressed to turn on the screen.
553     * </p><p>
554     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
555     * </p>
556     *
557     * @param time The time when the request to wake up was issued, in the
558     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
559     * order the wake up request with other power management functions.  It should be set
560     * to the timestamp of the input event that caused the request to wake up.
561     *
562     * @see #userActivity
563     * @see #goToSleep
564     */
565    public void wakeUp(long time) {
566        try {
567            mService.wakeUp(time);
568        } catch (RemoteException e) {
569        }
570    }
571
572    /**
573     * Forces the device to start napping.
574     * <p>
575     * If the device is currently awake, starts dreaming, otherwise does nothing.
576     * When the dream ends or if the dream cannot be started, the device will
577     * either wake up or go to sleep depending on whether there has been recent
578     * user activity.
579     * </p><p>
580     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
581     * </p>
582     *
583     * @param time The time when the request to nap was issued, in the
584     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
585     * order the nap request with other power management functions.  It should be set
586     * to the timestamp of the input event that caused the request to nap.
587     *
588     * @see #wakeUp
589     * @see #goToSleep
590     *
591     * @hide
592     */
593    public void nap(long time) {
594        try {
595            mService.nap(time);
596        } catch (RemoteException e) {
597        }
598    }
599
600    /**
601     * Sets the brightness of the backlights (screen, keyboard, button).
602     * <p>
603     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
604     * </p>
605     *
606     * @param brightness The brightness value from 0 to 255.
607     *
608     * {@hide}
609     */
610    public void setBacklightBrightness(int brightness) {
611        try {
612            mService.setTemporaryScreenBrightnessSettingOverride(brightness);
613        } catch (RemoteException e) {
614        }
615    }
616
617   /**
618     * Returns true if the specified wake lock level is supported.
619     *
620     * @param level The wake lock level to check.
621     * @return True if the specified wake lock level is supported.
622     *
623     * {@hide}
624     */
625    public boolean isWakeLockLevelSupported(int level) {
626        try {
627            return mService.isWakeLockLevelSupported(level);
628        } catch (RemoteException e) {
629            return false;
630        }
631    }
632
633    /**
634      * Returns true if the device is in an interactive state.
635      * <p>
636      * For historical reasons, the name of this method refers to the power state of
637      * the screen but it actually describes the overall interactive state of
638      * the device.  This method has been replaced by {@link #isInteractive}.
639      * </p><p>
640      * The value returned by this method only indicates whether the device is
641      * in an interactive state which may have nothing to do with the screen being
642      * on or off.  To determine the actual state of the screen,
643      * use {@link android.view.Display#getState}.
644      * </p>
645      *
646      * @return True if the device is in an interactive state.
647      *
648      * @deprecated Use {@link #isInteractive} instead.
649      */
650    @Deprecated
651    public boolean isScreenOn() {
652        return isInteractive();
653    }
654
655    /**
656     * Returns true if the device is in an interactive state.
657     * <p>
658     * When this method returns true, the device is awake and ready to interact
659     * with the user (although this is not a guarantee that the user is actively
660     * interacting with the device just this moment).  The main screen is usually
661     * turned on while in this state.  Certain features, such as the proximity
662     * sensor, may temporarily turn off the screen while still leaving the device in an
663     * interactive state.  Note in particular that the device is still considered
664     * to be interactive while dreaming (since dreams can be interactive) but not
665     * when it is dozing or asleep.
666     * </p><p>
667     * When this method returns false, the device is dozing or asleep and must
668     * be awoken before it will become ready to interact with the user again.  The
669     * main screen is usually turned off while in this state.  Certain features,
670     * such as "ambient mode" may cause the main screen to remain on (albeit in a
671     * low power state) to display system-provided content while the device dozes.
672     * </p><p>
673     * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
674     * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
675     * whenever the interactive state of the device changes.  For historical reasons,
676     * the names of these broadcasts refer to the power state of the screen
677     * but they are actually sent in response to changes in the overall interactive
678     * state of the device, as described by this method.
679     * </p><p>
680     * Services may use the non-interactive state as a hint to conserve power
681     * since the user is not present.
682     * </p>
683     *
684     * @return True if the device is in an interactive state.
685     *
686     * @see android.content.Intent#ACTION_SCREEN_ON
687     * @see android.content.Intent#ACTION_SCREEN_OFF
688     */
689    public boolean isInteractive() {
690        try {
691            return mService.isInteractive();
692        } catch (RemoteException e) {
693            return false;
694        }
695    }
696
697    /**
698     * Reboot the device.  Will not return if the reboot is successful.
699     * <p>
700     * Requires the {@link android.Manifest.permission#REBOOT} permission.
701     * </p>
702     *
703     * @param reason code to pass to the kernel (e.g., "recovery") to
704     *               request special boot modes, or null.
705     */
706    public void reboot(String reason) {
707        try {
708            mService.reboot(false, reason, true);
709        } catch (RemoteException e) {
710        }
711    }
712
713    /**
714     * Returns true if the device is currently in power save mode.  When in this mode,
715     * applications should reduce their functionality in order to conserve battery as
716     * much as possible.  You can monitor for changes to this state with
717     * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
718     *
719     * @return Returns true if currently in low power mode, else false.
720     */
721    public boolean isPowerSaveMode() {
722        try {
723            return mService.isPowerSaveMode();
724        } catch (RemoteException e) {
725            return false;
726        }
727    }
728
729    /**
730     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
731     * This broadcast is only sent to registered receivers.
732     */
733    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
734    public static final String ACTION_POWER_SAVE_MODE_CHANGED
735            = "android.os.action.POWER_SAVE_MODE_CHANGED";
736
737    /**
738     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
739     * This broadcast is only sent to registered receivers.
740     *
741     * @hide
742     */
743    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
744    public static final String ACTION_POWER_SAVE_MODE_CHANGING
745            = "android.os.action.POWER_SAVE_MODE_CHANGING";
746
747    /** @hide */
748    public static final String EXTRA_POWER_SAVE_MODE = "mode";
749
750    /**
751     * A wake lock is a mechanism to indicate that your application needs
752     * to have the device stay on.
753     * <p>
754     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
755     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
756     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
757     * </p><p>
758     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
759     * on at the level that was requested when the wake lock was created.
760     * </p><p>
761     * Call {@link #release()} when you are done and don't need the lock anymore.
762     * It is very important to do this as soon as possible to avoid running down the
763     * device's battery excessively.
764     * </p>
765     */
766    public final class WakeLock {
767        private int mFlags;
768        private String mTag;
769        private final String mPackageName;
770        private final IBinder mToken;
771        private int mCount;
772        private boolean mRefCounted = true;
773        private boolean mHeld;
774        private WorkSource mWorkSource;
775        private String mHistoryTag;
776        private final String mTraceName;
777
778        private final Runnable mReleaser = new Runnable() {
779            public void run() {
780                release();
781            }
782        };
783
784        WakeLock(int flags, String tag, String packageName) {
785            mFlags = flags;
786            mTag = tag;
787            mPackageName = packageName;
788            mToken = new Binder();
789            mTraceName = "WakeLock (" + mTag + ")";
790        }
791
792        @Override
793        protected void finalize() throws Throwable {
794            synchronized (mToken) {
795                if (mHeld) {
796                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
797                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
798                    try {
799                        mService.releaseWakeLock(mToken, 0);
800                    } catch (RemoteException e) {
801                    }
802                }
803            }
804        }
805
806        /**
807         * Sets whether this WakeLock is reference counted.
808         * <p>
809         * Wake locks are reference counted by default.  If a wake lock is
810         * reference counted, then each call to {@link #acquire()} must be
811         * balanced by an equal number of calls to {@link #release()}.  If a wake
812         * lock is not reference counted, then one call to {@link #release()} is
813         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
814         * </p>
815         *
816         * @param value True to make the wake lock reference counted, false to
817         * make the wake lock non-reference counted.
818         */
819        public void setReferenceCounted(boolean value) {
820            synchronized (mToken) {
821                mRefCounted = value;
822            }
823        }
824
825        /**
826         * Acquires the wake lock.
827         * <p>
828         * Ensures that the device is on at the level requested when
829         * the wake lock was created.
830         * </p>
831         */
832        public void acquire() {
833            synchronized (mToken) {
834                acquireLocked();
835            }
836        }
837
838        /**
839         * Acquires the wake lock with a timeout.
840         * <p>
841         * Ensures that the device is on at the level requested when
842         * the wake lock was created.  The lock will be released after the given timeout
843         * expires.
844         * </p>
845         *
846         * @param timeout The timeout after which to release the wake lock, in milliseconds.
847         */
848        public void acquire(long timeout) {
849            synchronized (mToken) {
850                acquireLocked();
851                mHandler.postDelayed(mReleaser, timeout);
852            }
853        }
854
855        private void acquireLocked() {
856            if (!mRefCounted || mCount++ == 0) {
857                // Do this even if the wake lock is already thought to be held (mHeld == true)
858                // because non-reference counted wake locks are not always properly released.
859                // For example, the keyguard's wake lock might be forcibly released by the
860                // power manager without the keyguard knowing.  A subsequent call to acquire
861                // should immediately acquire the wake lock once again despite never having
862                // been explicitly released by the keyguard.
863                mHandler.removeCallbacks(mReleaser);
864                Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
865                try {
866                    mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
867                            mHistoryTag);
868                } catch (RemoteException e) {
869                }
870                mHeld = true;
871            }
872        }
873
874        /**
875         * Releases the wake lock.
876         * <p>
877         * This method releases your claim to the CPU or screen being on.
878         * The screen may turn off shortly after you release the wake lock, or it may
879         * not if there are other wake locks still held.
880         * </p>
881         */
882        public void release() {
883            release(0);
884        }
885
886        /**
887         * Releases the wake lock with flags to modify the release behavior.
888         * <p>
889         * This method releases your claim to the CPU or screen being on.
890         * The screen may turn off shortly after you release the wake lock, or it may
891         * not if there are other wake locks still held.
892         * </p>
893         *
894         * @param flags Combination of flag values to modify the release behavior.
895         * Currently only {@link #WAIT_FOR_PROXIMITY_NEGATIVE} is supported.
896         *
897         * {@hide}
898         */
899        public void release(int flags) {
900            synchronized (mToken) {
901                if (!mRefCounted || --mCount == 0) {
902                    mHandler.removeCallbacks(mReleaser);
903                    if (mHeld) {
904                        Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
905                        try {
906                            mService.releaseWakeLock(mToken, flags);
907                        } catch (RemoteException e) {
908                        }
909                        mHeld = false;
910                    }
911                }
912                if (mCount < 0) {
913                    throw new RuntimeException("WakeLock under-locked " + mTag);
914                }
915            }
916        }
917
918        /**
919         * Returns true if the wake lock has been acquired but not yet released.
920         *
921         * @return True if the wake lock is held.
922         */
923        public boolean isHeld() {
924            synchronized (mToken) {
925                return mHeld;
926            }
927        }
928
929        /**
930         * Sets the work source associated with the wake lock.
931         * <p>
932         * The work source is used to determine on behalf of which application
933         * the wake lock is being held.  This is useful in the case where a
934         * service is performing work on behalf of an application so that the
935         * cost of that work can be accounted to the application.
936         * </p>
937         *
938         * @param ws The work source, or null if none.
939         */
940        public void setWorkSource(WorkSource ws) {
941            synchronized (mToken) {
942                if (ws != null && ws.size() == 0) {
943                    ws = null;
944                }
945
946                final boolean changed;
947                if (ws == null) {
948                    changed = mWorkSource != null;
949                    mWorkSource = null;
950                } else if (mWorkSource == null) {
951                    changed = true;
952                    mWorkSource = new WorkSource(ws);
953                } else {
954                    changed = mWorkSource.diff(ws);
955                    if (changed) {
956                        mWorkSource.set(ws);
957                    }
958                }
959
960                if (changed && mHeld) {
961                    try {
962                        mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
963                    } catch (RemoteException e) {
964                    }
965                }
966            }
967        }
968
969        /** @hide */
970        public void setTag(String tag) {
971            mTag = tag;
972        }
973
974        /** @hide */
975        public void setHistoryTag(String tag) {
976            mHistoryTag = tag;
977        }
978
979        /** @hide */
980        public void setUnimportantForLogging(boolean state) {
981            if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
982            else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
983        }
984
985        @Override
986        public String toString() {
987            synchronized (mToken) {
988                return "WakeLock{"
989                    + Integer.toHexString(System.identityHashCode(this))
990                    + " held=" + mHeld + ", refCount=" + mCount + "}";
991            }
992        }
993    }
994}
995