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