PowerManager.java revision 3d658bf20e2d56e36941e7407deebeec1276fbcf
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     * Mask for the wake lock level component of a combined wake lock level and flags integer.
195     *
196     * @hide
197     */
198    public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
199
200    /**
201     * Wake lock flag: Turn the screen on when the wake lock is acquired.
202     * <p>
203     * Normally wake locks don't actually wake the device, they just cause
204     * the screen to remain on once it's already on.  Think of the video player
205     * application as the normal behavior.  Notifications that pop up and want
206     * the device to be on are the exception; use this flag to be like them.
207     * </p><p>
208     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
209     * </p>
210     */
211    public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
212
213    /**
214     * Wake lock flag: When this wake lock is released, poke the user activity timer
215     * so the screen stays on for a little longer.
216     * <p>
217     * Will not turn the screen on if it is not already on.
218     * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
219     * </p><p>
220     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
221     * </p>
222     */
223    public static final int ON_AFTER_RELEASE = 0x20000000;
224
225    /**
226     * Wake lock flag: This wake lock is not important for logging events.  If a later
227     * wake lock is acquired that is important, it will be considered the one to log.
228     * @hide
229     */
230    public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
231
232    /**
233     * Flag for {@link WakeLock#release release(int)} to defer releasing a
234     * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor returns
235     * a negative value.
236     *
237     * {@hide}
238     */
239    public static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1;
240
241    /**
242     * Brightness value for fully on.
243     * @hide
244     */
245    public static final int BRIGHTNESS_ON = 255;
246
247    /**
248     * Brightness value for fully off.
249     * @hide
250     */
251    public static final int BRIGHTNESS_OFF = 0;
252
253    // Note: Be sure to update android.os.BatteryStats and PowerManager.h
254    // if adding or modifying user activity event constants.
255
256    /**
257     * User activity event type: Unspecified event type.
258     * @hide
259     */
260    public static final int USER_ACTIVITY_EVENT_OTHER = 0;
261
262    /**
263     * User activity event type: Button or key pressed or released.
264     * @hide
265     */
266    public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
267
268    /**
269     * User activity event type: Touch down, move or up.
270     * @hide
271     */
272    public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
273
274    /**
275     * User activity flag: Do not restart the user activity timeout or brighten
276     * the display in response to user activity if it is already dimmed.
277     * @hide
278     */
279    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
280
281    /**
282     * Go to sleep reason code: Going to sleep due by user request.
283     * @hide
284     */
285    public static final int GO_TO_SLEEP_REASON_USER = 0;
286
287    /**
288     * Go to sleep reason code: Going to sleep due by request of the
289     * device administration policy.
290     * @hide
291     */
292    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
293
294    /**
295     * Go to sleep reason code: Going to sleep due to a screen timeout.
296     * @hide
297     */
298    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
299
300    /**
301     * The value to pass as the 'reason' argument to reboot() to
302     * reboot into recovery mode (for applying system updates, doing
303     * factory resets, etc.).
304     * <p>
305     * Requires the {@link android.Manifest.permission#RECOVERY}
306     * permission (in addition to
307     * {@link android.Manifest.permission#REBOOT}).
308     * </p>
309     */
310    public static final String REBOOT_RECOVERY = "recovery";
311
312    final Context mContext;
313    final IPowerManager mService;
314    final Handler mHandler;
315
316    /**
317     * {@hide}
318     */
319    public PowerManager(Context context, IPowerManager service, Handler handler) {
320        mContext = context;
321        mService = service;
322        mHandler = handler;
323    }
324
325    /**
326     * Gets the minimum supported screen brightness setting.
327     * The screen may be allowed to become dimmer than this value but
328     * this is the minimum value that can be set by the user.
329     * @hide
330     */
331    public int getMinimumScreenBrightnessSetting() {
332        return mContext.getResources().getInteger(
333                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
334    }
335
336    /**
337     * Gets the maximum supported screen brightness setting.
338     * The screen may be allowed to become dimmer than this value but
339     * this is the maximum value that can be set by the user.
340     * @hide
341     */
342    public int getMaximumScreenBrightnessSetting() {
343        return mContext.getResources().getInteger(
344                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
345    }
346
347    /**
348     * Gets the default screen brightness setting.
349     * @hide
350     */
351    public int getDefaultScreenBrightnessSetting() {
352        return mContext.getResources().getInteger(
353                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
354    }
355
356    /**
357     * Returns true if the screen auto-brightness adjustment setting should
358     * be available in the UI.  This setting is experimental and disabled by default.
359     * @hide
360     */
361    public static boolean useScreenAutoBrightnessAdjustmentFeature() {
362        return SystemProperties.getBoolean("persist.power.useautobrightadj", false);
363    }
364
365    /**
366     * Returns true if the twilight service should be used to adjust screen brightness
367     * policy.  This setting is experimental and disabled by default.
368     * @hide
369     */
370    public static boolean useTwilightAdjustmentFeature() {
371        return SystemProperties.getBoolean("persist.power.usetwilightadj", false);
372    }
373
374    /**
375     * Creates a new wake lock with the specified level and flags.
376     * <p>
377     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
378     * combined using the logical OR operator.
379     * </p><p>
380     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
381     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
382     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
383     * specified as part of the {@code levelAndFlags} parameter.
384     * </p><p>
385     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
386     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
387     * {@code levelAndFlags} parameters.
388     * </p><p>
389     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
390     * wake lock, and {@link WakeLock#release release()} when you are done.
391     * </p><p>
392     * {@samplecode
393     * PowerManager pm = (PowerManager)mContext.getSystemService(
394     *                                          Context.POWER_SERVICE);
395     * PowerManager.WakeLock wl = pm.newWakeLock(
396     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
397     *                                      | PowerManager.ON_AFTER_RELEASE,
398     *                                      TAG);
399     * wl.acquire();
400     * // ... do work...
401     * wl.release();
402     * }
403     * </p><p>
404     * Although a wake lock can be created without special permissions,
405     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
406     * required to actually acquire or release the wake lock that is returned.
407     * </p><p class="note">
408     * If using this to keep the screen on, you should strongly consider using
409     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
410     * This window flag will be correctly managed by the platform
411     * as the user moves between applications and doesn't require a special permission.
412     * </p>
413     *
414     * @param levelAndFlags Combination of wake lock level and flag values defining
415     * the requested behavior of the WakeLock.
416     * @param tag Your class name (or other tag) for debugging purposes.
417     *
418     * @see WakeLock#acquire()
419     * @see WakeLock#release()
420     * @see #PARTIAL_WAKE_LOCK
421     * @see #FULL_WAKE_LOCK
422     * @see #SCREEN_DIM_WAKE_LOCK
423     * @see #SCREEN_BRIGHT_WAKE_LOCK
424     * @see #ACQUIRE_CAUSES_WAKEUP
425     * @see #ON_AFTER_RELEASE
426     */
427    public WakeLock newWakeLock(int levelAndFlags, String tag) {
428        validateWakeLockParameters(levelAndFlags, tag);
429        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
430    }
431
432    /** @hide */
433    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
434        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
435            case PARTIAL_WAKE_LOCK:
436            case SCREEN_DIM_WAKE_LOCK:
437            case SCREEN_BRIGHT_WAKE_LOCK:
438            case FULL_WAKE_LOCK:
439            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
440                break;
441            default:
442                throw new IllegalArgumentException("Must specify a valid wake lock level.");
443        }
444        if (tag == null) {
445            throw new IllegalArgumentException("The tag must not be null.");
446        }
447    }
448
449    /**
450     * Notifies the power manager that user activity happened.
451     * <p>
452     * Resets the auto-off timer and brightens the screen if the device
453     * is not asleep.  This is what happens normally when a key or the touch
454     * screen is pressed or when some other user activity occurs.
455     * This method does not wake up the device if it has been put to sleep.
456     * </p><p>
457     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
458     * </p>
459     *
460     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
461     * time base.  This timestamp is used to correctly order the user activity request with
462     * other power management functions.  It should be set
463     * to the timestamp of the input event that caused the user activity.
464     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
465     * because of this event.  This is set when the power key is pressed.
466     * We want the device to stay on while the button is down, but we're about
467     * to turn off the screen so we don't want the keyboard backlight to turn on again.
468     * Otherwise the lights flash on and then off and it looks weird.
469     *
470     * @see #wakeUp
471     * @see #goToSleep
472     */
473    public void userActivity(long when, boolean noChangeLights) {
474        try {
475            mService.userActivity(when, USER_ACTIVITY_EVENT_OTHER,
476                    noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
477        } catch (RemoteException e) {
478        }
479    }
480
481   /**
482     * Forces the device to go to sleep.
483     * <p>
484     * Overrides all the wake locks that are held.
485     * This is what happens when the power key is pressed to turn off the screen.
486     * </p><p>
487     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
488     * </p>
489     *
490     * @param time The time when the request to go to sleep was issued, in the
491     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
492     * order the go to sleep request with other power management functions.  It should be set
493     * to the timestamp of the input event that caused the request to go to sleep.
494     *
495     * @see #userActivity
496     * @see #wakeUp
497     */
498    public void goToSleep(long time) {
499        try {
500            mService.goToSleep(time, GO_TO_SLEEP_REASON_USER);
501        } catch (RemoteException e) {
502        }
503    }
504
505    /**
506     * Forces the device to wake up from sleep.
507     * <p>
508     * If the device is currently asleep, wakes it up, otherwise does nothing.
509     * This is what happens when the power key is pressed to turn on the screen.
510     * </p><p>
511     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
512     * </p>
513     *
514     * @param time The time when the request to wake up was issued, in the
515     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
516     * order the wake up request with other power management functions.  It should be set
517     * to the timestamp of the input event that caused the request to wake up.
518     *
519     * @see #userActivity
520     * @see #goToSleep
521     */
522    public void wakeUp(long time) {
523        try {
524            mService.wakeUp(time);
525        } catch (RemoteException e) {
526        }
527    }
528
529    /**
530     * Forces the device to start napping.
531     * <p>
532     * If the device is currently awake, starts dreaming, otherwise does nothing.
533     * When the dream ends or if the dream cannot be started, the device will
534     * either wake up or go to sleep depending on whether there has been recent
535     * user activity.
536     * </p><p>
537     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
538     * </p>
539     *
540     * @param time The time when the request to nap was issued, in the
541     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
542     * order the nap request with other power management functions.  It should be set
543     * to the timestamp of the input event that caused the request to nap.
544     *
545     * @see #wakeUp
546     * @see #goToSleep
547     *
548     * @hide
549     */
550    public void nap(long time) {
551        try {
552            mService.nap(time);
553        } catch (RemoteException e) {
554        }
555    }
556
557    /**
558     * Sets the brightness of the backlights (screen, keyboard, button).
559     * <p>
560     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
561     * </p>
562     *
563     * @param brightness The brightness value from 0 to 255.
564     *
565     * {@hide}
566     */
567    public void setBacklightBrightness(int brightness) {
568        try {
569            mService.setTemporaryScreenBrightnessSettingOverride(brightness);
570        } catch (RemoteException e) {
571        }
572    }
573
574   /**
575     * Returns true if the specified wake lock level is supported.
576     *
577     * @param level The wake lock level to check.
578     * @return True if the specified wake lock level is supported.
579     *
580     * {@hide}
581     */
582    public boolean isWakeLockLevelSupported(int level) {
583        try {
584            return mService.isWakeLockLevelSupported(level);
585        } catch (RemoteException e) {
586            return false;
587        }
588    }
589
590    /**
591      * Returns whether the screen is currently on.
592      * <p>
593      * Only indicates whether the screen is on.  The screen could be either bright or dim.
594      * </p><p>
595      * {@samplecode
596      * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
597      * boolean isScreenOn = pm.isScreenOn();
598      * }
599      * </p>
600      *
601      * @return whether the screen is on (bright or dim).
602      */
603    public boolean isScreenOn() {
604        try {
605            return mService.isScreenOn();
606        } catch (RemoteException e) {
607            return false;
608        }
609    }
610
611    /**
612     * Reboot the device.  Will not return if the reboot is successful.
613     * <p>
614     * Requires the {@link android.Manifest.permission#REBOOT} permission.
615     * </p>
616     *
617     * @param reason code to pass to the kernel (e.g., "recovery") to
618     *               request special boot modes, or null.
619     */
620    public void reboot(String reason) {
621        try {
622            mService.reboot(false, reason, true);
623        } catch (RemoteException e) {
624        }
625    }
626
627    /**
628     * A wake lock is a mechanism to indicate that your application needs
629     * to have the device stay on.
630     * <p>
631     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
632     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
633     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
634     * </p><p>
635     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
636     * on at the level that was requested when the wake lock was created.
637     * </p><p>
638     * Call {@link #release()} when you are done and don't need the lock anymore.
639     * It is very important to do this as soon as possible to avoid running down the
640     * device's battery excessively.
641     * </p>
642     */
643    public final class WakeLock {
644        private int mFlags;
645        private String mTag;
646        private final String mPackageName;
647        private final IBinder mToken;
648        private int mCount;
649        private boolean mRefCounted = true;
650        private boolean mHeld;
651        private WorkSource mWorkSource;
652
653        private final Runnable mReleaser = new Runnable() {
654            public void run() {
655                release();
656            }
657        };
658
659        WakeLock(int flags, String tag, String packageName) {
660            mFlags = flags;
661            mTag = tag;
662            mPackageName = packageName;
663            mToken = new Binder();
664        }
665
666        @Override
667        protected void finalize() throws Throwable {
668            synchronized (mToken) {
669                if (mHeld) {
670                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
671                    try {
672                        mService.releaseWakeLock(mToken, 0);
673                    } catch (RemoteException e) {
674                    }
675                }
676            }
677        }
678
679        /**
680         * Sets whether this WakeLock is reference counted.
681         * <p>
682         * Wake locks are reference counted by default.  If a wake lock is
683         * reference counted, then each call to {@link #acquire()} must be
684         * balanced by an equal number of calls to {@link #release()}.  If a wake
685         * lock is not reference counted, then one call to {@link #release()} is
686         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
687         * </p>
688         *
689         * @param value True to make the wake lock reference counted, false to
690         * make the wake lock non-reference counted.
691         */
692        public void setReferenceCounted(boolean value) {
693            synchronized (mToken) {
694                mRefCounted = value;
695            }
696        }
697
698        /**
699         * Acquires the wake lock.
700         * <p>
701         * Ensures that the device is on at the level requested when
702         * the wake lock was created.
703         * </p>
704         */
705        public void acquire() {
706            synchronized (mToken) {
707                acquireLocked();
708            }
709        }
710
711        /**
712         * Acquires the wake lock with a timeout.
713         * <p>
714         * Ensures that the device is on at the level requested when
715         * the wake lock was created.  The lock will be released after the given timeout
716         * expires.
717         * </p>
718         *
719         * @param timeout The timeout after which to release the wake lock, in milliseconds.
720         */
721        public void acquire(long timeout) {
722            synchronized (mToken) {
723                acquireLocked();
724                mHandler.postDelayed(mReleaser, timeout);
725            }
726        }
727
728        private void acquireLocked() {
729            if (!mRefCounted || mCount++ == 0) {
730                // Do this even if the wake lock is already thought to be held (mHeld == true)
731                // because non-reference counted wake locks are not always properly released.
732                // For example, the keyguard's wake lock might be forcibly released by the
733                // power manager without the keyguard knowing.  A subsequent call to acquire
734                // should immediately acquire the wake lock once again despite never having
735                // been explicitly released by the keyguard.
736                mHandler.removeCallbacks(mReleaser);
737                try {
738                    mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource);
739                } catch (RemoteException e) {
740                }
741                mHeld = true;
742            }
743        }
744
745        /**
746         * Releases the wake lock.
747         * <p>
748         * This method releases your claim to the CPU or screen being on.
749         * The screen may turn off shortly after you release the wake lock, or it may
750         * not if there are other wake locks still held.
751         * </p>
752         */
753        public void release() {
754            release(0);
755        }
756
757        /**
758         * Releases the wake lock with flags to modify the release behavior.
759         * <p>
760         * This method releases your claim to the CPU or screen being on.
761         * The screen may turn off shortly after you release the wake lock, or it may
762         * not if there are other wake locks still held.
763         * </p>
764         *
765         * @param flags Combination of flag values to modify the release behavior.
766         * Currently only {@link #WAIT_FOR_PROXIMITY_NEGATIVE} is supported.
767         *
768         * {@hide}
769         */
770        public void release(int flags) {
771            synchronized (mToken) {
772                if (!mRefCounted || --mCount == 0) {
773                    mHandler.removeCallbacks(mReleaser);
774                    if (mHeld) {
775                        try {
776                            mService.releaseWakeLock(mToken, flags);
777                        } catch (RemoteException e) {
778                        }
779                        mHeld = false;
780                    }
781                }
782                if (mCount < 0) {
783                    throw new RuntimeException("WakeLock under-locked " + mTag);
784                }
785            }
786        }
787
788        /**
789         * Returns true if the wake lock has been acquired but not yet released.
790         *
791         * @return True if the wake lock is held.
792         */
793        public boolean isHeld() {
794            synchronized (mToken) {
795                return mHeld;
796            }
797        }
798
799        /**
800         * Sets the work source associated with the wake lock.
801         * <p>
802         * The work source is used to determine on behalf of which application
803         * the wake lock is being held.  This is useful in the case where a
804         * service is performing work on behalf of an application so that the
805         * cost of that work can be accounted to the application.
806         * </p>
807         *
808         * @param ws The work source, or null if none.
809         */
810        public void setWorkSource(WorkSource ws) {
811            synchronized (mToken) {
812                if (ws != null && ws.size() == 0) {
813                    ws = null;
814                }
815
816                final boolean changed;
817                if (ws == null) {
818                    changed = mWorkSource != null;
819                    mWorkSource = null;
820                } else if (mWorkSource == null) {
821                    changed = true;
822                    mWorkSource = new WorkSource(ws);
823                } else {
824                    changed = mWorkSource.diff(ws);
825                    if (changed) {
826                        mWorkSource.set(ws);
827                    }
828                }
829
830                if (changed && mHeld) {
831                    try {
832                        mService.updateWakeLockWorkSource(mToken, mWorkSource);
833                    } catch (RemoteException e) {
834                    }
835                }
836            }
837        }
838
839        /** @hide */
840        public void setTag(String tag) {
841            mTag = tag;
842        }
843
844        /** @hide */
845        public void setUnimportantForLogging(boolean state) {
846            if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
847            else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
848        }
849
850        @Override
851        public String toString() {
852            synchronized (mToken) {
853                return "WakeLock{"
854                    + Integer.toHexString(System.identityHashCode(this))
855                    + " held=" + mHeld + ", refCount=" + mCount + "}";
856            }
857        }
858    }
859}
860