PowerManager.java revision 16cfe45dec96154d37b36364f67cedce16ca2484
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.IntDef;
20import android.annotation.RequiresPermission;
21import android.annotation.SdkConstant;
22import android.annotation.SystemApi;
23import android.annotation.SystemService;
24import android.content.Context;
25import android.util.Log;
26import android.util.proto.ProtoOutputStream;
27
28import java.lang.annotation.Retention;
29import java.lang.annotation.RetentionPolicy;
30
31/**
32 * This class gives you control of the power state of the device.
33 *
34 * <p>
35 * <b>Device battery life will be significantly affected by the use of this API.</b>
36 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
37 * possible, and be sure to release them as soon as possible.
38 * </p><p>
39 * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
40 * This will create a {@link PowerManager.WakeLock} object.  You can then use methods
41 * on the wake lock object to control the power state of the device.
42 * </p><p>
43 * In practice it's quite simple:
44 * {@samplecode
45 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
46 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
47 * wl.acquire();
48 *   ..screen will stay on during this section..
49 * wl.release();
50 * }
51 * </p><p>
52 * The following wake lock levels are defined, with varying effects on system power.
53 * <i>These levels are mutually exclusive - you may only specify one of them.</i>
54 *
55 * <table>
56 *     <tr><th>Flag Value</th>
57 *     <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
58 *
59 *     <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
60 *         <td>On*</td> <td>Off</td> <td>Off</td>
61 *     </tr>
62 *
63 *     <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
64 *         <td>On</td> <td>Dim</td> <td>Off</td>
65 *     </tr>
66 *
67 *     <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
68 *         <td>On</td> <td>Bright</td> <td>Off</td>
69 *     </tr>
70 *
71 *     <tr><td>{@link #FULL_WAKE_LOCK}</td>
72 *         <td>On</td> <td>Bright</td> <td>Bright</td>
73 *     </tr>
74 * </table>
75 * </p><p>
76 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
77 * display timeouts or the state of the screen and even after the user presses the power button.
78 * In all other wake locks, the CPU will run, but the user can still put the device to sleep
79 * using the power button.</i>
80 * </p><p>
81 * In addition, you can add two more flags, which affect behavior of the screen only.
82 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
83 *
84 * <table>
85 *     <tr><th>Flag Value</th> <th>Description</th></tr>
86 *
87 *     <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
88 *         <td>Normal wake locks don't actually turn on the illumination.  Instead, they cause
89 *         the illumination to remain on once it turns on (e.g. from user activity).  This flag
90 *         will force the screen and/or keyboard to turn on immediately, when the WakeLock is
91 *         acquired.  A typical use would be for notifications which are important for the user to
92 *         see immediately.</td>
93 *     </tr>
94 *
95 *     <tr><td>{@link #ON_AFTER_RELEASE}</td>
96 *         <td>If this flag is set, the user activity timer will be reset when the WakeLock is
97 *         released, causing the illumination to remain on a bit longer.  This can be used to
98 *         reduce flicker if you are cycling between wake lock conditions.</td>
99 *     </tr>
100 * </table>
101 * <p>
102 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
103 * permission in an {@code <uses-permission>} element of the application's manifest.
104 * </p>
105 */
106@SystemService(Context.POWER_SERVICE)
107public final class PowerManager {
108    private static final String TAG = "PowerManager";
109
110    /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
111     * combinations were actually supported so the bit field was removed.  This explains
112     * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
113     * value (in frameworks/base/core/proto/android/os/enums.proto) can be used.
114     */
115
116    /**
117     * Wake lock level: Ensures that the CPU is running; the screen and keyboard
118     * backlight will be allowed to go off.
119     * <p>
120     * If the user presses the power button, then the screen will be turned off
121     * but the CPU will be kept on until all partial wake locks have been released.
122     * </p>
123     */
124    public static final int PARTIAL_WAKE_LOCK = OsProtoEnums.PARTIAL_WAKE_LOCK; // 0x00000001
125
126    /**
127     * Wake lock level: Ensures that the screen is on (but may be dimmed);
128     * the keyboard backlight will be allowed to go off.
129     * <p>
130     * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
131     * implicitly released by the system, causing both the screen and the CPU to be turned off.
132     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
133     * </p>
134     *
135     * @deprecated Most applications should use
136     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
137     * of this type of wake lock, as it will be correctly managed by the platform
138     * as the user moves between applications and doesn't require a special permission.
139     */
140    @Deprecated
141    public static final int SCREEN_DIM_WAKE_LOCK = OsProtoEnums.SCREEN_DIM_WAKE_LOCK; // 0x00000006
142
143    /**
144     * Wake lock level: Ensures that the screen is on at full brightness;
145     * the keyboard backlight will be allowed to go off.
146     * <p>
147     * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
148     * implicitly released by the system, causing both the screen and the CPU to be turned off.
149     * Contrast with {@link #PARTIAL_WAKE_LOCK}.
150     * </p>
151     *
152     * @deprecated Most applications should use
153     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
154     * of this type of wake lock, as it will be correctly managed by the platform
155     * as the user moves between applications and doesn't require a special permission.
156     */
157    @Deprecated
158    public static final int SCREEN_BRIGHT_WAKE_LOCK =
159            OsProtoEnums.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 = OsProtoEnums.FULL_WAKE_LOCK; // 0x0000001a
177
178    /**
179     * Wake lock level: Turns the screen off when the proximity sensor activates.
180     * <p>
181     * If the proximity sensor detects that an object is nearby, the screen turns off
182     * immediately.  Shortly after the object moves away, the screen turns on again.
183     * </p><p>
184     * A proximity wake lock does not prevent the device from falling asleep
185     * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
186     * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
187     * wake locks are held, then the device will fall asleep (and lock) as usual.
188     * However, the device will not fall asleep while the screen has been turned off
189     * by the proximity sensor because it effectively counts as ongoing user activity.
190     * </p><p>
191     * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
192     * to determine whether this wake lock level is supported.
193     * </p><p>
194     * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
195     * </p>
196     */
197    public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK =
198            OsProtoEnums.PROXIMITY_SCREEN_OFF_WAKE_LOCK; // 0x00000020
199
200    /**
201     * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
202     * if no other wake locks are held.
203     * <p>
204     * This is used by the dream manager to implement doze mode.  It currently
205     * has no effect unless the power manager is in the dozing state.
206     * </p><p>
207     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
208     * </p>
209     *
210     * {@hide}
211     */
212    public static final int DOZE_WAKE_LOCK = OsProtoEnums.DOZE_WAKE_LOCK; // 0x00000040
213
214    /**
215     * Wake lock level: Keep the device awake enough to allow drawing to occur.
216     * <p>
217     * This is used by the window manager to allow applications to draw while the
218     * system is dozing.  It currently has no effect unless the power manager is in
219     * the dozing state.
220     * </p><p>
221     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
222     * </p>
223     *
224     * {@hide}
225     */
226    public static final int DRAW_WAKE_LOCK = OsProtoEnums.DRAW_WAKE_LOCK; // 0x00000080
227
228    /**
229     * Mask for the wake lock level component of a combined wake lock level and flags integer.
230     *
231     * @hide
232     */
233    public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
234
235    /**
236     * Wake lock flag: Turn the screen on when the wake lock is acquired.
237     * <p>
238     * Normally wake locks don't actually wake the device, they just cause
239     * the screen to remain on once it's already on.  Think of the video player
240     * application as the normal behavior.  Notifications that pop up and want
241     * the device to be on are the exception; use this flag to be like them.
242     * </p><p>
243     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
244     * </p>
245     */
246    public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
247
248    /**
249     * Wake lock flag: When this wake lock is released, poke the user activity timer
250     * so the screen stays on for a little longer.
251     * <p>
252     * Will not turn the screen on if it is not already on.
253     * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
254     * </p><p>
255     * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
256     * </p>
257     */
258    public static final int ON_AFTER_RELEASE = 0x20000000;
259
260    /**
261     * Wake lock flag: This wake lock is not important for logging events.  If a later
262     * wake lock is acquired that is important, it will be considered the one to log.
263     * @hide
264     */
265    public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
266
267    /**
268     * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
269     * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
270     * indicates that an object is not in close proximity.
271     */
272    public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1 << 0;
273
274    /**
275     * Flag for {@link WakeLock#release(int)} when called due to timeout.
276     * @hide
277     */
278    public static final int RELEASE_FLAG_TIMEOUT = 1 << 16;
279
280    /**
281     * Brightness value for fully on.
282     * @hide
283     */
284    public static final int BRIGHTNESS_ON = 255;
285
286    /**
287     * Brightness value for fully off.
288     * @hide
289     */
290    public static final int BRIGHTNESS_OFF = 0;
291
292    /**
293     * Brightness value for default policy handling by the system.
294     * @hide
295     */
296    public static final int BRIGHTNESS_DEFAULT = -1;
297
298    // Note: Be sure to update android.os.BatteryStats and PowerManager.h
299    // if adding or modifying user activity event constants.
300
301    /**
302     * User activity event type: Unspecified event type.
303     * @hide
304     */
305    @SystemApi
306    public static final int USER_ACTIVITY_EVENT_OTHER = 0;
307
308    /**
309     * User activity event type: Button or key pressed or released.
310     * @hide
311     */
312    @SystemApi
313    public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
314
315    /**
316     * User activity event type: Touch down, move or up.
317     * @hide
318     */
319    @SystemApi
320    public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
321
322    /**
323     * User activity event type: Accessibility taking action on behalf of user.
324     * @hide
325     */
326    @SystemApi
327    public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
328
329    /**
330     * User activity flag: If already dimmed, extend the dim timeout
331     * but do not brighten.  This flag is useful for keeping the screen on
332     * a little longer without causing a visible change such as when
333     * the power key is pressed.
334     * @hide
335     */
336    @SystemApi
337    public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
338
339    /**
340     * User activity flag: Note the user activity as usual but do not
341     * reset the user activity timeout.  This flag is useful for applying
342     * user activity power hints when interacting with the device indirectly
343     * on a secondary screen while allowing the primary screen to go to sleep.
344     * @hide
345     */
346    @SystemApi
347    public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
348
349    /**
350     * Go to sleep reason code: Going to sleep due by application request.
351     * @hide
352     */
353    public static final int GO_TO_SLEEP_REASON_APPLICATION = 0;
354
355    /**
356     * Go to sleep reason code: Going to sleep due by request of the
357     * device administration policy.
358     * @hide
359     */
360    public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
361
362    /**
363     * Go to sleep reason code: Going to sleep due to a screen timeout.
364     * @hide
365     */
366    public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
367
368    /**
369     * Go to sleep reason code: Going to sleep due to the lid switch being closed.
370     * @hide
371     */
372    public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
373
374    /**
375     * Go to sleep reason code: Going to sleep due to the power button being pressed.
376     * @hide
377     */
378    public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
379
380    /**
381     * Go to sleep reason code: Going to sleep due to HDMI.
382     * @hide
383     */
384    public static final int GO_TO_SLEEP_REASON_HDMI = 5;
385
386    /**
387     * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
388     * @hide
389     */
390    public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
391
392    /**
393     * Go to sleep reason code: Going to sleep by request of an accessibility service
394     * @hide
395     */
396    public static final int GO_TO_SLEEP_REASON_ACCESSIBILITY = 7;
397
398    /**
399     * Go to sleep flag: Skip dozing state and directly go to full sleep.
400     * @hide
401     */
402    public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
403
404    /**
405     * The value to pass as the 'reason' argument to reboot() to reboot into
406     * recovery mode for tasks other than applying system updates, such as
407     * doing factory resets.
408     * <p>
409     * Requires the {@link android.Manifest.permission#RECOVERY}
410     * permission (in addition to
411     * {@link android.Manifest.permission#REBOOT}).
412     * </p>
413     * @hide
414     */
415    public static final String REBOOT_RECOVERY = "recovery";
416
417    /**
418     * The value to pass as the 'reason' argument to reboot() to reboot into
419     * recovery mode for applying system updates.
420     * <p>
421     * Requires the {@link android.Manifest.permission#RECOVERY}
422     * permission (in addition to
423     * {@link android.Manifest.permission#REBOOT}).
424     * </p>
425     * @hide
426     */
427    public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
428
429    /**
430     * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
431     * the device.
432     * @hide
433     */
434    public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
435
436    /**
437     * The 'reason' value used when rebooting in safe mode
438     * @hide
439     */
440    public static final String REBOOT_SAFE_MODE = "safemode";
441
442    /**
443     * The 'reason' value used when rebooting the device without turning on the screen.
444     * @hide
445     */
446    public static final String REBOOT_QUIESCENT = "quiescent";
447
448    /**
449     * The value to pass as the 'reason' argument to android_reboot().
450     * @hide
451     */
452    public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
453
454    /**
455     * The value to pass as the 'reason' argument to android_reboot() when battery temperature
456     * is too high.
457     * @hide
458     */
459    public static final String SHUTDOWN_BATTERY_THERMAL_STATE = "thermal,battery";
460
461    /**
462     * The value to pass as the 'reason' argument to android_reboot() when device is running
463     * critically low on battery.
464     * @hide
465     */
466    public static final String SHUTDOWN_LOW_BATTERY = "battery";
467
468    /**
469     * @hide
470     */
471    @Retention(RetentionPolicy.SOURCE)
472    @IntDef(prefix = { "SHUTDOWN_REASON_" }, value = {
473            SHUTDOWN_REASON_UNKNOWN,
474            SHUTDOWN_REASON_SHUTDOWN,
475            SHUTDOWN_REASON_REBOOT,
476            SHUTDOWN_REASON_USER_REQUESTED,
477            SHUTDOWN_REASON_THERMAL_SHUTDOWN,
478            SHUTDOWN_REASON_LOW_BATTERY,
479            SHUTDOWN_REASON_BATTERY_THERMAL
480    })
481    public @interface ShutdownReason {}
482
483    /**
484     * constant for shutdown reason being unknown.
485     * @hide
486     */
487    public static final int SHUTDOWN_REASON_UNKNOWN = 0;
488
489    /**
490     * constant for shutdown reason being normal shutdown.
491     * @hide
492     */
493    public static final int SHUTDOWN_REASON_SHUTDOWN = 1;
494
495    /**
496     * constant for shutdown reason being reboot.
497     * @hide
498     */
499    public static final int SHUTDOWN_REASON_REBOOT = 2;
500
501    /**
502     * constant for shutdown reason being user requested.
503     * @hide
504     */
505    public static final int SHUTDOWN_REASON_USER_REQUESTED = 3;
506
507    /**
508     * constant for shutdown reason being overheating.
509     * @hide
510     */
511    public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4;
512
513    /**
514     * constant for shutdown reason being low battery.
515     * @hide
516     */
517    public static final int SHUTDOWN_REASON_LOW_BATTERY = 5;
518
519    /**
520     * constant for shutdown reason being critical battery thermal state.
521     * @hide
522     */
523    public static final int SHUTDOWN_REASON_BATTERY_THERMAL = 6;
524
525    /**
526     * @hide
527     */
528    @Retention(RetentionPolicy.SOURCE)
529    @IntDef({ServiceType.GPS,
530            ServiceType.VIBRATION,
531            ServiceType.ANIMATION,
532            ServiceType.FULL_BACKUP,
533            ServiceType.KEYVALUE_BACKUP,
534            ServiceType.NETWORK_FIREWALL,
535            ServiceType.SCREEN_BRIGHTNESS,
536            ServiceType.SOUND,
537            ServiceType.BATTERY_STATS,
538            ServiceType.DATA_SAVER,
539            ServiceType.FORCE_ALL_APPS_STANDBY,
540            ServiceType.OPTIONAL_SENSORS,
541            ServiceType.AOD,
542    })
543    public @interface ServiceType {
544        int NULL = 0;
545        int GPS = 1;
546        int VIBRATION = 2;
547        int ANIMATION = 3;
548        int FULL_BACKUP = 4;
549        int KEYVALUE_BACKUP = 5;
550        int NETWORK_FIREWALL = 6;
551        int SCREEN_BRIGHTNESS = 7;
552        int SOUND = 8;
553        int BATTERY_STATS = 9;
554        int DATA_SAVER = 10;
555        int AOD = 14;
556
557        /**
558         * Whether to enable force-app-standby on all apps or not.
559         */
560        int FORCE_ALL_APPS_STANDBY = 11;
561
562        /**
563         * Whether to enable background check on all apps or not.
564         */
565        int FORCE_BACKGROUND_CHECK = 12;
566
567        /**
568         * Whether to disable non-essential sensors. (e.g. edge sensors.)
569         */
570        int OPTIONAL_SENSORS = 13;
571    }
572
573    /**
574     * Either the location providers shouldn't be affected by battery saver,
575     * or battery saver is off.
576     */
577    public static final int LOCATION_MODE_NO_CHANGE = 0;
578
579    /**
580     * In this mode, the GPS based location provider should be disabled when battery saver is on and
581     * the device is non-interactive.
582     */
583    public static final int LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 1;
584
585    /**
586     * All location providers should be disabled when battery saver is on and
587     * the device is non-interactive.
588     */
589    public static final int LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 2;
590
591    /**
592     * In this mode, all the location providers will be kept available, but location fixes
593     * should only be provided to foreground apps.
594     */
595    public static final int LOCATION_MODE_FOREGROUND_ONLY = 3;
596
597    /**
598     * @hide
599     */
600    @Retention(RetentionPolicy.SOURCE)
601    @IntDef(prefix = {"LOCATION_MODE_"}, value = {
602            LOCATION_MODE_NO_CHANGE,
603            LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF,
604            LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF,
605            LOCATION_MODE_FOREGROUND_ONLY,
606    })
607    public @interface LocationPowerSaveMode {}
608
609    final Context mContext;
610    final IPowerManager mService;
611    final Handler mHandler;
612
613    IDeviceIdleController mIDeviceIdleController;
614
615    /**
616     * {@hide}
617     */
618    public PowerManager(Context context, IPowerManager service, Handler handler) {
619        mContext = context;
620        mService = service;
621        mHandler = handler;
622    }
623
624    /**
625     * Gets the minimum supported screen brightness setting.
626     * The screen may be allowed to become dimmer than this value but
627     * this is the minimum value that can be set by the user.
628     * @hide
629     */
630    public int getMinimumScreenBrightnessSetting() {
631        return mContext.getResources().getInteger(
632                com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
633    }
634
635    /**
636     * Gets the maximum supported screen brightness setting.
637     * The screen may be allowed to become dimmer than this value but
638     * this is the maximum value that can be set by the user.
639     * @hide
640     */
641    public int getMaximumScreenBrightnessSetting() {
642        return mContext.getResources().getInteger(
643                com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
644    }
645
646    /**
647     * Gets the default screen brightness setting.
648     * @hide
649     */
650    public int getDefaultScreenBrightnessSetting() {
651        return mContext.getResources().getInteger(
652                com.android.internal.R.integer.config_screenBrightnessSettingDefault);
653    }
654
655    /**
656     * Gets the minimum supported screen brightness setting for VR Mode.
657     * @hide
658     */
659    public int getMinimumScreenBrightnessForVrSetting() {
660        return mContext.getResources().getInteger(
661                com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum);
662    }
663
664    /**
665     * Gets the maximum supported screen brightness setting for VR Mode.
666     * The screen may be allowed to become dimmer than this value but
667     * this is the maximum value that can be set by the user.
668     * @hide
669     */
670    public int getMaximumScreenBrightnessForVrSetting() {
671        return mContext.getResources().getInteger(
672                com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum);
673    }
674
675    /**
676     * Gets the default screen brightness for VR setting.
677     * @hide
678     */
679    public int getDefaultScreenBrightnessForVrSetting() {
680        return mContext.getResources().getInteger(
681                com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
682    }
683
684    /**
685     * Creates a new wake lock with the specified level and flags.
686     * <p>
687     * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
688     * combined using the logical OR operator.
689     * </p><p>
690     * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
691     * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
692     * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
693     * specified as part of the {@code levelAndFlags} parameter.
694     * </p><p>
695     * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
696     * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
697     * {@code levelAndFlags} parameters.
698     * </p><p>
699     * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
700     * wake lock, and {@link WakeLock#release release()} when you are done.
701     * </p><p>
702     * {@samplecode
703     * PowerManager pm = (PowerManager)mContext.getSystemService(
704     *                                          Context.POWER_SERVICE);
705     * PowerManager.WakeLock wl = pm.newWakeLock(
706     *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
707     *                                      | PowerManager.ON_AFTER_RELEASE,
708     *                                      TAG);
709     * wl.acquire();
710     * // ... do work...
711     * wl.release();
712     * }
713     * </p><p>
714     * Although a wake lock can be created without special permissions,
715     * the {@link android.Manifest.permission#WAKE_LOCK} permission is
716     * required to actually acquire or release the wake lock that is returned.
717     * </p><p class="note">
718     * If using this to keep the screen on, you should strongly consider using
719     * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
720     * This window flag will be correctly managed by the platform
721     * as the user moves between applications and doesn't require a special permission.
722     * </p>
723     *
724     * <p>
725     * Recommended naming conventions for tags to make debugging easier:
726     * <ul>
727     * <li>use a unique prefix delimited by a colon for your app/library (e.g.
728     * gmail:mytag) to make it easier to understand where the wake locks comes
729     * from. This namespace will also avoid collision for tags inside your app
730     * coming from different libraries which will make debugging easier.
731     * <li>use constants (e.g. do not include timestamps in the tag) to make it
732     * easier for tools to aggregate similar wake locks. When collecting
733     * debugging data, the platform only monitors a finite number of tags,
734     * using constants will help tools to provide better debugging data.
735     * <li>avoid using Class#getName() or similar method since this class name
736     * can be transformed by java optimizer and obfuscator tools.
737     * <li>avoid wrapping the tag or a prefix to avoid collision with wake lock
738     * tags from the platform (e.g. *alarm*).
739     * <li>never include personnally identifiable information for privacy
740     * reasons.
741     * </ul>
742     * </p>
743     *
744     * @param levelAndFlags Combination of wake lock level and flag values defining
745     * the requested behavior of the WakeLock.
746     * @param tag Your class name (or other tag) for debugging purposes.
747     *
748     * @see WakeLock#acquire()
749     * @see WakeLock#release()
750     * @see #PARTIAL_WAKE_LOCK
751     * @see #FULL_WAKE_LOCK
752     * @see #SCREEN_DIM_WAKE_LOCK
753     * @see #SCREEN_BRIGHT_WAKE_LOCK
754     * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
755     * @see #ACQUIRE_CAUSES_WAKEUP
756     * @see #ON_AFTER_RELEASE
757     */
758    public WakeLock newWakeLock(int levelAndFlags, String tag) {
759        validateWakeLockParameters(levelAndFlags, tag);
760        return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
761    }
762
763    /** @hide */
764    public static void validateWakeLockParameters(int levelAndFlags, String tag) {
765        switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
766            case PARTIAL_WAKE_LOCK:
767            case SCREEN_DIM_WAKE_LOCK:
768            case SCREEN_BRIGHT_WAKE_LOCK:
769            case FULL_WAKE_LOCK:
770            case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
771            case DOZE_WAKE_LOCK:
772            case DRAW_WAKE_LOCK:
773                break;
774            default:
775                throw new IllegalArgumentException("Must specify a valid wake lock level.");
776        }
777        if (tag == null) {
778            throw new IllegalArgumentException("The tag must not be null.");
779        }
780    }
781
782    /**
783     * Notifies the power manager that user activity happened.
784     * <p>
785     * Resets the auto-off timer and brightens the screen if the device
786     * is not asleep.  This is what happens normally when a key or the touch
787     * screen is pressed or when some other user activity occurs.
788     * This method does not wake up the device if it has been put to sleep.
789     * </p><p>
790     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
791     * </p>
792     *
793     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
794     * time base.  This timestamp is used to correctly order the user activity request with
795     * other power management functions.  It should be set
796     * to the timestamp of the input event that caused the user activity.
797     * @param noChangeLights If true, does not cause the keyboard backlight to turn on
798     * because of this event.  This is set when the power key is pressed.
799     * We want the device to stay on while the button is down, but we're about
800     * to turn off the screen so we don't want the keyboard backlight to turn on again.
801     * Otherwise the lights flash on and then off and it looks weird.
802     *
803     * @see #wakeUp
804     * @see #goToSleep
805     *
806     * @removed Requires signature or system permission.
807     * @deprecated Use {@link #userActivity(long, int, int)}.
808     */
809    @Deprecated
810    public void userActivity(long when, boolean noChangeLights) {
811        userActivity(when, USER_ACTIVITY_EVENT_OTHER,
812                noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
813    }
814
815    /**
816     * Notifies the power manager that user activity happened.
817     * <p>
818     * Resets the auto-off timer and brightens the screen if the device
819     * is not asleep.  This is what happens normally when a key or the touch
820     * screen is pressed or when some other user activity occurs.
821     * This method does not wake up the device if it has been put to sleep.
822     * </p><p>
823     * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
824     * {@link android.Manifest.permission#USER_ACTIVITY} permission.
825     * </p>
826     *
827     * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
828     * time base.  This timestamp is used to correctly order the user activity request with
829     * other power management functions.  It should be set
830     * to the timestamp of the input event that caused the user activity.
831     * @param event The user activity event.
832     * @param flags Optional user activity flags.
833     *
834     * @see #wakeUp
835     * @see #goToSleep
836     *
837     * @hide Requires signature or system permission.
838     */
839    @SystemApi
840    @RequiresPermission(anyOf = {
841            android.Manifest.permission.DEVICE_POWER,
842            android.Manifest.permission.USER_ACTIVITY
843    })
844    public void userActivity(long when, int event, int flags) {
845        try {
846            mService.userActivity(when, event, flags);
847        } catch (RemoteException e) {
848            throw e.rethrowFromSystemServer();
849        }
850    }
851
852   /**
853     * Forces the device to go to sleep.
854     * <p>
855     * Overrides all the wake locks that are held.
856     * This is what happens when the power key is pressed to turn off the screen.
857     * </p><p>
858     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
859     * </p>
860     *
861     * @param time The time when the request to go to sleep was issued, in the
862     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
863     * order the go to sleep request with other power management functions.  It should be set
864     * to the timestamp of the input event that caused the request to go to sleep.
865     *
866     * @see #userActivity
867     * @see #wakeUp
868     *
869     * @removed Requires signature permission.
870     */
871    public void goToSleep(long time) {
872        goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
873    }
874
875    /**
876     * Forces the device to go to sleep.
877     * <p>
878     * Overrides all the wake locks that are held.
879     * This is what happens when the power key is pressed to turn off the screen.
880     * </p><p>
881     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
882     * </p>
883     *
884     * @param time The time when the request to go to sleep was issued, in the
885     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
886     * order the go to sleep request with other power management functions.  It should be set
887     * to the timestamp of the input event that caused the request to go to sleep.
888     * @param reason The reason the device is going to sleep.
889     * @param flags Optional flags to apply when going to sleep.
890     *
891     * @see #userActivity
892     * @see #wakeUp
893     *
894     * @hide Requires signature permission.
895     */
896    public void goToSleep(long time, int reason, int flags) {
897        try {
898            mService.goToSleep(time, reason, flags);
899        } catch (RemoteException e) {
900            throw e.rethrowFromSystemServer();
901        }
902    }
903
904    /**
905     * Forces the device to wake up from sleep.
906     * <p>
907     * If the device is currently asleep, wakes it up, otherwise does nothing.
908     * This is what happens when the power key is pressed to turn on the screen.
909     * </p><p>
910     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
911     * </p>
912     *
913     * @param time The time when the request to wake up was issued, in the
914     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
915     * order the wake up request with other power management functions.  It should be set
916     * to the timestamp of the input event that caused the request to wake up.
917     *
918     * @see #userActivity
919     * @see #goToSleep
920     *
921     * @removed Requires signature permission.
922     */
923    public void wakeUp(long time) {
924        try {
925            mService.wakeUp(time, "wakeUp", mContext.getOpPackageName());
926        } catch (RemoteException e) {
927            throw e.rethrowFromSystemServer();
928        }
929    }
930
931    /**
932     * @hide
933     */
934    public void wakeUp(long time, String reason) {
935        try {
936            mService.wakeUp(time, reason, mContext.getOpPackageName());
937        } catch (RemoteException e) {
938            throw e.rethrowFromSystemServer();
939        }
940    }
941
942    /**
943     * Forces the device to start napping.
944     * <p>
945     * If the device is currently awake, starts dreaming, otherwise does nothing.
946     * When the dream ends or if the dream cannot be started, the device will
947     * either wake up or go to sleep depending on whether there has been recent
948     * user activity.
949     * </p><p>
950     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
951     * </p>
952     *
953     * @param time The time when the request to nap was issued, in the
954     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
955     * order the nap request with other power management functions.  It should be set
956     * to the timestamp of the input event that caused the request to nap.
957     *
958     * @see #wakeUp
959     * @see #goToSleep
960     *
961     * @hide Requires signature permission.
962     */
963    public void nap(long time) {
964        try {
965            mService.nap(time);
966        } catch (RemoteException e) {
967            throw e.rethrowFromSystemServer();
968        }
969    }
970
971    /**
972     * Boosts the brightness of the screen to maximum for a predetermined
973     * period of time.  This is used to make the screen more readable in bright
974     * daylight for a short duration.
975     * <p>
976     * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
977     * </p>
978     *
979     * @param time The time when the request to boost was issued, in the
980     * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
981     * order the boost request with other power management functions.  It should be set
982     * to the timestamp of the input event that caused the request to boost.
983     *
984     * @hide Requires signature permission.
985     */
986    public void boostScreenBrightness(long time) {
987        try {
988            mService.boostScreenBrightness(time);
989        } catch (RemoteException e) {
990            throw e.rethrowFromSystemServer();
991        }
992    }
993
994    /**
995     * Returns whether the screen brightness is currently boosted to maximum, caused by a call
996     * to {@link #boostScreenBrightness(long)}.
997     * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
998     *
999     * @deprecated This call is rarely used and will be phased out soon.
1000     * @hide
1001     * @removed
1002     */
1003    @SystemApi @Deprecated
1004    public boolean isScreenBrightnessBoosted() {
1005        return false;
1006    }
1007
1008   /**
1009     * Returns true if the specified wake lock level is supported.
1010     *
1011     * @param level The wake lock level to check.
1012     * @return True if the specified wake lock level is supported.
1013     */
1014    public boolean isWakeLockLevelSupported(int level) {
1015        try {
1016            return mService.isWakeLockLevelSupported(level);
1017        } catch (RemoteException e) {
1018            throw e.rethrowFromSystemServer();
1019        }
1020    }
1021
1022    /**
1023      * Returns true if the device is in an interactive state.
1024      * <p>
1025      * For historical reasons, the name of this method refers to the power state of
1026      * the screen but it actually describes the overall interactive state of
1027      * the device.  This method has been replaced by {@link #isInteractive}.
1028      * </p><p>
1029      * The value returned by this method only indicates whether the device is
1030      * in an interactive state which may have nothing to do with the screen being
1031      * on or off.  To determine the actual state of the screen,
1032      * use {@link android.view.Display#getState}.
1033      * </p>
1034      *
1035      * @return True if the device is in an interactive state.
1036      *
1037      * @deprecated Use {@link #isInteractive} instead.
1038      */
1039    @Deprecated
1040    public boolean isScreenOn() {
1041        return isInteractive();
1042    }
1043
1044    /**
1045     * Returns true if the device is in an interactive state.
1046     * <p>
1047     * When this method returns true, the device is awake and ready to interact
1048     * with the user (although this is not a guarantee that the user is actively
1049     * interacting with the device just this moment).  The main screen is usually
1050     * turned on while in this state.  Certain features, such as the proximity
1051     * sensor, may temporarily turn off the screen while still leaving the device in an
1052     * interactive state.  Note in particular that the device is still considered
1053     * to be interactive while dreaming (since dreams can be interactive) but not
1054     * when it is dozing or asleep.
1055     * </p><p>
1056     * When this method returns false, the device is dozing or asleep and must
1057     * be awoken before it will become ready to interact with the user again.  The
1058     * main screen is usually turned off while in this state.  Certain features,
1059     * such as "ambient mode" may cause the main screen to remain on (albeit in a
1060     * low power state) to display system-provided content while the device dozes.
1061     * </p><p>
1062     * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
1063     * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
1064     * whenever the interactive state of the device changes.  For historical reasons,
1065     * the names of these broadcasts refer to the power state of the screen
1066     * but they are actually sent in response to changes in the overall interactive
1067     * state of the device, as described by this method.
1068     * </p><p>
1069     * Services may use the non-interactive state as a hint to conserve power
1070     * since the user is not present.
1071     * </p>
1072     *
1073     * @return True if the device is in an interactive state.
1074     *
1075     * @see android.content.Intent#ACTION_SCREEN_ON
1076     * @see android.content.Intent#ACTION_SCREEN_OFF
1077     */
1078    public boolean isInteractive() {
1079        try {
1080            return mService.isInteractive();
1081        } catch (RemoteException e) {
1082            throw e.rethrowFromSystemServer();
1083        }
1084    }
1085
1086    /**
1087     * Reboot the device.  Will not return if the reboot is successful.
1088     * <p>
1089     * Requires the {@link android.Manifest.permission#REBOOT} permission.
1090     * </p>
1091     *
1092     * @param reason code to pass to the kernel (e.g., "recovery") to
1093     *               request special boot modes, or null.
1094     */
1095    public void reboot(String reason) {
1096        try {
1097            mService.reboot(false, reason, true);
1098        } catch (RemoteException e) {
1099            throw e.rethrowFromSystemServer();
1100        }
1101    }
1102
1103    /**
1104     * Reboot the device. Will not return if the reboot is successful.
1105     * <p>
1106     * Requires the {@link android.Manifest.permission#REBOOT} permission.
1107     * </p>
1108     * @hide
1109     */
1110    public void rebootSafeMode() {
1111        try {
1112            mService.rebootSafeMode(false, true);
1113        } catch (RemoteException e) {
1114            throw e.rethrowFromSystemServer();
1115        }
1116    }
1117
1118    /**
1119     * Returns true if the device is currently in power save mode.  When in this mode,
1120     * applications should reduce their functionality in order to conserve battery as
1121     * much as possible.  You can monitor for changes to this state with
1122     * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
1123     *
1124     * @return Returns true if currently in low power mode, else false.
1125     */
1126    public boolean isPowerSaveMode() {
1127        try {
1128            return mService.isPowerSaveMode();
1129        } catch (RemoteException e) {
1130            throw e.rethrowFromSystemServer();
1131        }
1132    }
1133
1134    /**
1135     * Set the current power save mode.
1136     *
1137     * @return True if the set was allowed.
1138     *
1139     * @see #isPowerSaveMode()
1140     *
1141     * @hide
1142     */
1143    public boolean setPowerSaveMode(boolean mode) {
1144        try {
1145            return mService.setPowerSaveMode(mode);
1146        } catch (RemoteException e) {
1147            throw e.rethrowFromSystemServer();
1148        }
1149    }
1150
1151    /**
1152     * Get data about the battery saver mode for a specific service
1153     * @param serviceType unique key for the service, one of {@link ServiceType}
1154     * @return Battery saver state data.
1155     *
1156     * @hide
1157     * @see com.android.server.power.BatterySaverPolicy
1158     * @see PowerSaveState
1159     */
1160    public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
1161        try {
1162            return mService.getPowerSaveState(serviceType);
1163        } catch (RemoteException e) {
1164            throw e.rethrowFromSystemServer();
1165        }
1166    }
1167
1168    /**
1169     * Returns how location features should behave when battery saver is on. When battery saver
1170     * is off, this will always return {@link #LOCATION_MODE_NO_CHANGE}.
1171     *
1172     * <p>This API is normally only useful for components that provide location features.
1173     *
1174     * @see #isPowerSaveMode()
1175     * @see #ACTION_POWER_SAVE_MODE_CHANGED
1176     */
1177    @LocationPowerSaveMode
1178    public int getLocationPowerSaveMode() {
1179        final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.GPS);
1180        if (!powerSaveState.globalBatterySaverEnabled) {
1181            return LOCATION_MODE_NO_CHANGE;
1182        }
1183        return powerSaveState.gpsMode;
1184    }
1185
1186    /**
1187     * Returns true if the device is currently in idle mode.  This happens when a device
1188     * has been sitting unused and unmoving for a sufficiently long period of time, so that
1189     * it decides to go into a lower power-use state.  This may involve things like turning
1190     * off network access to apps.  You can monitor for changes to this state with
1191     * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
1192     *
1193     * @return Returns true if currently in active device idle mode, else false.  This is
1194     * when idle mode restrictions are being actively applied; it will return false if the
1195     * device is in a long-term idle mode but currently running a maintenance window where
1196     * restrictions have been lifted.
1197     */
1198    public boolean isDeviceIdleMode() {
1199        try {
1200            return mService.isDeviceIdleMode();
1201        } catch (RemoteException e) {
1202            throw e.rethrowFromSystemServer();
1203        }
1204    }
1205
1206    /**
1207     * Returns true if the device is currently in light idle mode.  This happens when a device
1208     * has had its screen off for a short time, switching it into a batching mode where we
1209     * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
1210     * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
1211     *
1212     * @return Returns true if currently in active light device idle mode, else false.  This is
1213     * when light idle mode restrictions are being actively applied; it will return false if the
1214     * device is in a long-term idle mode but currently running a maintenance window where
1215     * restrictions have been lifted.
1216     * @hide
1217     */
1218    public boolean isLightDeviceIdleMode() {
1219        try {
1220            return mService.isLightDeviceIdleMode();
1221        } catch (RemoteException e) {
1222            throw e.rethrowFromSystemServer();
1223        }
1224    }
1225
1226    /**
1227     * Return whether the given application package name is on the device's power whitelist.
1228     * Apps can be placed on the whitelist through the settings UI invoked by
1229     * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
1230     */
1231    public boolean isIgnoringBatteryOptimizations(String packageName) {
1232        synchronized (this) {
1233            if (mIDeviceIdleController == null) {
1234                mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
1235                        ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
1236            }
1237        }
1238        try {
1239            return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
1240        } catch (RemoteException e) {
1241            throw e.rethrowFromSystemServer();
1242        }
1243    }
1244
1245    /**
1246     * Turn off the device.
1247     *
1248     * @param confirm If true, shows a shutdown confirmation dialog.
1249     * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
1250     * @param wait If true, this call waits for the shutdown to complete and does not return.
1251     *
1252     * @hide
1253     */
1254    public void shutdown(boolean confirm, String reason, boolean wait) {
1255        try {
1256            mService.shutdown(confirm, reason, wait);
1257        } catch (RemoteException e) {
1258            throw e.rethrowFromSystemServer();
1259        }
1260    }
1261
1262    /**
1263     * This function checks if the device has implemented Sustained Performance
1264     * Mode. This needs to be checked only once and is constant for a particular
1265     * device/release.
1266     *
1267     * Sustained Performance Mode is intended to provide a consistent level of
1268     * performance for prolonged amount of time.
1269     *
1270     * Applications should check if the device supports this mode, before using
1271     * {@link android.view.Window#setSustainedPerformanceMode}.
1272     *
1273     * @return Returns True if the device supports it, false otherwise.
1274     *
1275     * @see android.view.Window#setSustainedPerformanceMode
1276     */
1277    public boolean isSustainedPerformanceModeSupported() {
1278        return mContext.getResources().getBoolean(
1279                com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
1280    }
1281
1282    /**
1283     * If true, the doze component is not started until after the screen has been
1284     * turned off and the screen off animation has been performed.
1285     * @hide
1286     */
1287    public void setDozeAfterScreenOff(boolean dozeAfterScreenOf) {
1288        try {
1289            mService.setDozeAfterScreenOff(dozeAfterScreenOf);
1290        } catch (RemoteException e) {
1291            throw e.rethrowFromSystemServer();
1292        }
1293    }
1294
1295    /**
1296     * Returns the reason the phone was last shutdown. Calling app must have the
1297     * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information.
1298     * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could
1299     * not be accessed.
1300     * @hide
1301     */
1302    @ShutdownReason
1303    public int getLastShutdownReason() {
1304        try {
1305            return mService.getLastShutdownReason();
1306        } catch (RemoteException e) {
1307            throw e.rethrowFromSystemServer();
1308        }
1309    }
1310
1311    /**
1312     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1313     * This broadcast is only sent to registered receivers.
1314     */
1315    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1316    public static final String ACTION_POWER_SAVE_MODE_CHANGED
1317            = "android.os.action.POWER_SAVE_MODE_CHANGED";
1318
1319    /**
1320     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1321     * @hide
1322     */
1323    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1324    public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
1325            = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
1326
1327    /**
1328     * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1329     * This broadcast is only sent to registered receivers.
1330     */
1331    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1332    public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
1333            = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
1334
1335    /**
1336     * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1337     * This broadcast is only sent to registered receivers.
1338     * @hide
1339     */
1340    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1341    public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
1342            = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
1343
1344    /**
1345     * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
1346     * This broadcast is only sent to registered receivers.
1347     */
1348    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1349    public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
1350            = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
1351
1352    /**
1353     * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1354     * This broadcast is only sent to registered receivers.
1355     */
1356    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1357    public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
1358            = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
1359
1360    /**
1361     * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
1362     * This broadcast is only sent to registered receivers.
1363     *
1364     * @hide
1365     */
1366    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1367    public static final String ACTION_POWER_SAVE_MODE_CHANGING
1368            = "android.os.action.POWER_SAVE_MODE_CHANGING";
1369
1370    /** @hide */
1371    public static final String EXTRA_POWER_SAVE_MODE = "mode";
1372
1373    /**
1374     * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
1375     * This broadcast is only sent to registered receivers.
1376     *
1377     * @deprecated This intent is rarely used and will be phased out soon.
1378     * @hide
1379     * @removed
1380     **/
1381    @SystemApi @Deprecated
1382    public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
1383            = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
1384
1385    /**
1386     * A wake lock is a mechanism to indicate that your application needs
1387     * to have the device stay on.
1388     * <p>
1389     * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
1390     * permission in an {@code <uses-permission>} element of the application's manifest.
1391     * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
1392     * </p><p>
1393     * Call {@link #acquire()} to acquire the wake lock and force the device to stay
1394     * on at the level that was requested when the wake lock was created.
1395     * </p><p>
1396     * Call {@link #release()} when you are done and don't need the lock anymore.
1397     * It is very important to do this as soon as possible to avoid running down the
1398     * device's battery excessively.
1399     * </p>
1400     */
1401    public final class WakeLock {
1402        private int mFlags;
1403        private String mTag;
1404        private final String mPackageName;
1405        private final IBinder mToken;
1406        private int mInternalCount;
1407        private int mExternalCount;
1408        private boolean mRefCounted = true;
1409        private boolean mHeld;
1410        private WorkSource mWorkSource;
1411        private String mHistoryTag;
1412        private final String mTraceName;
1413
1414        private final Runnable mReleaser = new Runnable() {
1415            public void run() {
1416                release(RELEASE_FLAG_TIMEOUT);
1417            }
1418        };
1419
1420        WakeLock(int flags, String tag, String packageName) {
1421            mFlags = flags;
1422            mTag = tag;
1423            mPackageName = packageName;
1424            mToken = new Binder();
1425            mTraceName = "WakeLock (" + mTag + ")";
1426        }
1427
1428        @Override
1429        protected void finalize() throws Throwable {
1430            synchronized (mToken) {
1431                if (mHeld) {
1432                    Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
1433                    Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1434                    try {
1435                        mService.releaseWakeLock(mToken, 0);
1436                    } catch (RemoteException e) {
1437                        throw e.rethrowFromSystemServer();
1438                    }
1439                }
1440            }
1441        }
1442
1443        /**
1444         * Sets whether this WakeLock is reference counted.
1445         * <p>
1446         * Wake locks are reference counted by default.  If a wake lock is
1447         * reference counted, then each call to {@link #acquire()} must be
1448         * balanced by an equal number of calls to {@link #release()}.  If a wake
1449         * lock is not reference counted, then one call to {@link #release()} is
1450         * sufficient to undo the effect of all previous calls to {@link #acquire()}.
1451         * </p>
1452         *
1453         * @param value True to make the wake lock reference counted, false to
1454         * make the wake lock non-reference counted.
1455         */
1456        public void setReferenceCounted(boolean value) {
1457            synchronized (mToken) {
1458                mRefCounted = value;
1459            }
1460        }
1461
1462        /**
1463         * Acquires the wake lock.
1464         * <p>
1465         * Ensures that the device is on at the level requested when
1466         * the wake lock was created.
1467         * </p>
1468         */
1469        public void acquire() {
1470            synchronized (mToken) {
1471                acquireLocked();
1472            }
1473        }
1474
1475        /**
1476         * Acquires the wake lock with a timeout.
1477         * <p>
1478         * Ensures that the device is on at the level requested when
1479         * the wake lock was created.  The lock will be released after the given timeout
1480         * expires.
1481         * </p>
1482         *
1483         * @param timeout The timeout after which to release the wake lock, in milliseconds.
1484         */
1485        public void acquire(long timeout) {
1486            synchronized (mToken) {
1487                acquireLocked();
1488                mHandler.postDelayed(mReleaser, timeout);
1489            }
1490        }
1491
1492        private void acquireLocked() {
1493            mInternalCount++;
1494            mExternalCount++;
1495            if (!mRefCounted || mInternalCount == 1) {
1496                // Do this even if the wake lock is already thought to be held (mHeld == true)
1497                // because non-reference counted wake locks are not always properly released.
1498                // For example, the keyguard's wake lock might be forcibly released by the
1499                // power manager without the keyguard knowing.  A subsequent call to acquire
1500                // should immediately acquire the wake lock once again despite never having
1501                // been explicitly released by the keyguard.
1502                mHandler.removeCallbacks(mReleaser);
1503                Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
1504                try {
1505                    mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
1506                            mHistoryTag);
1507                } catch (RemoteException e) {
1508                    throw e.rethrowFromSystemServer();
1509                }
1510                mHeld = true;
1511            }
1512        }
1513
1514        /**
1515         * Releases the wake lock.
1516         * <p>
1517         * This method releases your claim to the CPU or screen being on.
1518         * The screen may turn off shortly after you release the wake lock, or it may
1519         * not if there are other wake locks still held.
1520         * </p>
1521         */
1522        public void release() {
1523            release(0);
1524        }
1525
1526        /**
1527         * Releases the wake lock with flags to modify the release behavior.
1528         * <p>
1529         * This method releases your claim to the CPU or screen being on.
1530         * The screen may turn off shortly after you release the wake lock, or it may
1531         * not if there are other wake locks still held.
1532         * </p>
1533         *
1534         * @param flags Combination of flag values to modify the release behavior.
1535         * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
1536         * Passing 0 is equivalent to calling {@link #release()}.
1537         */
1538        public void release(int flags) {
1539            synchronized (mToken) {
1540                if (mInternalCount > 0) {
1541                    // internal count must only be decreased if it is > 0 or state of
1542                    // the WakeLock object is broken.
1543                    mInternalCount--;
1544                }
1545                if ((flags & RELEASE_FLAG_TIMEOUT) == 0) {
1546                    mExternalCount--;
1547                }
1548                if (!mRefCounted || mInternalCount == 0) {
1549                    mHandler.removeCallbacks(mReleaser);
1550                    if (mHeld) {
1551                        Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
1552                        try {
1553                            mService.releaseWakeLock(mToken, flags);
1554                        } catch (RemoteException e) {
1555                            throw e.rethrowFromSystemServer();
1556                        }
1557                        mHeld = false;
1558                    }
1559                }
1560                if (mRefCounted && mExternalCount < 0) {
1561                    throw new RuntimeException("WakeLock under-locked " + mTag);
1562                }
1563            }
1564        }
1565
1566        /**
1567         * Returns true if the wake lock has been acquired but not yet released.
1568         *
1569         * @return True if the wake lock is held.
1570         */
1571        public boolean isHeld() {
1572            synchronized (mToken) {
1573                return mHeld;
1574            }
1575        }
1576
1577        /**
1578         * Sets the work source associated with the wake lock.
1579         * <p>
1580         * The work source is used to determine on behalf of which application
1581         * the wake lock is being held.  This is useful in the case where a
1582         * service is performing work on behalf of an application so that the
1583         * cost of that work can be accounted to the application.
1584         * </p>
1585         *
1586         * <p>
1587         * Make sure to follow the tag naming convention when using WorkSource
1588         * to make it easier for app developers to understand wake locks
1589         * attributed to them. See {@link PowerManager#newWakeLock(int, String)}
1590         * documentation.
1591         * </p>
1592         *
1593         * @param ws The work source, or null if none.
1594         */
1595        public void setWorkSource(WorkSource ws) {
1596            synchronized (mToken) {
1597                if (ws != null && ws.isEmpty()) {
1598                    ws = null;
1599                }
1600
1601                final boolean changed;
1602                if (ws == null) {
1603                    changed = mWorkSource != null;
1604                    mWorkSource = null;
1605                } else if (mWorkSource == null) {
1606                    changed = true;
1607                    mWorkSource = new WorkSource(ws);
1608                } else {
1609                    changed = !mWorkSource.equals(ws);
1610                    if (changed) {
1611                        mWorkSource.set(ws);
1612                    }
1613                }
1614
1615                if (changed && mHeld) {
1616                    try {
1617                        mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
1618                    } catch (RemoteException e) {
1619                        throw e.rethrowFromSystemServer();
1620                    }
1621                }
1622            }
1623        }
1624
1625        /** @hide */
1626        public void setTag(String tag) {
1627            mTag = tag;
1628        }
1629
1630        /** @hide */
1631        public String getTag() {
1632            return mTag;
1633        }
1634
1635        /** @hide */
1636        public void setHistoryTag(String tag) {
1637            mHistoryTag = tag;
1638        }
1639
1640        /** @hide */
1641        public void setUnimportantForLogging(boolean state) {
1642            if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
1643            else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
1644        }
1645
1646        @Override
1647        public String toString() {
1648            synchronized (mToken) {
1649                return "WakeLock{"
1650                    + Integer.toHexString(System.identityHashCode(this))
1651                    + " held=" + mHeld + ", refCount=" + mInternalCount + "}";
1652            }
1653        }
1654
1655        /** @hide */
1656        public void writeToProto(ProtoOutputStream proto, long fieldId) {
1657            synchronized (mToken) {
1658                final long token = proto.start(fieldId);
1659                proto.write(PowerManagerProto.WakeLock.TAG, mTag);
1660                proto.write(PowerManagerProto.WakeLock.PACKAGE_NAME, mPackageName);
1661                proto.write(PowerManagerProto.WakeLock.HELD, mHeld);
1662                proto.write(PowerManagerProto.WakeLock.INTERNAL_COUNT, mInternalCount);
1663                if (mWorkSource != null) {
1664                    mWorkSource.writeToProto(proto, PowerManagerProto.WakeLock.WORK_SOURCE);
1665                }
1666                proto.end(token);
1667            }
1668        }
1669
1670        /**
1671         * Wraps a Runnable such that this method immediately acquires the wake lock and then
1672         * once the Runnable is done the wake lock is released.
1673         *
1674         * <p>Example:
1675         *
1676         * <pre>
1677         * mHandler.post(mWakeLock.wrap(() -> {
1678         *     // do things on handler, lock is held while we're waiting for this
1679         *     // to get scheduled and until the runnable is done executing.
1680         * });
1681         * </pre>
1682         *
1683         * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
1684         *    leak the wakelock!
1685         *
1686         * @hide
1687         */
1688        public Runnable wrap(Runnable r) {
1689            acquire();
1690            return () -> {
1691                try {
1692                    r.run();
1693                } finally {
1694                    release();
1695                }
1696            };
1697        }
1698    }
1699}
1700