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