PowerManager.java revision b9b56954ec5a242f7c4945942539106539f98ffb
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 border="2" width="85%" align="center" frame="hsides" rules="rows">
50 *     <thead>
51 *     <tr><th>Flag Value</th>
52 *     <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
53 *     </thead>
54 *
55 *     <tbody>
56 *     <tr><th>{@link #PARTIAL_WAKE_LOCK}</th>
57 *         <td>On*</td> <td>Off</td> <td>Off</td>
58 *     </tr>
59 *
60 *     <tr><th>{@link #SCREEN_DIM_WAKE_LOCK}</th>
61 *         <td>On</td> <td>Dim</td> <td>Off</td>
62 *     </tr>
63 *
64 *     <tr><th>{@link #SCREEN_BRIGHT_WAKE_LOCK}</th>
65 *         <td>On</td> <td>Bright</td> <td>Off</td>
66 *     </tr>
67 *
68 *     <tr><th>{@link #FULL_WAKE_LOCK}</th>
69 *         <td>On</td> <td>Bright</td> <td>Bright</td>
70 *     </tr>
71 *     </tbody>
72 * </table>
73 * </p><p>
74 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
75 * display timeouts or the state of the screen and even after the user presses the power button.
76 * In all other wake locks, the CPU will run, but the user can still put the device to sleep
77 * using the power button.</i>
78 * </p><p>
79 * In addition, you can add two more flags, which affect behavior of the screen only.
80 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i>
81 *
82 * <table border="2" width="85%" align="center" frame="hsides" rules="rows">
83 *     <thead>
84 *     <tr><th>Flag Value</th> <th>Description</th></tr>
85 *     </thead>
86 *
87 *     <tbody>
88 *     <tr><th>{@link #ACQUIRE_CAUSES_WAKEUP}</th>
89 *         <td>Normal wake locks don't actually turn on the illumination.  Instead, they cause
90 *         the illumination to remain on once it turns on (e.g. from user activity).  This flag
91 *         will force the screen and/or keyboard to turn on immediately, when the WakeLock is
92 *         acquired.  A typical use would be for notifications which are important for the user to
93 *         see immediately.</td>
94 *     </tr>
95 *
96 *     <tr><th>{@link #ON_AFTER_RELEASE}</th>
97 *         <td>If this flag is set, the user activity timer will be reset when the WakeLock is
98 *         released, causing the illumination to remain on a bit longer.  This can be used to
99 *         reduce flicker if you are cycling between wake lock conditions.</td>
100 *     </tr>
101 *     </tbody>
102 * </table>
103 * </p><p>
104 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
105 * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
106 * </p>
107 */
108public final class PowerManager {
109    private static final String TAG = "PowerManager";
110
111    /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
112     * combinations were actually supported so the bit field was removed.  This explains
113     * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
114     * value can be used.
115     */
116
117    /**
118     * Wake lock level: Ensures that the CPU is running; the screen and keyboard
119     * backlight will be allowed to go off.
120     * <p>
121     * If the user presses the power button, then the screen will be turned off
122     * but the CPU will be kept on until all partial wake locks have been released.
123     * </p>
124     */
125    public static final int PARTIAL_WAKE_LOCK = 0x00000001;
126
127    /**
128     * Wake lock level: Ensures that the screen is on (but may be dimmed);
129     * the keyboard backlight will be allowed to go off.
130     * <p>
131     * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
132     * implicitly released by the system, causing both the screen and the CPU to be turned off.
133     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
134     * </p>
135     *
136     * @deprecated Most applications should use
137     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
138     * of this type of wake lock, as it will be correctly managed by the platform
139     * as the user moves between applications and doesn't require a special permission.
140     */
141    @Deprecated
142    public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;
143
144    /**
145     * Wake lock level: Ensures that the screen is on at full brightness;
146     * the keyboard backlight will be allowed to go off.
147     * <p>
148     * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
149     * implicitly released by the system, causing both the screen and the CPU to be turned off.
150     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
151     * </p>
152     *
153     * @deprecated Most applications should use
154     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
155     * of this type of wake lock, as it will be correctly managed by the platform
156     * as the user moves between applications and doesn't require a special permission.
157     */
158    @Deprecated
159    public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a;
160
161    /**
162     * Wake lock level: Ensures that the screen and keyboard backlight are on at
163     * full brightness.
164     * <p>
165     * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
166     * implicitly released by the system, causing both the screen and the CPU to be turned off.
167     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
168     * </p>
169     *
170     * @deprecated Most applications should use
171     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
172     * of this type of wake lock, as it will be correctly managed by the platform
173     * as the user moves between applications and doesn't require a special permission.
174     */
175    @Deprecated
176    public static final int FULL_WAKE_LOCK = 0x0000001a;
177
178    /**
179     * Wake lock level: Turns the screen off when the proximity sensor activates.
180     * <p>
181     * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
182     * to determine whether this wake lock level is supported.
183     * </p>
184     *
185     * {@hide}
186     */
187    public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020;
188
189    /**
190     * Mask for the wake lock level component of a combined wake lock level and flags integer.
191     *
192     * @hide
193     */
194    public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
195
196    /**
197     * Wake lock flag: Turn the screen on when the wake lock is acquired.
198     * <p>
199     * Normally wake locks don't actually wake the device, they just cause
200     * the screen to remain on once it's already on.  Think of the video player
201     * application as the normal behavior.  Notifications that pop up and want
202     * the device to be on are the exception; use this flag to be like them.
203     * </p><p>
204     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
205     * </p>
206     */
207    public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
208
209    /**
210     * Wake lock flag: When this wake lock is released, poke the user activity timer
211     * so the screen stays on for a little longer.
212     * <p>
213     * Will not turn the screen on if it is not already on.
214     * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
215     * </p><p>
216     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
217     * </p>
218     */
219    public static final int ON_AFTER_RELEASE = 0x20000000;
220
221    /**
222     * Flag for {@link WakeLock#release release(int)} to defer releasing a
223     * {@link #WAKE_BIT_PROXIMITY_SCREEN_OFF} wake lock until the proximity sensor returns
224     * a negative value.
225     *
226     * {@hide}
227     */
228    public static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1;
229
230    /**
231     * Brightness value for fully on.
232     * @hide
233     */
234    public static final int BRIGHTNESS_ON = 255;
235
236    /**
237     * Brightness value for fully off.
238     * @hide
239     */
240    public static final int BRIGHTNESS_OFF = 0;
241
242    // Note: Be sure to update android.os.BatteryStats and PowerManager.h
243    // if adding or modifying user activity event constants.
244
245    /**
246     * User activity event type: Unspecified event type.
247     * @hide
248     */
249    public static final int USER_ACTIVITY_EVENT_OTHER = 0;
250
251    /**
252     * User activity event type: Button or key pressed or released.
253     * @hide
254     */
255    public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
256
257    /**
258     * User activity event type: Touch down, move or up.
259     * @hide
260     */
261    public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
262
263    /**
264     * User activity flag: Do not restart the user activity timeout or brighten
265     * the display in response to user activity if it is already dimmed.
266     * @hide
267     */
268    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
269
270    /**
271     * Go to sleep reason code: Going to sleep due by user request.
272     * @hide
273     */
274    public static final int GO_TO_SLEEP_REASON_USER = 0;
275
276    /**
277     * Go to sleep reason code: Going to sleep due by request of the
278     * device administration policy.
279     * @hide
280     */
281    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
282
283    /**
284     * Go to sleep reason code: Going to sleep due to a screen timeout.
285     * @hide
286     */
287    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
288
289    final Context mContext;
290    final IPowerManager mService;
291    final Handler mHandler;
292
293    /**
294     * {@hide}
295     */
296    public PowerManager(Context context, IPowerManager service, Handler handler) {
297        mContext = context;
298        mService = service;
299        mHandler = handler;
300    }
301
302    /**
303     * Gets the minimum supported screen brightness setting.
304     * The screen may be allowed to become dimmer than this value but
305     * this is the minimum value that can be set by the user.
306     * @hide
307     */
308    public int getMinimumScreenBrightnessSetting() {
309        return mContext.getResources().getInteger(
310                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
311    }
312
313    /**
314     * Gets the maximum supported screen brightness setting.
315     * The screen may be allowed to become dimmer than this value but
316     * this is the maximum value that can be set by the user.
317     * @hide
318     */
319    public int getMaximumScreenBrightnessSetting() {
320        return mContext.getResources().getInteger(
321                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
322    }
323
324    /**
325     * Gets the default screen brightness setting.
326     * @hide
327     */
328    public int getDefaultScreenBrightnessSetting() {
329        return mContext.getResources().getInteger(
330                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
331    }
332
333    /**
334     * Creates a new wake lock with the specified level and flags.
335     * <p>
336     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
337     * combined using the logical OR operator.
338     * </p><p>
339     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
340     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
341     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
342     * specified as part of the {@code levelAndFlags} parameter.
343     * </p><p>
344     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
345     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
346     * {@code levelAndFlags} parameters.
347     * </p><p>
348     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
349     * wake lock, and {@link WakeLock#release release()} when you are done.
350     * </p><p>
351     * {@samplecode
352     * PowerManager pm = (PowerManager)mContext.getSystemService(
353     *                                          Context.POWER_SERVICE);
354     * PowerManager.WakeLock wl = pm.newWakeLock(
355     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
356     *                                      | PowerManager.ON_AFTER_RELEASE,
357     *                                      TAG);
358     * wl.acquire();
359     * // ... do work...
360     * wl.release();
361     * }
362     * </p><p>
363     * Although a wake lock can be created without special permissions,
364     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
365     * required to actually acquire or release the wake lock that is returned.
366     * </p><p class="note">
367     * If using this to keep the screen on, you should strongly consider using
368     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
369     * This window flag will be correctly managed by the platform
370     * as the user moves between applications and doesn't require a special permission.
371     * </p>
372     *
373     * @param levelAndFlags Combination of wake lock level and flag values defining
374     * the requested behavior of the WakeLock.
375     * @param tag Your class name (or other tag) for debugging purposes.
376     *
377     * @see WakeLock#acquire()
378     * @see WakeLock#release()
379     * @see #PARTIAL_WAKE_LOCK
380     * @see #FULL_WAKE_LOCK
381     * @see #SCREEN_DIM_WAKE_LOCK
382     * @see #SCREEN_BRIGHT_WAKE_LOCK
383     * @see #ACQUIRE_CAUSES_WAKEUP
384     * @see #ON_AFTER_RELEASE
385     */
386    public WakeLock newWakeLock(int levelAndFlags, String tag) {
387        validateWakeLockParameters(levelAndFlags, tag);
388        return new WakeLock(levelAndFlags, tag);
389    }
390
391    /** @hide */
392    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
393        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
394            case PARTIAL_WAKE_LOCK:
395            case SCREEN_DIM_WAKE_LOCK:
396            case SCREEN_BRIGHT_WAKE_LOCK:
397            case FULL_WAKE_LOCK:
398            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
399                break;
400            default:
401                throw new IllegalArgumentException("Must specify a valid wake lock level.");
402        }
403        if (tag == null) {
404            throw new IllegalArgumentException("The tag must not be null.");
405        }
406    }
407
408    /**
409     * Notifies the power manager that user activity happened.
410     * <p>
411     * Resets the auto-off timer and brightens the screen if the device
412     * is not asleep.  This is what happens normally when a key or the touch
413     * screen is pressed or when some other user activity occurs.
414     * This method does not wake up the device if it has been put to sleep.
415     * </p><p>
416     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
417     * </p>
418     *
419     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
420     * time base.  This timestamp is used to correctly order the user activity with
421     * other power management functions.  It should be set
422     * to the timestamp of the input event that caused the user activity.
423     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
424     * because of this event.  This is set when the power key is pressed.
425     * We want the device to stay on while the button is down, but we're about
426     * to turn off the screen so we don't want the keyboard backlight to turn on again.
427     * Otherwise the lights flash on and then off and it looks weird.
428     *
429     * @see #wakeUp
430     * @see #goToSleep
431     */
432    public void userActivity(long when, boolean noChangeLights) {
433        try {
434            mService.userActivity(when, USER_ACTIVITY_EVENT_OTHER,
435                    noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
436        } catch (RemoteException e) {
437        }
438    }
439
440   /**
441     * Forces the device to go to sleep.
442     * <p>
443     * Overrides all the wake locks that are held.
444     * This is what happens when the power key is pressed to turn off the screen.
445     * </p><p>
446     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
447     * </p>
448     *
449     * @param time The time when the request to go to sleep was issued, in the
450     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
451     * order the user activity with other power management functions.  It should be set
452     * to the timestamp of the input event that caused the request to go to sleep.
453     *
454     * @see #userActivity
455     * @see #wakeUp
456     */
457    public void goToSleep(long time) {
458        try {
459            mService.goToSleep(time, GO_TO_SLEEP_REASON_USER);
460        } catch (RemoteException e) {
461        }
462    }
463
464    /**
465     * Forces the device to wake up from sleep.
466     * <p>
467     * If the device is currently asleep, wakes it up, otherwise does nothing.
468     * This is what happens when the power key is pressed to turn on the screen.
469     * </p><p>
470     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
471     * </p>
472     *
473     * @param time The time when the request to wake up was issued, in the
474     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
475     * order the user activity with other power management functions.  It should be set
476     * to the timestamp of the input event that caused the request to wake up.
477     *
478     * @see #userActivity
479     * @see #goToSleep
480     */
481    public void wakeUp(long time) {
482        try {
483            mService.wakeUp(time);
484        } catch (RemoteException e) {
485        }
486    }
487
488    /**
489     * Sets the brightness of the backlights (screen, keyboard, button).
490     * <p>
491     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
492     * </p>
493     *
494     * @param brightness The brightness value from 0 to 255.
495     *
496     * {@hide}
497     */
498    public void setBacklightBrightness(int brightness) {
499        try {
500            mService.setTemporaryScreenBrightnessSettingOverride(brightness);
501        } catch (RemoteException e) {
502        }
503    }
504
505   /**
506     * Returns true if the specified wake lock level is supported.
507     *
508     * @param level The wake lock level to check.
509     * @return True if the specified wake lock level is supported.
510     *
511     * {@hide}
512     */
513    public boolean isWakeLockLevelSupported(int level) {
514        try {
515            return mService.isWakeLockLevelSupported(level);
516        } catch (RemoteException e) {
517            return false;
518        }
519    }
520
521    /**
522      * Returns whether the screen is currently on.
523      * <p>
524      * Only indicates whether the screen is on.  The screen could be either bright or dim.
525      * </p><p>
526      * {@samplecode
527      * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
528      * boolean isScreenOn = pm.isScreenOn();
529      * }
530      * </p>
531      *
532      * @return whether the screen is on (bright or dim).
533      */
534    public boolean isScreenOn() {
535        try {
536            return mService.isScreenOn();
537        } catch (RemoteException e) {
538            return false;
539        }
540    }
541
542    /**
543     * Reboot the device.  Will not return if the reboot is successful.
544     * <p>
545     * Requires the {@link android.Manifest.permission#REBOOT} permission.
546     * </p>
547     *
548     * @param reason code to pass to the kernel (e.g., "recovery") to
549     *               request special boot modes, or null.
550     */
551    public void reboot(String reason) {
552        try {
553            mService.reboot(reason);
554        } catch (RemoteException e) {
555        }
556    }
557
558    /**
559     * A wake lock is a mechanism to indicate that your application needs
560     * to have the device stay on.
561     * <p>
562     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
563     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
564     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
565     * </p><p>
566     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
567     * on at the level that was requested when the wake lock was created.
568     * </p><p>
569     * Call {@link #release()} when you are done and don't need the lock anymore.
570     * It is very important to do this as soon as possible to avoid running down the
571     * device's battery excessively.
572     * </p>
573     */
574    public final class WakeLock {
575        private final int mFlags;
576        private final String mTag;
577        private final IBinder mToken;
578        private int mCount;
579        private boolean mRefCounted = true;
580        private boolean mHeld;
581        private WorkSource mWorkSource;
582
583        private final Runnable mReleaser = new Runnable() {
584            public void run() {
585                release();
586            }
587        };
588
589        WakeLock(int flags, String tag) {
590            mFlags = flags;
591            mTag = tag;
592            mToken = new Binder();
593        }
594
595        @Override
596        protected void finalize() throws Throwable {
597            synchronized (mToken) {
598                if (mHeld) {
599                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
600                    try {
601                        mService.releaseWakeLock(mToken, 0);
602                    } catch (RemoteException e) {
603                    }
604                }
605            }
606        }
607
608        /**
609         * Sets whether this WakeLock is reference counted.
610         * <p>
611         * Wake locks are reference counted by default.  If a wake lock is
612         * reference counted, then each call to {@link #acquire()} must be
613         * balanced by an equal number of calls to {@link #release()}.  If a wake
614         * lock is not reference counted, then one call to {@link #release()} is
615         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
616         * </p>
617         *
618         * @param value True to make the wake lock reference counted, false to
619         * make the wake lock non-reference counted.
620         */
621        public void setReferenceCounted(boolean value) {
622            synchronized (mToken) {
623                mRefCounted = value;
624            }
625        }
626
627        /**
628         * Acquires the wake lock.
629         * <p>
630         * Ensures that the device is on at the level requested when
631         * the wake lock was created.
632         * </p>
633         */
634        public void acquire() {
635            synchronized (mToken) {
636                acquireLocked();
637            }
638        }
639
640        /**
641         * Acquires the wake lock with a timeout.
642         * <p>
643         * Ensures that the device is on at the level requested when
644         * the wake lock was created.  The lock will be released after the given timeout
645         * expires.
646         * </p>
647         *
648         * @param timeout The timeout after which to release the wake lock, in milliseconds.
649         */
650        public void acquire(long timeout) {
651            synchronized (mToken) {
652                acquireLocked();
653                mHandler.postDelayed(mReleaser, timeout);
654            }
655        }
656
657        private void acquireLocked() {
658            if (!mRefCounted || mCount++ == 0) {
659                // Do this even if the wake lock is already thought to be held (mHeld == true)
660                // because non-reference counted wake locks are not always properly released.
661                // For example, the keyguard's wake lock might be forcibly released by the
662                // power manager without the keyguard knowing.  A subsequent call to acquire
663                // should immediately acquire the wake lock once again despite never having
664                // been explicitly released by the keyguard.
665                mHandler.removeCallbacks(mReleaser);
666                try {
667                    mService.acquireWakeLock(mToken, mFlags, mTag, mWorkSource);
668                } catch (RemoteException e) {
669                }
670                mHeld = true;
671            }
672        }
673
674        /**
675         * Releases the wake lock.
676         * <p>
677         * This method releases your claim to the CPU or screen being on.
678         * The screen may turn off shortly after you release the wake lock, or it may
679         * not if there are other wake locks still held.
680         * </p>
681         */
682        public void release() {
683            release(0);
684        }
685
686        /**
687         * Releases the wake lock with flags to modify the release behavior.
688         * <p>
689         * This method releases your claim to the CPU or screen being on.
690         * The screen may turn off shortly after you release the wake lock, or it may
691         * not if there are other wake locks still held.
692         * </p>
693         *
694         * @param flags Combination of flag values to modify the release behavior.
695         * Currently only {@link #WAIT_FOR_PROXIMITY_NEGATIVE} is supported.
696         *
697         * {@hide}
698         */
699        public void release(int flags) {
700            synchronized (mToken) {
701                if (!mRefCounted || --mCount == 0) {
702                    mHandler.removeCallbacks(mReleaser);
703                    if (mHeld) {
704                        try {
705                            mService.releaseWakeLock(mToken, flags);
706                        } catch (RemoteException e) {
707                        }
708                        mHeld = false;
709                    }
710                }
711                if (mCount < 0) {
712                    throw new RuntimeException("WakeLock under-locked " + mTag);
713                }
714            }
715        }
716
717        /**
718         * Returns true if the wake lock has been acquired but not yet released.
719         *
720         * @return True if the wake lock is held.
721         */
722        public boolean isHeld() {
723            synchronized (mToken) {
724                return mHeld;
725            }
726        }
727
728        /**
729         * Sets the work source associated with the wake lock.
730         * <p>
731         * The work source is used to determine on behalf of which application
732         * the wake lock is being held.  This is useful in the case where a
733         * service is performing work on behalf of an application so that the
734         * cost of that work can be accounted to the application.
735         * </p>
736         *
737         * @param ws The work source, or null if none.
738         */
739        public void setWorkSource(WorkSource ws) {
740            synchronized (mToken) {
741                if (ws != null && ws.size() == 0) {
742                    ws = null;
743                }
744
745                final boolean changed;
746                if (ws == null) {
747                    changed = mWorkSource != null;
748                    mWorkSource = null;
749                } else if (mWorkSource == null) {
750                    changed = true;
751                    mWorkSource = new WorkSource(ws);
752                } else {
753                    changed = mWorkSource.diff(ws);
754                    if (changed) {
755                        mWorkSource.set(ws);
756                    }
757                }
758
759                if (changed && mHeld) {
760                    try {
761                        mService.updateWakeLockWorkSource(mToken, mWorkSource);
762                    } catch (RemoteException e) {
763                    }
764                }
765            }
766        }
767
768        @Override
769        public String toString() {
770            synchronized (mToken) {
771                return "WakeLock{"
772                    + Integer.toHexString(System.identityHashCode(this))
773                    + " held=" + mHeld + ", refCount=" + mCount + "}";
774            }
775        }
776    }
777}
778