PowerManager.java revision e8a403d57c8ea540f8287cdaee8b90f0cf9626a3
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
19import android.annotation.SdkConstant;
20import android.annotation.SystemApi;
21import android.content.Context;
22import android.util.Log;
23
24/**
25 * This class gives you control of the power state of the device.
26 *
27 * <p>
28 * <b>Device battery life will be significantly affected by the use of this API.</b>
29 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
30 * possible, and be sure to release them as soon as possible.
31 * </p><p>
32 * You can obtain an instance of this class by calling
33 * {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
34 * </p><p>
35 * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
36 * This will create a {@link PowerManager.WakeLock} object.  You can then use methods
37 * on the wake lock object to control the power state of the device.
38 * </p><p>
39 * In practice it's quite simple:
40 * {@samplecode
41 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
42 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
43 * wl.acquire();
44 *   ..screen will stay on during this section..
45 * wl.release();
46 * }
47 * </p><p>
48 * The following wake lock levels are defined, with varying effects on system power.
49 * <i>These levels are mutually exclusive - you may only specify one of them.</i>
50 *
51 * <table>
52 *     <tr><th>Flag Value</th>
53 *     <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
54 *
55 *     <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
56 *         <td>On*</td> <td>Off</td> <td>Off</td>
57 *     </tr>
58 *
59 *     <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
60 *         <td>On</td> <td>Dim</td> <td>Off</td>
61 *     </tr>
62 *
63 *     <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
64 *         <td>On</td> <td>Bright</td> <td>Off</td>
65 *     </tr>
66 *
67 *     <tr><td>{@link #FULL_WAKE_LOCK}</td>
68 *         <td>On</td> <td>Bright</td> <td>Bright</td>
69 *     </tr>
70 * </table>
71 * </p><p>
72 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
73 * display timeouts or the state of the screen and even after the user presses the power button.
74 * In all other wake locks, the CPU will run, but the user can still put the device to sleep
75 * using the power button.</i>
76 * </p><p>
77 * In addition, you can add two more flags, which affect behavior of the screen only.
78 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
79 *
80 * <table>
81 *     <tr><th>Flag Value</th> <th>Description</th></tr>
82 *
83 *     <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
84 *         <td>Normal wake locks don't actually turn on the illumination.  Instead, they cause
85 *         the illumination to remain on once it turns on (e.g. from user activity).  This flag
86 *         will force the screen and/or keyboard to turn on immediately, when the WakeLock is
87 *         acquired.  A typical use would be for notifications which are important for the user to
88 *         see immediately.</td>
89 *     </tr>
90 *
91 *     <tr><td>{@link #ON_AFTER_RELEASE}</td>
92 *         <td>If this flag is set, the user activity timer will be reset when the WakeLock is
93 *         released, causing the illumination to remain on a bit longer.  This can be used to
94 *         reduce flicker if you are cycling between wake lock conditions.</td>
95 *     </tr>
96 * </table>
97 * <p>
98 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
99 * permission in an {@code <uses-permission>} element of the application's manifest.
100 * </p>
101 */
102public final class PowerManager {
103    private static final String TAG = "PowerManager";
104
105    /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
106     * combinations were actually supported so the bit field was removed.  This explains
107     * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
108     * value can be used.
109     */
110
111    /**
112     * Wake lock level: Ensures that the CPU is running; the screen and keyboard
113     * backlight will be allowed to go off.
114     * <p>
115     * If the user presses the power button, then the screen will be turned off
116     * but the CPU will be kept on until all partial wake locks have been released.
117     * </p>
118     */
119    public static final int PARTIAL_WAKE_LOCK = 0x00000001;
120
121    /**
122     * Wake lock level: Ensures that the screen is on (but may be dimmed);
123     * the keyboard backlight will be allowed to go off.
124     * <p>
125     * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
126     * implicitly released by the system, causing both the screen and the CPU to be turned off.
127     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
128     * </p>
129     *
130     * @deprecated Most applications should use
131     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
132     * of this type of wake lock, as it will be correctly managed by the platform
133     * as the user moves between applications and doesn't require a special permission.
134     */
135    @Deprecated
136    public static final int SCREEN_DIM_WAKE_LOCK = 0x00000006;
137
138    /**
139     * Wake lock level: Ensures that the screen is on at full brightness;
140     * the keyboard backlight will be allowed to go off.
141     * <p>
142     * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
143     * implicitly released by the system, causing both the screen and the CPU to be turned off.
144     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
145     * </p>
146     *
147     * @deprecated Most applications should use
148     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
149     * of this type of wake lock, as it will be correctly managed by the platform
150     * as the user moves between applications and doesn't require a special permission.
151     */
152    @Deprecated
153    public static final int SCREEN_BRIGHT_WAKE_LOCK = 0x0000000a;
154
155    /**
156     * Wake lock level: Ensures that the screen and keyboard backlight are on at
157     * full brightness.
158     * <p>
159     * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
160     * implicitly released by the system, causing both the screen and the CPU to be turned off.
161     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
162     * </p>
163     *
164     * @deprecated Most applications should use
165     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
166     * of this type of wake lock, as it will be correctly managed by the platform
167     * as the user moves between applications and doesn't require a special permission.
168     */
169    @Deprecated
170    public static final int FULL_WAKE_LOCK = 0x0000001a;
171
172    /**
173     * Wake lock level: Turns the screen off when the proximity sensor activates.
174     * <p>
175     * If the proximity sensor detects that an object is nearby, the screen turns off
176     * immediately.  Shortly after the object moves away, the screen turns on again.
177     * </p><p>
178     * A proximity wake lock does not prevent the device from falling asleep
179     * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
180     * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
181     * wake locks are held, then the device will fall asleep (and lock) as usual.
182     * However, the device will not fall asleep while the screen has been turned off
183     * by the proximity sensor because it effectively counts as ongoing user activity.
184     * </p><p>
185     * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
186     * to determine whether this wake lock level is supported.
187     * </p><p>
188     * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
189     * </p>
190     */
191    public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 0x00000020;
192
193    /**
194     * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
195     * if no other wake locks are held.
196     * <p>
197     * This is used by the dream manager to implement doze mode.  It currently
198     * has no effect unless the power manager is in the dozing state.
199     * </p><p>
200     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
201     * </p>
202     *
203     * {@hide}
204     */
205    public static final int DOZE_WAKE_LOCK = 0x00000040;
206
207    /**
208     * Wake lock level: Keep the device awake enough to allow drawing to occur.
209     * <p>
210     * This is used by the window manager to allow applications to draw while the
211     * system is dozing.  It currently has no effect unless the power manager is in
212     * the dozing state.
213     * </p><p>
214     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
215     * </p>
216     *
217     * {@hide}
218     */
219    public static final int DRAW_WAKE_LOCK = 0x00000080;
220
221    /**
222     * Wake lock level: Enables Sustained Performance Mode.
223     * <p>
224     * This is used by Gaming and VR applications to ensure the device provides
225     * will provide consistent performance over a large amount of time.
226     * </p>
227     */
228    public static final int SUSTAINED_PERFORMANCE_WAKE_LOCK = 0x00000100;
229
230    /**
231     * Mask for the wake lock level component of a combined wake lock level and flags integer.
232     *
233     * @hide
234     */
235    public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
236
237    /**
238     * Wake lock flag: Turn the screen on when the wake lock is acquired.
239     * <p>
240     * Normally wake locks don't actually wake the device, they just cause
241     * the screen to remain on once it's already on.  Think of the video player
242     * application as the normal behavior.  Notifications that pop up and want
243     * the device to be on are the exception; use this flag to be like them.
244     * </p><p>
245     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
246     * </p>
247     */
248    public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
249
250    /**
251     * Wake lock flag: When this wake lock is released, poke the user activity timer
252     * so the screen stays on for a little longer.
253     * <p>
254     * Will not turn the screen on if it is not already on.
255     * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
256     * </p><p>
257     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
258     * </p>
259     */
260    public static final int ON_AFTER_RELEASE = 0x20000000;
261
262    /**
263     * Wake lock flag: This wake lock is not important for logging events.  If a later
264     * wake lock is acquired that is important, it will be considered the one to log.
265     * @hide
266     */
267    public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
268
269    /**
270     * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
271     * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
272     * indicates that an object is not in close proximity.
273     */
274    public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
275
276    /**
277     * Brightness value for fully on.
278     * @hide
279     */
280    public static final int BRIGHTNESS_ON = 255;
281
282    /**
283     * Brightness value for fully off.
284     * @hide
285     */
286    public static final int BRIGHTNESS_OFF = 0;
287
288    /**
289     * Brightness value for default policy handling by the system.
290     * @hide
291     */
292    public static final int BRIGHTNESS_DEFAULT = -1;
293
294    // Note: Be sure to update android.os.BatteryStats and PowerManager.h
295    // if adding or modifying user activity event constants.
296
297    /**
298     * User activity event type: Unspecified event type.
299     * @hide
300     */
301    @SystemApi
302    public static final int USER_ACTIVITY_EVENT_OTHER = 0;
303
304    /**
305     * User activity event type: Button or key pressed or released.
306     * @hide
307     */
308    @SystemApi
309    public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
310
311    /**
312     * User activity event type: Touch down, move or up.
313     * @hide
314     */
315    @SystemApi
316    public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
317
318    /**
319     * User activity flag: If already dimmed, extend the dim timeout
320     * but do not brighten.  This flag is useful for keeping the screen on
321     * a little longer without causing a visible change such as when
322     * the power key is pressed.
323     * @hide
324     */
325    @SystemApi
326    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
327
328    /**
329     * User activity flag: Note the user activity as usual but do not
330     * reset the user activity timeout.  This flag is useful for applying
331     * user activity power hints when interacting with the device indirectly
332     * on a secondary screen while allowing the primary screen to go to sleep.
333     * @hide
334     */
335    @SystemApi
336    public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
337
338    /**
339     * Go to sleep reason code: Going to sleep due by application request.
340     * @hide
341     */
342    public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
343
344    /**
345     * Go to sleep reason code: Going to sleep due by request of the
346     * device administration policy.
347     * @hide
348     */
349    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
350
351    /**
352     * Go to sleep reason code: Going to sleep due to a screen timeout.
353     * @hide
354     */
355    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
356
357    /**
358     * Go to sleep reason code: Going to sleep due to the lid switch being closed.
359     * @hide
360     */
361    public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
362
363    /**
364     * Go to sleep reason code: Going to sleep due to the power button being pressed.
365     * @hide
366     */
367    public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
368
369    /**
370     * Go to sleep reason code: Going to sleep due to HDMI.
371     * @hide
372     */
373    public static final int GO_TO_SLEEP_REASON_HDMI = 5;
374
375    /**
376     * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
377     * @hide
378     */
379    public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
380
381    /**
382     * Go to sleep flag: Skip dozing state and directly go to full sleep.
383     * @hide
384     */
385    public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
386
387    /**
388     * The value to pass as the 'reason' argument to reboot() to reboot into
389     * recovery mode for tasks other than applying system updates, such as
390     * doing factory resets.
391     * <p>
392     * Requires the {@link android.Manifest.permission#RECOVERY}
393     * permission (in addition to
394     * {@link android.Manifest.permission#REBOOT}).
395     * </p>
396     * @hide
397     */
398    public static final String REBOOT_RECOVERY = "recovery";
399
400    /**
401     * The value to pass as the 'reason' argument to reboot() to reboot into
402     * recovery mode for applying system updates.
403     * <p>
404     * Requires the {@link android.Manifest.permission#RECOVERY}
405     * permission (in addition to
406     * {@link android.Manifest.permission#REBOOT}).
407     * </p>
408     * @hide
409     */
410    public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
411
412    /**
413     * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
414     * the device.
415     * @hide
416     */
417    public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
418
419    /**
420     * The value to pass as the 'reason' argument to android_reboot().
421     * @hide
422     */
423    public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
424
425    final Context mContext;
426    final IPowerManager mService;
427    final Handler mHandler;
428
429    IDeviceIdleController mIDeviceIdleController;
430
431    /**
432     * {@hide}
433     */
434    public PowerManager(Context context, IPowerManager service, Handler handler) {
435        mContext = context;
436        mService = service;
437        mHandler = handler;
438    }
439
440    /**
441     * Gets the minimum supported screen brightness setting.
442     * The screen may be allowed to become dimmer than this value but
443     * this is the minimum value that can be set by the user.
444     * @hide
445     */
446    public int getMinimumScreenBrightnessSetting() {
447        return mContext.getResources().getInteger(
448                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
449    }
450
451    /**
452     * Gets the maximum supported screen brightness setting.
453     * The screen may be allowed to become dimmer than this value but
454     * this is the maximum value that can be set by the user.
455     * @hide
456     */
457    public int getMaximumScreenBrightnessSetting() {
458        return mContext.getResources().getInteger(
459                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
460    }
461
462    /**
463     * Gets the default screen brightness setting.
464     * @hide
465     */
466    public int getDefaultScreenBrightnessSetting() {
467        return mContext.getResources().getInteger(
468                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
469    }
470
471    /**
472     * Returns true if the twilight service should be used to adjust screen brightness
473     * policy.  This setting is experimental and disabled by default.
474     * @hide
475     */
476    public static boolean useTwilightAdjustmentFeature() {
477        return SystemProperties.getBoolean("persist.power.usetwilightadj", false);
478    }
479
480    /**
481     * Creates a new wake lock with the specified level and flags.
482     * <p>
483     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
484     * combined using the logical OR operator.
485     * </p><p>
486     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
487     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
488     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
489     * specified as part of the {@code levelAndFlags} parameter.
490     * </p><p>
491     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
492     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
493     * {@code levelAndFlags} parameters.
494     * </p><p>
495     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
496     * wake lock, and {@link WakeLock#release release()} when you are done.
497     * </p><p>
498     * {@samplecode
499     * PowerManager pm = (PowerManager)mContext.getSystemService(
500     *                                          Context.POWER_SERVICE);
501     * PowerManager.WakeLock wl = pm.newWakeLock(
502     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
503     *                                      | PowerManager.ON_AFTER_RELEASE,
504     *                                      TAG);
505     * wl.acquire();
506     * // ... do work...
507     * wl.release();
508     * }
509     * </p><p>
510     * Although a wake lock can be created without special permissions,
511     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
512     * required to actually acquire or release the wake lock that is returned.
513     * </p><p class="note">
514     * If using this to keep the screen on, you should strongly consider using
515     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
516     * This window flag will be correctly managed by the platform
517     * as the user moves between applications and doesn't require a special permission.
518     * </p>
519     *
520     * @param levelAndFlags Combination of wake lock level and flag values defining
521     * the requested behavior of the WakeLock.
522     * @param tag Your class name (or other tag) for debugging purposes.
523     *
524     * @see WakeLock#acquire()
525     * @see WakeLock#release()
526     * @see #PARTIAL_WAKE_LOCK
527     * @see #FULL_WAKE_LOCK
528     * @see #SCREEN_DIM_WAKE_LOCK
529     * @see #SCREEN_BRIGHT_WAKE_LOCK
530     * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
531     * @see #ACQUIRE_CAUSES_WAKEUP
532     * @see #ON_AFTER_RELEASE
533     */
534    public WakeLock newWakeLock(int levelAndFlags, String tag) {
535        validateWakeLockParameters(levelAndFlags, tag);
536        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
537    }
538
539    /** @hide */
540    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
541        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
542            case PARTIAL_WAKE_LOCK:
543            case SCREEN_DIM_WAKE_LOCK:
544            case SCREEN_BRIGHT_WAKE_LOCK:
545            case FULL_WAKE_LOCK:
546            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
547            case DOZE_WAKE_LOCK:
548            case DRAW_WAKE_LOCK:
549            case SUSTAINED_PERFORMANCE_WAKE_LOCK:
550                break;
551            default:
552                throw new IllegalArgumentException("Must specify a valid wake lock level.");
553        }
554        if (tag == null) {
555            throw new IllegalArgumentException("The tag must not be null.");
556        }
557    }
558
559    /**
560     * Notifies the power manager that user activity happened.
561     * <p>
562     * Resets the auto-off timer and brightens the screen if the device
563     * is not asleep.  This is what happens normally when a key or the touch
564     * screen is pressed or when some other user activity occurs.
565     * This method does not wake up the device if it has been put to sleep.
566     * </p><p>
567     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
568     * </p>
569     *
570     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
571     * time base.  This timestamp is used to correctly order the user activity request with
572     * other power management functions.  It should be set
573     * to the timestamp of the input event that caused the user activity.
574     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
575     * because of this event.  This is set when the power key is pressed.
576     * We want the device to stay on while the button is down, but we're about
577     * to turn off the screen so we don't want the keyboard backlight to turn on again.
578     * Otherwise the lights flash on and then off and it looks weird.
579     *
580     * @see #wakeUp
581     * @see #goToSleep
582     *
583     * @removed Requires signature or system permission.
584     * @deprecated Use {@link #userActivity(long, int, int)}.
585     */
586    @Deprecated
587    public void userActivity(long when, boolean noChangeLights) {
588        userActivity(when, USER_ACTIVITY_EVENT_OTHER,
589                noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
590    }
591
592    /**
593     * Notifies the power manager that user activity happened.
594     * <p>
595     * Resets the auto-off timer and brightens the screen if the device
596     * is not asleep.  This is what happens normally when a key or the touch
597     * screen is pressed or when some other user activity occurs.
598     * This method does not wake up the device if it has been put to sleep.
599     * </p><p>
600     * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
601     * {@link android.Manifest.permission#USER_ACTIVITY} permission.
602     * </p>
603     *
604     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
605     * time base.  This timestamp is used to correctly order the user activity request with
606     * other power management functions.  It should be set
607     * to the timestamp of the input event that caused the user activity.
608     * @param event The user activity event.
609     * @param flags Optional user activity flags.
610     *
611     * @see #wakeUp
612     * @see #goToSleep
613     *
614     * @hide Requires signature or system permission.
615     */
616    @SystemApi
617    public void userActivity(long when, int event, int flags) {
618        try {
619            mService.userActivity(when, event, flags);
620        } catch (RemoteException e) {
621        }
622    }
623
624   /**
625     * Forces the device to go to sleep.
626     * <p>
627     * Overrides all the wake locks that are held.
628     * This is what happens when the power key is pressed to turn off the screen.
629     * </p><p>
630     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
631     * </p>
632     *
633     * @param time The time when the request to go to sleep was issued, in the
634     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
635     * order the go to sleep request with other power management functions.  It should be set
636     * to the timestamp of the input event that caused the request to go to sleep.
637     *
638     * @see #userActivity
639     * @see #wakeUp
640     *
641     * @removed Requires signature permission.
642     */
643    public void goToSleep(long time) {
644        goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
645    }
646
647    /**
648     * Forces the device to go to sleep.
649     * <p>
650     * Overrides all the wake locks that are held.
651     * This is what happens when the power key is pressed to turn off the screen.
652     * </p><p>
653     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
654     * </p>
655     *
656     * @param time The time when the request to go to sleep was issued, in the
657     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
658     * order the go to sleep request with other power management functions.  It should be set
659     * to the timestamp of the input event that caused the request to go to sleep.
660     * @param reason The reason the device is going to sleep.
661     * @param flags Optional flags to apply when going to sleep.
662     *
663     * @see #userActivity
664     * @see #wakeUp
665     *
666     * @hide Requires signature permission.
667     */
668    public void goToSleep(long time, int reason, int flags) {
669        try {
670            mService.goToSleep(time, reason, flags);
671        } catch (RemoteException e) {
672        }
673    }
674
675    /**
676     * Forces the device to wake up from sleep.
677     * <p>
678     * If the device is currently asleep, wakes it up, otherwise does nothing.
679     * This is what happens when the power key is pressed to turn on the screen.
680     * </p><p>
681     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
682     * </p>
683     *
684     * @param time The time when the request to wake up was issued, in the
685     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
686     * order the wake up request with other power management functions.  It should be set
687     * to the timestamp of the input event that caused the request to wake up.
688     *
689     * @see #userActivity
690     * @see #goToSleep
691     *
692     * @removed Requires signature permission.
693     */
694    public void wakeUp(long time) {
695        try {
696            mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
697        } catch (RemoteException e) {
698        }
699    }
700
701    /**
702     * @hide
703     */
704    public void wakeUp(long time, String reason) {
705        try {
706            mService.wakeUp(time, reason, mContext.getOpPackageName());
707        } catch (RemoteException e) {
708        }
709    }
710
711    /**
712     * Forces the device to start napping.
713     * <p>
714     * If the device is currently awake, starts dreaming, otherwise does nothing.
715     * When the dream ends or if the dream cannot be started, the device will
716     * either wake up or go to sleep depending on whether there has been recent
717     * user activity.
718     * </p><p>
719     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
720     * </p>
721     *
722     * @param time The time when the request to nap was issued, in the
723     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
724     * order the nap request with other power management functions.  It should be set
725     * to the timestamp of the input event that caused the request to nap.
726     *
727     * @see #wakeUp
728     * @see #goToSleep
729     *
730     * @hide Requires signature permission.
731     */
732    public void nap(long time) {
733        try {
734            mService.nap(time);
735        } catch (RemoteException e) {
736        }
737    }
738
739    /**
740     * Boosts the brightness of the screen to maximum for a predetermined
741     * period of time.  This is used to make the screen more readable in bright
742     * daylight for a short duration.
743     * <p>
744     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
745     * </p>
746     *
747     * @param time The time when the request to boost was issued, in the
748     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
749     * order the boost request with other power management functions.  It should be set
750     * to the timestamp of the input event that caused the request to boost.
751     *
752     * @hide Requires signature permission.
753     */
754    public void boostScreenBrightness(long time) {
755        try {
756            mService.boostScreenBrightness(time);
757        } catch (RemoteException e) {
758        }
759    }
760
761    /**
762     * Returns whether the screen brightness is currently boosted to maximum, caused by a call
763     * to {@link #boostScreenBrightness(long)}.
764     * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
765     *
766     * @hide
767     */
768    @SystemApi
769    public boolean isScreenBrightnessBoosted() {
770        try {
771            return mService.isScreenBrightnessBoosted();
772        } catch (RemoteException e) {
773            return false;
774        }
775    }
776
777    /**
778     * Sets the brightness of the backlights (screen, keyboard, button).
779     * <p>
780     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
781     * </p>
782     *
783     * @param brightness The brightness value from 0 to 255.
784     *
785     * @hide Requires signature permission.
786     */
787    public void setBacklightBrightness(int brightness) {
788        try {
789            mService.setTemporaryScreenBrightnessSettingOverride(brightness);
790        } catch (RemoteException e) {
791        }
792    }
793
794   /**
795     * Returns true if the specified wake lock level is supported.
796     *
797     * @param level The wake lock level to check.
798     * @return True if the specified wake lock level is supported.
799     */
800    public boolean isWakeLockLevelSupported(int level) {
801        try {
802            return mService.isWakeLockLevelSupported(level);
803        } catch (RemoteException e) {
804            return false;
805        }
806    }
807
808    /**
809      * Returns true if the device is in an interactive state.
810      * <p>
811      * For historical reasons, the name of this method refers to the power state of
812      * the screen but it actually describes the overall interactive state of
813      * the device.  This method has been replaced by {@link #isInteractive}.
814      * </p><p>
815      * The value returned by this method only indicates whether the device is
816      * in an interactive state which may have nothing to do with the screen being
817      * on or off.  To determine the actual state of the screen,
818      * use {@link android.view.Display#getState}.
819      * </p>
820      *
821      * @return True if the device is in an interactive state.
822      *
823      * @deprecated Use {@link #isInteractive} instead.
824      */
825    @Deprecated
826    public boolean isScreenOn() {
827        return isInteractive();
828    }
829
830    /**
831     * Returns true if the device is in an interactive state.
832     * <p>
833     * When this method returns true, the device is awake and ready to interact
834     * with the user (although this is not a guarantee that the user is actively
835     * interacting with the device just this moment).  The main screen is usually
836     * turned on while in this state.  Certain features, such as the proximity
837     * sensor, may temporarily turn off the screen while still leaving the device in an
838     * interactive state.  Note in particular that the device is still considered
839     * to be interactive while dreaming (since dreams can be interactive) but not
840     * when it is dozing or asleep.
841     * </p><p>
842     * When this method returns false, the device is dozing or asleep and must
843     * be awoken before it will become ready to interact with the user again.  The
844     * main screen is usually turned off while in this state.  Certain features,
845     * such as "ambient mode" may cause the main screen to remain on (albeit in a
846     * low power state) to display system-provided content while the device dozes.
847     * </p><p>
848     * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
849     * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
850     * whenever the interactive state of the device changes.  For historical reasons,
851     * the names of these broadcasts refer to the power state of the screen
852     * but they are actually sent in response to changes in the overall interactive
853     * state of the device, as described by this method.
854     * </p><p>
855     * Services may use the non-interactive state as a hint to conserve power
856     * since the user is not present.
857     * </p>
858     *
859     * @return True if the device is in an interactive state.
860     *
861     * @see android.content.Intent#ACTION_SCREEN_ON
862     * @see android.content.Intent#ACTION_SCREEN_OFF
863     */
864    public boolean isInteractive() {
865        try {
866            return mService.isInteractive();
867        } catch (RemoteException e) {
868            return false;
869        }
870    }
871
872    /**
873     * Reboot the device.  Will not return if the reboot is successful.
874     * <p>
875     * Requires the {@link android.Manifest.permission#REBOOT} permission.
876     * </p>
877     *
878     * @param reason code to pass to the kernel (e.g., "recovery") to
879     *               request special boot modes, or null.
880     */
881    public void reboot(String reason) {
882        try {
883            mService.reboot(false, reason, true);
884        } catch (RemoteException e) {
885        }
886    }
887
888    /**
889     * Returns true if the device is currently in power save mode.  When in this mode,
890     * applications should reduce their functionality in order to conserve battery as
891     * much as possible.  You can monitor for changes to this state with
892     * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
893     *
894     * @return Returns true if currently in low power mode, else false.
895     */
896    public boolean isPowerSaveMode() {
897        try {
898            return mService.isPowerSaveMode();
899        } catch (RemoteException e) {
900            return false;
901        }
902    }
903
904    /**
905     * Set the current power save mode.
906     *
907     * @return True if the set was allowed.
908     *
909     * @see #isPowerSaveMode()
910     *
911     * @hide
912     */
913    public boolean setPowerSaveMode(boolean mode) {
914        try {
915            return mService.setPowerSaveMode(mode);
916        } catch (RemoteException e) {
917            return false;
918        }
919    }
920
921    /**
922     * Returns true if the device is currently in idle mode.  This happens when a device
923     * has been sitting unused and unmoving for a sufficiently long period of time, so that
924     * it decides to go into a lower power-use state.  This may involve things like turning
925     * off network access to apps.  You can monitor for changes to this state with
926     * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
927     *
928     * @return Returns true if currently in active device idle mode, else false.  This is
929     * when idle mode restrictions are being actively applied; it will return false if the
930     * device is in a long-term idle mode but currently running a maintenance window where
931     * restrictions have been lifted.
932     */
933    public boolean isDeviceIdleMode() {
934        try {
935            return mService.isDeviceIdleMode();
936        } catch (RemoteException e) {
937            return false;
938        }
939    }
940
941    /**
942     * Returns true if the device is currently in light idle mode.  This happens when a device
943     * has had its screen off for a short time, switching it into a batching mode where we
944     * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
945     * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
946     *
947     * @return Returns true if currently in active light device idle mode, else false.  This is
948     * when light idle mode restrictions are being actively applied; it will return false if the
949     * device is in a long-term idle mode but currently running a maintenance window where
950     * restrictions have been lifted.
951     * @hide
952     */
953    public boolean isLightDeviceIdleMode() {
954        try {
955            return mService.isLightDeviceIdleMode();
956        } catch (RemoteException e) {
957            return false;
958        }
959    }
960
961    /**
962     * Return whether the given application package name is on the device's power whitelist.
963     * Apps can be placed on the whitelist through the settings UI invoked by
964     * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
965     */
966    public boolean isIgnoringBatteryOptimizations(String packageName) {
967        synchronized (this) {
968            if (mIDeviceIdleController == null) {
969                mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
970                        ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
971            }
972        }
973        try {
974            return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
975        } catch (RemoteException e) {
976            return false;
977        }
978    }
979
980    /**
981     * Turn off the device.
982     *
983     * @param confirm If true, shows a shutdown confirmation dialog.
984     * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
985     * @param wait If true, this call waits for the shutdown to complete and does not return.
986     *
987     * @hide
988     */
989    public void shutdown(boolean confirm, String reason, boolean wait) {
990        try {
991            mService.shutdown(confirm, reason, wait);
992        } catch (RemoteException e) {
993        }
994    }
995
996    /**
997     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
998     * This broadcast is only sent to registered receivers.
999     */
1000    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1001    public static final String ACTION_POWER_SAVE_MODE_CHANGED
1002            = "android.os.action.POWER_SAVE_MODE_CHANGED";
1003
1004    /**
1005     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1006     * @hide
1007     */
1008    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1009    public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
1010            = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
1011
1012    /**
1013     * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1014     * This broadcast is only sent to registered receivers.
1015     */
1016    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1017    public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
1018            = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
1019
1020    /**
1021     * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1022     * This broadcast is only sent to registered receivers.
1023     * @hide
1024     */
1025    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1026    public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
1027            = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
1028
1029    /**
1030     * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
1031     * This broadcast is only sent to registered receivers.
1032     */
1033    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1034    public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
1035            = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
1036
1037    /**
1038     * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1039     * This broadcast is only sent to registered receivers.
1040     */
1041    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1042    public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
1043            = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
1044
1045    /**
1046     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
1047     * This broadcast is only sent to registered receivers.
1048     *
1049     * @hide
1050     */
1051    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1052    public static final String ACTION_POWER_SAVE_MODE_CHANGING
1053            = "android.os.action.POWER_SAVE_MODE_CHANGING";
1054
1055    /** @hide */
1056    public static final String EXTRA_POWER_SAVE_MODE = "mode";
1057
1058    /**
1059     * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
1060     * This broadcast is only sent to registered receivers.
1061     *
1062     * @hide
1063     **/
1064    @SystemApi
1065    public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
1066            = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
1067
1068    /**
1069     * A wake lock is a mechanism to indicate that your application needs
1070     * to have the device stay on.
1071     * <p>
1072     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
1073     * permission in an {@code <uses-permission>} element of the application's manifest.
1074     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
1075     * </p><p>
1076     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
1077     * on at the level that was requested when the wake lock was created.
1078     * </p><p>
1079     * Call {@link #release()} when you are done and don't need the lock anymore.
1080     * It is very important to do this as soon as possible to avoid running down the
1081     * device's battery excessively.
1082     * </p>
1083     */
1084    public final class WakeLock {
1085        private int mFlags;
1086        private String mTag;
1087        private final String mPackageName;
1088        private final IBinder mToken;
1089        private int mCount;
1090        private boolean mRefCounted = true;
1091        private boolean mHeld;
1092        private WorkSource mWorkSource;
1093        private String mHistoryTag;
1094        private final String mTraceName;
1095
1096        private final Runnable mReleaser = new Runnable() {
1097            public void run() {
1098                release();
1099            }
1100        };
1101
1102        WakeLock(int flags, String tag, String packageName) {
1103            mFlags = flags;
1104            mTag = tag;
1105            mPackageName = packageName;
1106            mToken = new Binder();
1107            mTraceName = "WakeLock (" + mTag + ")";
1108        }
1109
1110        @Override
1111        protected void finalize() throws Throwable {
1112            synchronized (mToken) {
1113                if (mHeld) {
1114                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
1115                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1116                    try {
1117                        mService.releaseWakeLock(mToken, 0);
1118                    } catch (RemoteException e) {
1119                    }
1120                }
1121            }
1122        }
1123
1124        /**
1125         * Sets whether this WakeLock is reference counted.
1126         * <p>
1127         * Wake locks are reference counted by default.  If a wake lock is
1128         * reference counted, then each call to {@link #acquire()} must be
1129         * balanced by an equal number of calls to {@link #release()}.  If a wake
1130         * lock is not reference counted, then one call to {@link #release()} is
1131         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
1132         * </p>
1133         *
1134         * @param value True to make the wake lock reference counted, false to
1135         * make the wake lock non-reference counted.
1136         */
1137        public void setReferenceCounted(boolean value) {
1138            synchronized (mToken) {
1139                mRefCounted = value;
1140            }
1141        }
1142
1143        /**
1144         * Acquires the wake lock.
1145         * <p>
1146         * Ensures that the device is on at the level requested when
1147         * the wake lock was created.
1148         * </p>
1149         */
1150        public void acquire() {
1151            synchronized (mToken) {
1152                acquireLocked();
1153            }
1154        }
1155
1156        /**
1157         * Acquires the wake lock with a timeout.
1158         * <p>
1159         * Ensures that the device is on at the level requested when
1160         * the wake lock was created.  The lock will be released after the given timeout
1161         * expires.
1162         * </p>
1163         *
1164         * @param timeout The timeout after which to release the wake lock, in milliseconds.
1165         */
1166        public void acquire(long timeout) {
1167            synchronized (mToken) {
1168                acquireLocked();
1169                mHandler.postDelayed(mReleaser, timeout);
1170            }
1171        }
1172
1173        private void acquireLocked() {
1174            if (!mRefCounted || mCount++ == 0) {
1175                // Do this even if the wake lock is already thought to be held (mHeld == true)
1176                // because non-reference counted wake locks are not always properly released.
1177                // For example, the keyguard's wake lock might be forcibly released by the
1178                // power manager without the keyguard knowing.  A subsequent call to acquire
1179                // should immediately acquire the wake lock once again despite never having
1180                // been explicitly released by the keyguard.
1181                mHandler.removeCallbacks(mReleaser);
1182                Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
1183                try {
1184                    mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
1185                            mHistoryTag);
1186                } catch (RemoteException e) {
1187                }
1188                mHeld = true;
1189            }
1190        }
1191
1192        /**
1193         * Releases the wake lock.
1194         * <p>
1195         * This method releases your claim to the CPU or screen being on.
1196         * The screen may turn off shortly after you release the wake lock, or it may
1197         * not if there are other wake locks still held.
1198         * </p>
1199         */
1200        public void release() {
1201            release(0);
1202        }
1203
1204        /**
1205         * Releases the wake lock with flags to modify the release behavior.
1206         * <p>
1207         * This method releases your claim to the CPU or screen being on.
1208         * The screen may turn off shortly after you release the wake lock, or it may
1209         * not if there are other wake locks still held.
1210         * </p>
1211         *
1212         * @param flags Combination of flag values to modify the release behavior.
1213         * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
1214         * Passing 0 is equivalent to calling {@link #release()}.
1215         */
1216        public void release(int flags) {
1217            synchronized (mToken) {
1218                if (!mRefCounted || --mCount == 0) {
1219                    mHandler.removeCallbacks(mReleaser);
1220                    if (mHeld) {
1221                        Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1222                        try {
1223                            mService.releaseWakeLock(mToken, flags);
1224                        } catch (RemoteException e) {
1225                        }
1226                        mHeld = false;
1227                    }
1228                }
1229                if (mCount < 0) {
1230                    throw new RuntimeException("WakeLock under-locked " + mTag);
1231                }
1232            }
1233        }
1234
1235        /**
1236         * Returns true if the wake lock has been acquired but not yet released.
1237         *
1238         * @return True if the wake lock is held.
1239         */
1240        public boolean isHeld() {
1241            synchronized (mToken) {
1242                return mHeld;
1243            }
1244        }
1245
1246        /**
1247         * Sets the work source associated with the wake lock.
1248         * <p>
1249         * The work source is used to determine on behalf of which application
1250         * the wake lock is being held.  This is useful in the case where a
1251         * service is performing work on behalf of an application so that the
1252         * cost of that work can be accounted to the application.
1253         * </p>
1254         *
1255         * @param ws The work source, or null if none.
1256         */
1257        public void setWorkSource(WorkSource ws) {
1258            synchronized (mToken) {
1259                if (ws != null && ws.size() == 0) {
1260                    ws = null;
1261                }
1262
1263                final boolean changed;
1264                if (ws == null) {
1265                    changed = mWorkSource != null;
1266                    mWorkSource = null;
1267                } else if (mWorkSource == null) {
1268                    changed = true;
1269                    mWorkSource = new WorkSource(ws);
1270                } else {
1271                    changed = mWorkSource.diff(ws);
1272                    if (changed) {
1273                        mWorkSource.set(ws);
1274                    }
1275                }
1276
1277                if (changed && mHeld) {
1278                    try {
1279                        mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
1280                    } catch (RemoteException e) {
1281                    }
1282                }
1283            }
1284        }
1285
1286        /** @hide */
1287        public void setTag(String tag) {
1288            mTag = tag;
1289        }
1290
1291        /** @hide */
1292        public void setHistoryTag(String tag) {
1293            mHistoryTag = tag;
1294        }
1295
1296        /** @hide */
1297        public void setUnimportantForLogging(boolean state) {
1298            if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
1299            else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
1300        }
1301
1302        @Override
1303        public String toString() {
1304            synchronized (mToken) {
1305                return "WakeLock{"
1306                    + Integer.toHexString(System.identityHashCode(this))
1307                    + " held=" + mHeld + ", refCount=" + mCount + "}";
1308            }
1309        }
1310    }
1311}
1312