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 
17 package android.os;
18 
19 import android.Manifest.permission;
20 import android.annotation.CallbackExecutor;
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.RequiresPermission;
25 import android.annotation.SdkConstant;
26 import android.annotation.SystemApi;
27 import android.annotation.SystemService;
28 import android.annotation.TestApi;
29 import android.compat.annotation.UnsupportedAppUsage;
30 import android.content.Context;
31 import android.service.dreams.Sandman;
32 import android.sysprop.InitProperties;
33 import android.util.ArrayMap;
34 import android.util.Log;
35 import android.util.proto.ProtoOutputStream;
36 
37 import com.android.internal.util.Preconditions;
38 
39 import java.lang.annotation.Retention;
40 import java.lang.annotation.RetentionPolicy;
41 import java.util.concurrent.Executor;
42 
43 /**
44  * This class gives you control of the power state of the device.
45  *
46  * <p>
47  * <b>Device battery life will be significantly affected by the use of this API.</b>
48  * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
49  * possible, and be sure to release them as soon as possible. In most cases,
50  * you'll want to use
51  * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
52  *
53  * <p>
54  * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
55  * permission in an {@code <uses-permission>} element of the application's manifest.
56  * </p>
57  */
58 @SystemService(Context.POWER_SERVICE)
59 public final class PowerManager {
60     private static final String TAG = "PowerManager";
61 
62     /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
63      * combinations were actually supported so the bit field was removed.  This explains
64      * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
65      * value (in frameworks/base/core/proto/android/os/enums.proto) can be used.
66      */
67 
68     /**
69      * Wake lock level: Ensures that the CPU is running; the screen and keyboard
70      * backlight will be allowed to go off.
71      * <p>
72      * If the user presses the power button, then the screen will be turned off
73      * but the CPU will be kept on until all partial wake locks have been released.
74      * </p>
75      */
76     public static final int PARTIAL_WAKE_LOCK = OsProtoEnums.PARTIAL_WAKE_LOCK; // 0x00000001
77 
78     /**
79      * Wake lock level: Ensures that the screen is on (but may be dimmed);
80      * the keyboard backlight will be allowed to go off.
81      * <p>
82      * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
83      * implicitly released by the system, causing both the screen and the CPU to be turned off.
84      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
85      * </p>
86      *
87      * @deprecated Most applications should use
88      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
89      * of this type of wake lock, as it will be correctly managed by the platform
90      * as the user moves between applications and doesn't require a special permission.
91      */
92     @Deprecated
93     public static final int SCREEN_DIM_WAKE_LOCK = OsProtoEnums.SCREEN_DIM_WAKE_LOCK; // 0x00000006
94 
95     /**
96      * Wake lock level: Ensures that the screen is on at full brightness;
97      * the keyboard backlight will be allowed to go off.
98      * <p>
99      * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
100      * implicitly released by the system, causing both the screen and the CPU to be turned off.
101      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
102      * </p>
103      *
104      * @deprecated Most applications should use
105      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
106      * of this type of wake lock, as it will be correctly managed by the platform
107      * as the user moves between applications and doesn't require a special permission.
108      */
109     @Deprecated
110     public static final int SCREEN_BRIGHT_WAKE_LOCK =
111             OsProtoEnums.SCREEN_BRIGHT_WAKE_LOCK; // 0x0000000a
112 
113     /**
114      * Wake lock level: Ensures that the screen and keyboard backlight are on at
115      * full brightness.
116      * <p>
117      * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
118      * implicitly released by the system, causing both the screen and the CPU to be turned off.
119      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
120      * </p>
121      *
122      * @deprecated Most applications should use
123      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
124      * of this type of wake lock, as it will be correctly managed by the platform
125      * as the user moves between applications and doesn't require a special permission.
126      */
127     @Deprecated
128     public static final int FULL_WAKE_LOCK = OsProtoEnums.FULL_WAKE_LOCK; // 0x0000001a
129 
130     /**
131      * Wake lock level: Turns the screen off when the proximity sensor activates.
132      * <p>
133      * If the proximity sensor detects that an object is nearby, the screen turns off
134      * immediately.  Shortly after the object moves away, the screen turns on again.
135      * </p><p>
136      * A proximity wake lock does not prevent the device from falling asleep
137      * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
138      * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
139      * wake locks are held, then the device will fall asleep (and lock) as usual.
140      * However, the device will not fall asleep while the screen has been turned off
141      * by the proximity sensor because it effectively counts as ongoing user activity.
142      * </p><p>
143      * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
144      * to determine whether this wake lock level is supported.
145      * </p><p>
146      * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
147      * </p>
148      */
149     public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK =
150             OsProtoEnums.PROXIMITY_SCREEN_OFF_WAKE_LOCK; // 0x00000020
151 
152     /**
153      * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
154      * if no other wake locks are held.
155      * <p>
156      * This is used by the dream manager to implement doze mode.  It currently
157      * has no effect unless the power manager is in the dozing state.
158      * </p><p>
159      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
160      * </p>
161      *
162      * {@hide}
163      */
164     public static final int DOZE_WAKE_LOCK = OsProtoEnums.DOZE_WAKE_LOCK; // 0x00000040
165 
166     /**
167      * Wake lock level: Keep the device awake enough to allow drawing to occur.
168      * <p>
169      * This is used by the window manager to allow applications to draw while the
170      * system is dozing.  It currently has no effect unless the power manager is in
171      * the dozing state.
172      * </p><p>
173      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
174      * </p>
175      *
176      * {@hide}
177      */
178     public static final int DRAW_WAKE_LOCK = OsProtoEnums.DRAW_WAKE_LOCK; // 0x00000080
179 
180     /**
181      * Mask for the wake lock level component of a combined wake lock level and flags integer.
182      *
183      * @hide
184      */
185     public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
186 
187     /**
188      * Wake lock flag: Turn the screen on when the wake lock is acquired.
189      * <p>
190      * Normally wake locks don't actually wake the device, they just cause
191      * the screen to remain on once it's already on.  Think of the video player
192      * application as the normal behavior.  Notifications that pop up and want
193      * the device to be on are the exception; use this flag to be like them.
194      * </p><p>
195      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
196      * </p>
197      */
198     public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
199 
200     /**
201      * Wake lock flag: When this wake lock is released, poke the user activity timer
202      * so the screen stays on for a little longer.
203      * <p>
204      * Will not turn the screen on if it is not already on.
205      * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
206      * </p><p>
207      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
208      * </p>
209      */
210     public static final int ON_AFTER_RELEASE = 0x20000000;
211 
212     /**
213      * Wake lock flag: This wake lock is not important for logging events.  If a later
214      * wake lock is acquired that is important, it will be considered the one to log.
215      * @hide
216      */
217     public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
218 
219     /**
220      * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
221      * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
222      * indicates that an object is not in close proximity.
223      */
224     public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1 << 0;
225 
226     /**
227      * Flag for {@link WakeLock#release(int)} when called due to timeout.
228      * @hide
229      */
230     public static final int RELEASE_FLAG_TIMEOUT = 1 << 16;
231 
232     /**
233      * Brightness value for fully on.
234      * @hide
235      */
236     @UnsupportedAppUsage
237     public static final int BRIGHTNESS_ON = 255;
238 
239     /**
240      * Brightness value for fully off.
241      * @hide
242      */
243     public static final int BRIGHTNESS_OFF = 0;
244 
245     /**
246      * Brightness value for default policy handling by the system.
247      * @hide
248      */
249     public static final int BRIGHTNESS_DEFAULT = -1;
250 
251     // Note: Be sure to update android.os.BatteryStats and PowerManager.h
252     // if adding or modifying user activity event constants.
253 
254     /**
255      * User activity event type: Unspecified event type.
256      * @hide
257      */
258     @SystemApi
259     public static final int USER_ACTIVITY_EVENT_OTHER = 0;
260 
261     /**
262      * User activity event type: Button or key pressed or released.
263      * @hide
264      */
265     @SystemApi
266     public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
267 
268     /**
269      * User activity event type: Touch down, move or up.
270      * @hide
271      */
272     @SystemApi
273     public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
274 
275     /**
276      * User activity event type: Accessibility taking action on behalf of user.
277      * @hide
278      */
279     @SystemApi
280     public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
281 
282     /**
283      * User activity event type: {@link android.service.attention.AttentionService} taking action
284      * on behalf of user.
285      * @hide
286      */
287     public static final int USER_ACTIVITY_EVENT_ATTENTION = 4;
288 
289     /**
290      * User activity flag: If already dimmed, extend the dim timeout
291      * but do not brighten.  This flag is useful for keeping the screen on
292      * a little longer without causing a visible change such as when
293      * the power key is pressed.
294      * @hide
295      */
296     @SystemApi
297     public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
298 
299     /**
300      * User activity flag: Note the user activity as usual but do not
301      * reset the user activity timeout.  This flag is useful for applying
302      * user activity power hints when interacting with the device indirectly
303      * on a secondary screen while allowing the primary screen to go to sleep.
304      * @hide
305      */
306     @SystemApi
307     public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
308 
309     /**
310      * @hide
311      */
312     public static final int GO_TO_SLEEP_REASON_MIN = 0;
313 
314     /**
315      * Go to sleep reason code: Going to sleep due by application request.
316      * @hide
317      */
318     public static final int GO_TO_SLEEP_REASON_APPLICATION = GO_TO_SLEEP_REASON_MIN;
319 
320     /**
321      * Go to sleep reason code: Going to sleep due by request of the
322      * device administration policy.
323      * @hide
324      */
325     public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
326 
327     /**
328      * Go to sleep reason code: Going to sleep due to a screen timeout.
329      * @hide
330      */
331     @UnsupportedAppUsage
332     public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
333 
334     /**
335      * Go to sleep reason code: Going to sleep due to the lid switch being closed.
336      * @hide
337      */
338     public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
339 
340     /**
341      * Go to sleep reason code: Going to sleep due to the power button being pressed.
342      * @hide
343      */
344     public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
345 
346     /**
347      * Go to sleep reason code: Going to sleep due to HDMI.
348      * @hide
349      */
350     public static final int GO_TO_SLEEP_REASON_HDMI = 5;
351 
352     /**
353      * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
354      * @hide
355      */
356     public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
357 
358     /**
359      * Go to sleep reason code: Going to sleep by request of an accessibility service
360      * @hide
361      */
362     public static final int GO_TO_SLEEP_REASON_ACCESSIBILITY = 7;
363 
364     /**
365      * Go to sleep reason code: Going to sleep due to force-suspend.
366      * @hide
367      */
368     public static final int GO_TO_SLEEP_REASON_FORCE_SUSPEND = 8;
369 
370     /**
371      * @hide
372      */
373     public static final int GO_TO_SLEEP_REASON_MAX = GO_TO_SLEEP_REASON_FORCE_SUSPEND;
374 
375     /**
376      * @hide
377      */
sleepReasonToString(int sleepReason)378     public static String sleepReasonToString(int sleepReason) {
379         switch (sleepReason) {
380             case GO_TO_SLEEP_REASON_APPLICATION: return "application";
381             case GO_TO_SLEEP_REASON_DEVICE_ADMIN: return "device_admin";
382             case GO_TO_SLEEP_REASON_TIMEOUT: return "timeout";
383             case GO_TO_SLEEP_REASON_LID_SWITCH: return "lid_switch";
384             case GO_TO_SLEEP_REASON_POWER_BUTTON: return "power_button";
385             case GO_TO_SLEEP_REASON_HDMI: return "hdmi";
386             case GO_TO_SLEEP_REASON_SLEEP_BUTTON: return "sleep_button";
387             case GO_TO_SLEEP_REASON_ACCESSIBILITY: return "accessibility";
388             case GO_TO_SLEEP_REASON_FORCE_SUSPEND: return "force_suspend";
389             default: return Integer.toString(sleepReason);
390         }
391     }
392 
393     /**
394      * Go to sleep flag: Skip dozing state and directly go to full sleep.
395      * @hide
396      */
397     public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
398 
399     /**
400      * @hide
401      */
402     @IntDef(prefix = { "WAKE_REASON_" }, value = {
403             WAKE_REASON_UNKNOWN,
404             WAKE_REASON_POWER_BUTTON,
405             WAKE_REASON_APPLICATION,
406             WAKE_REASON_PLUGGED_IN,
407             WAKE_REASON_GESTURE,
408             WAKE_REASON_CAMERA_LAUNCH,
409             WAKE_REASON_WAKE_KEY,
410             WAKE_REASON_WAKE_MOTION,
411             WAKE_REASON_HDMI,
412     })
413     @Retention(RetentionPolicy.SOURCE)
414     public @interface WakeReason{}
415 
416     /**
417      * Wake up reason code: Waking for an unknown reason.
418      * @hide
419      */
420     public static final int WAKE_REASON_UNKNOWN = 0;
421 
422     /**
423      * Wake up reason code: Waking up due to power button press.
424      * @hide
425      */
426     public static final int WAKE_REASON_POWER_BUTTON = 1;
427 
428     /**
429      * Wake up reason code: Waking up because an application requested it.
430      * @hide
431      */
432     public static final int WAKE_REASON_APPLICATION = 2;
433 
434     /**
435      * Wake up reason code: Waking up due to being plugged in or docked on a wireless charger.
436      * @hide
437      */
438     public static final int WAKE_REASON_PLUGGED_IN = 3;
439 
440     /**
441      * Wake up reason code: Waking up due to a user performed gesture (e.g. douple tapping on the
442      * screen).
443      * @hide
444      */
445     public static final int WAKE_REASON_GESTURE = 4;
446 
447     /**
448      * Wake up reason code: Waking up due to the camera being launched.
449      * @hide
450      */
451     public static final int WAKE_REASON_CAMERA_LAUNCH = 5;
452 
453     /**
454      * Wake up reason code: Waking up because a wake key other than power was pressed.
455      * @hide
456      */
457     public static final int WAKE_REASON_WAKE_KEY = 6;
458 
459     /**
460      * Wake up reason code: Waking up because a wake motion was performed.
461      *
462      * For example, a trackball that was set to wake the device up was spun.
463      * @hide
464      */
465     public static final int WAKE_REASON_WAKE_MOTION = 7;
466 
467     /**
468      * Wake up reason code: Waking due to HDMI.
469      * @hide
470      */
471     public static final int WAKE_REASON_HDMI = 8;
472 
473     /**
474      * Wake up reason code: Waking due to the lid being opened.
475      * @hide
476      */
477     public static final int WAKE_REASON_LID = 9;
478 
479     /**
480      * Convert the wake reason to a string for debugging purposes.
481      * @hide
482      */
wakeReasonToString(@akeReason int wakeReason)483     public static String wakeReasonToString(@WakeReason int wakeReason) {
484         switch (wakeReason) {
485             case WAKE_REASON_UNKNOWN: return "WAKE_REASON_UNKNOWN";
486             case WAKE_REASON_POWER_BUTTON: return "WAKE_REASON_POWER_BUTTON";
487             case WAKE_REASON_APPLICATION: return "WAKE_REASON_APPLICATION";
488             case WAKE_REASON_PLUGGED_IN: return "WAKE_REASON_PLUGGED_IN";
489             case WAKE_REASON_GESTURE: return "WAKE_REASON_GESTURE";
490             case WAKE_REASON_CAMERA_LAUNCH: return "WAKE_REASON_CAMERA_LAUNCH";
491             case WAKE_REASON_WAKE_KEY: return "WAKE_REASON_WAKE_KEY";
492             case WAKE_REASON_WAKE_MOTION: return "WAKE_REASON_WAKE_MOTION";
493             case WAKE_REASON_HDMI: return "WAKE_REASON_HDMI";
494             case WAKE_REASON_LID: return "WAKE_REASON_LID";
495             default: return Integer.toString(wakeReason);
496         }
497     }
498 
499     /**
500      * @hide
501      */
502     public static class WakeData {
WakeData(long wakeTime, @WakeReason int wakeReason)503         public WakeData(long wakeTime, @WakeReason int wakeReason) {
504             this.wakeTime = wakeTime;
505             this.wakeReason = wakeReason;
506         }
507         public long wakeTime;
508         public @WakeReason int wakeReason;
509     }
510 
511     /**
512      * The value to pass as the 'reason' argument to reboot() to reboot into
513      * recovery mode for tasks other than applying system updates, such as
514      * doing factory resets.
515      * <p>
516      * Requires the {@link android.Manifest.permission#RECOVERY}
517      * permission (in addition to
518      * {@link android.Manifest.permission#REBOOT}).
519      * </p>
520      * @hide
521      */
522     public static final String REBOOT_RECOVERY = "recovery";
523 
524     /**
525      * The value to pass as the 'reason' argument to reboot() to reboot into
526      * recovery mode for applying system updates.
527      * <p>
528      * Requires the {@link android.Manifest.permission#RECOVERY}
529      * permission (in addition to
530      * {@link android.Manifest.permission#REBOOT}).
531      * </p>
532      * @hide
533      */
534     public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
535 
536     /**
537      * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
538      * the device.
539      * @hide
540      */
541     public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
542 
543     /**
544      * The 'reason' value used when rebooting in safe mode
545      * @hide
546      */
547     public static final String REBOOT_SAFE_MODE = "safemode";
548 
549     /**
550      * The 'reason' value used for rebooting userspace.
551      * @hide
552      */
553     @SystemApi
554     public static final String REBOOT_USERSPACE = "userspace";
555 
556     /**
557      * The 'reason' value used when rebooting the device without turning on the screen.
558      * @hide
559      */
560     public static final String REBOOT_QUIESCENT = "quiescent";
561 
562     /**
563      * The value to pass as the 'reason' argument to android_reboot().
564      * @hide
565      */
566     public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
567 
568     /**
569      * The value to pass as the 'reason' argument to android_reboot() when battery temperature
570      * is too high.
571      * @hide
572      */
573     public static final String SHUTDOWN_BATTERY_THERMAL_STATE = "thermal,battery";
574 
575     /**
576      * The value to pass as the 'reason' argument to android_reboot() when device temperature
577      * is too high.
578      * @hide
579      */
580     public static final String SHUTDOWN_THERMAL_STATE = "thermal";
581 
582     /**
583      * The value to pass as the 'reason' argument to android_reboot() when device is running
584      * critically low on battery.
585      * @hide
586      */
587     public static final String SHUTDOWN_LOW_BATTERY = "battery";
588 
589     /**
590      * @hide
591      */
592     @Retention(RetentionPolicy.SOURCE)
593     @IntDef(prefix = { "SHUTDOWN_REASON_" }, value = {
594             SHUTDOWN_REASON_UNKNOWN,
595             SHUTDOWN_REASON_SHUTDOWN,
596             SHUTDOWN_REASON_REBOOT,
597             SHUTDOWN_REASON_USER_REQUESTED,
598             SHUTDOWN_REASON_THERMAL_SHUTDOWN,
599             SHUTDOWN_REASON_LOW_BATTERY,
600             SHUTDOWN_REASON_BATTERY_THERMAL
601     })
602     public @interface ShutdownReason {}
603 
604     /**
605      * constant for shutdown reason being unknown.
606      * @hide
607      */
608     public static final int SHUTDOWN_REASON_UNKNOWN = 0;
609 
610     /**
611      * constant for shutdown reason being normal shutdown.
612      * @hide
613      */
614     public static final int SHUTDOWN_REASON_SHUTDOWN = 1;
615 
616     /**
617      * constant for shutdown reason being reboot.
618      * @hide
619      */
620     public static final int SHUTDOWN_REASON_REBOOT = 2;
621 
622     /**
623      * constant for shutdown reason being user requested.
624      * @hide
625      */
626     public static final int SHUTDOWN_REASON_USER_REQUESTED = 3;
627 
628     /**
629      * constant for shutdown reason being overheating.
630      * @hide
631      */
632     public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4;
633 
634     /**
635      * constant for shutdown reason being low battery.
636      * @hide
637      */
638     public static final int SHUTDOWN_REASON_LOW_BATTERY = 5;
639 
640     /**
641      * constant for shutdown reason being critical battery thermal state.
642      * @hide
643      */
644     public static final int SHUTDOWN_REASON_BATTERY_THERMAL = 6;
645 
646     /**
647      * @hide
648      */
649     @Retention(RetentionPolicy.SOURCE)
650     @IntDef({ServiceType.LOCATION,
651             ServiceType.VIBRATION,
652             ServiceType.ANIMATION,
653             ServiceType.FULL_BACKUP,
654             ServiceType.KEYVALUE_BACKUP,
655             ServiceType.NETWORK_FIREWALL,
656             ServiceType.SCREEN_BRIGHTNESS,
657             ServiceType.SOUND,
658             ServiceType.BATTERY_STATS,
659             ServiceType.DATA_SAVER,
660             ServiceType.FORCE_ALL_APPS_STANDBY,
661             ServiceType.FORCE_BACKGROUND_CHECK,
662             ServiceType.OPTIONAL_SENSORS,
663             ServiceType.AOD,
664             ServiceType.QUICK_DOZE,
665             ServiceType.NIGHT_MODE,
666     })
667     public @interface ServiceType {
668         int NULL = 0;
669         int LOCATION = 1;
670         int VIBRATION = 2;
671         int ANIMATION = 3;
672         int FULL_BACKUP = 4;
673         int KEYVALUE_BACKUP = 5;
674         int NETWORK_FIREWALL = 6;
675         int SCREEN_BRIGHTNESS = 7;
676         int SOUND = 8;
677         int BATTERY_STATS = 9;
678         int DATA_SAVER = 10;
679         int AOD = 14;
680 
681         /**
682          * Whether to enable force-app-standby on all apps or not.
683          */
684         int FORCE_ALL_APPS_STANDBY = 11;
685 
686         /**
687          * Whether to enable background check on all apps or not.
688          */
689         int FORCE_BACKGROUND_CHECK = 12;
690 
691         /**
692          * Whether to disable non-essential sensors. (e.g. edge sensors.)
693          */
694         int OPTIONAL_SENSORS = 13;
695 
696         /**
697          * Whether to go into Deep Doze as soon as the screen turns off or not.
698          */
699         int QUICK_DOZE = 15;
700 
701         /**
702          * Whether to enable night mode when battery saver is enabled.
703          */
704         int NIGHT_MODE = 16;
705     }
706 
707     /**
708      * Either the location providers shouldn't be affected by battery saver,
709      * or battery saver is off.
710      */
711     public static final int LOCATION_MODE_NO_CHANGE = 0;
712 
713     /**
714      * In this mode, the GPS based location provider should be disabled when battery saver is on and
715      * the device is non-interactive.
716      */
717     public static final int LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 1;
718 
719     /**
720      * All location providers should be disabled when battery saver is on and
721      * the device is non-interactive.
722      */
723     public static final int LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 2;
724 
725     /**
726      * In this mode, all the location providers will be kept available, but location fixes
727      * should only be provided to foreground apps.
728      */
729     public static final int LOCATION_MODE_FOREGROUND_ONLY = 3;
730 
731     /**
732      * In this mode, location will not be turned off, but LocationManager will throttle all
733      * requests to providers when the device is non-interactive.
734      */
735     public static final int LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 4;
736 
737     /** @hide */
738     public static final int MIN_LOCATION_MODE = LOCATION_MODE_NO_CHANGE;
739     /** @hide */
740     public static final int MAX_LOCATION_MODE = LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF;
741 
742     /**
743      * @hide
744      */
745     @Retention(RetentionPolicy.SOURCE)
746     @IntDef(prefix = {"LOCATION_MODE_"}, value = {
747             LOCATION_MODE_NO_CHANGE,
748             LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF,
749             LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF,
750             LOCATION_MODE_FOREGROUND_ONLY,
751             LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF,
752     })
753     public @interface LocationPowerSaveMode {}
754 
755     /** @hide */
locationPowerSaveModeToString(@ocationPowerSaveMode int mode)756     public static String locationPowerSaveModeToString(@LocationPowerSaveMode int mode) {
757         switch (mode) {
758             case LOCATION_MODE_NO_CHANGE:
759                 return "NO_CHANGE";
760             case LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF:
761                 return "GPS_DISABLED_WHEN_SCREEN_OFF";
762             case LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF:
763                 return "ALL_DISABLED_WHEN_SCREEN_OFF";
764             case LOCATION_MODE_FOREGROUND_ONLY:
765                 return "FOREGROUND_ONLY";
766             case LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF:
767                 return "THROTTLE_REQUESTS_WHEN_SCREEN_OFF";
768             default:
769                 return Integer.toString(mode);
770         }
771     }
772 
773     final Context mContext;
774     @UnsupportedAppUsage
775     final IPowerManager mService;
776     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
777     final Handler mHandler;
778 
779     IThermalService mThermalService;
780     private final ArrayMap<OnThermalStatusChangedListener, IThermalStatusListener>
781             mListenerMap = new ArrayMap<>();
782 
783     IDeviceIdleController mIDeviceIdleController;
784 
785     /**
786      * {@hide}
787      */
PowerManager(Context context, IPowerManager service, Handler handler)788     public PowerManager(Context context, IPowerManager service, Handler handler) {
789         mContext = context;
790         mService = service;
791         mHandler = handler;
792     }
793 
794     /**
795      * Gets the minimum supported screen brightness setting.
796      * The screen may be allowed to become dimmer than this value but
797      * this is the minimum value that can be set by the user.
798      * @hide
799      */
800     @UnsupportedAppUsage
getMinimumScreenBrightnessSetting()801     public int getMinimumScreenBrightnessSetting() {
802         return mContext.getResources().getInteger(
803                 com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
804     }
805 
806     /**
807      * Gets the maximum supported screen brightness setting.
808      * The screen may be allowed to become dimmer than this value but
809      * this is the maximum value that can be set by the user.
810      * @hide
811      */
812     @UnsupportedAppUsage
getMaximumScreenBrightnessSetting()813     public int getMaximumScreenBrightnessSetting() {
814         return mContext.getResources().getInteger(
815                 com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
816     }
817 
818     /**
819      * Gets the default screen brightness setting.
820      * @hide
821      */
822     @UnsupportedAppUsage
getDefaultScreenBrightnessSetting()823     public int getDefaultScreenBrightnessSetting() {
824         return mContext.getResources().getInteger(
825                 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
826     }
827 
828     /**
829      * Gets the minimum supported screen brightness setting for VR Mode.
830      * @hide
831      */
getMinimumScreenBrightnessForVrSetting()832     public int getMinimumScreenBrightnessForVrSetting() {
833         return mContext.getResources().getInteger(
834                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum);
835     }
836 
837     /**
838      * Gets the maximum supported screen brightness setting for VR Mode.
839      * The screen may be allowed to become dimmer than this value but
840      * this is the maximum value that can be set by the user.
841      * @hide
842      */
getMaximumScreenBrightnessForVrSetting()843     public int getMaximumScreenBrightnessForVrSetting() {
844         return mContext.getResources().getInteger(
845                 com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum);
846     }
847 
848     /**
849      * Gets the default screen brightness for VR setting.
850      * @hide
851      */
getDefaultScreenBrightnessForVrSetting()852     public int getDefaultScreenBrightnessForVrSetting() {
853         return mContext.getResources().getInteger(
854                 com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
855     }
856 
857     /**
858      * Creates a new wake lock with the specified level and flags.
859      * <p>
860      * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
861      * combined using the logical OR operator.
862      * </p><p>
863      * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
864      * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
865      * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
866      * specified as part of the {@code levelAndFlags} parameter.
867      * </p>
868      * <p>
869      * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
870      * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
871      * {@code levelAndFlags} parameters.
872      * </p><p>
873      * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
874      * wake lock, and {@link WakeLock#release release()} when you are done.
875      * </p><p>
876      * {@samplecode
877      * PowerManager pm = (PowerManager)mContext.getSystemService(
878      *                                          Context.POWER_SERVICE);
879      * PowerManager.WakeLock wl = pm.newWakeLock(
880      *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
881      *                                      | PowerManager.ON_AFTER_RELEASE,
882      *                                      TAG);
883      * wl.acquire();
884      * // ... do work...
885      * wl.release();
886      * }
887      * </p><p>
888      * Although a wake lock can be created without special permissions,
889      * the {@link android.Manifest.permission#WAKE_LOCK} permission is
890      * required to actually acquire or release the wake lock that is returned.
891      * </p><p class="note">
892      * If using this to keep the screen on, you should strongly consider using
893      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
894      * This window flag will be correctly managed by the platform
895      * as the user moves between applications and doesn't require a special permission.
896      * </p>
897      *
898      * <p>
899      * Recommended naming conventions for tags to make debugging easier:
900      * <ul>
901      * <li>use a unique prefix delimited by a colon for your app/library (e.g.
902      * gmail:mytag) to make it easier to understand where the wake locks comes
903      * from. This namespace will also avoid collision for tags inside your app
904      * coming from different libraries which will make debugging easier.
905      * <li>use constants (e.g. do not include timestamps in the tag) to make it
906      * easier for tools to aggregate similar wake locks. When collecting
907      * debugging data, the platform only monitors a finite number of tags,
908      * using constants will help tools to provide better debugging data.
909      * <li>avoid using Class#getName() or similar method since this class name
910      * can be transformed by java optimizer and obfuscator tools.
911      * <li>avoid wrapping the tag or a prefix to avoid collision with wake lock
912      * tags from the platform (e.g. *alarm*).
913      * <li>never include personnally identifiable information for privacy
914      * reasons.
915      * </ul>
916      * </p>
917      *
918      * @param levelAndFlags Combination of wake lock level and flag values defining
919      * the requested behavior of the WakeLock.
920      * @param tag Your class name (or other tag) for debugging purposes.
921      *
922      * @see WakeLock#acquire()
923      * @see WakeLock#release()
924      * @see #PARTIAL_WAKE_LOCK
925      * @see #FULL_WAKE_LOCK
926      * @see #SCREEN_DIM_WAKE_LOCK
927      * @see #SCREEN_BRIGHT_WAKE_LOCK
928      * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
929      * @see #ACQUIRE_CAUSES_WAKEUP
930      * @see #ON_AFTER_RELEASE
931      */
newWakeLock(int levelAndFlags, String tag)932     public WakeLock newWakeLock(int levelAndFlags, String tag) {
933         validateWakeLockParameters(levelAndFlags, tag);
934         return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
935     }
936 
937     /** @hide */
938     @UnsupportedAppUsage
validateWakeLockParameters(int levelAndFlags, String tag)939     public static void validateWakeLockParameters(int levelAndFlags, String tag) {
940         switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
941             case PARTIAL_WAKE_LOCK:
942             case SCREEN_DIM_WAKE_LOCK:
943             case SCREEN_BRIGHT_WAKE_LOCK:
944             case FULL_WAKE_LOCK:
945             case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
946             case DOZE_WAKE_LOCK:
947             case DRAW_WAKE_LOCK:
948                 break;
949             default:
950                 throw new IllegalArgumentException("Must specify a valid wake lock level.");
951         }
952         if (tag == null) {
953             throw new IllegalArgumentException("The tag must not be null.");
954         }
955     }
956 
957     /**
958      * Notifies the power manager that user activity happened.
959      * <p>
960      * Resets the auto-off timer and brightens the screen if the device
961      * is not asleep.  This is what happens normally when a key or the touch
962      * screen is pressed or when some other user activity occurs.
963      * This method does not wake up the device if it has been put to sleep.
964      * </p><p>
965      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
966      * </p>
967      *
968      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
969      * time base.  This timestamp is used to correctly order the user activity request with
970      * other power management functions.  It should be set
971      * to the timestamp of the input event that caused the user activity.
972      * @param noChangeLights If true, does not cause the keyboard backlight to turn on
973      * because of this event.  This is set when the power key is pressed.
974      * We want the device to stay on while the button is down, but we're about
975      * to turn off the screen so we don't want the keyboard backlight to turn on again.
976      * Otherwise the lights flash on and then off and it looks weird.
977      *
978      * @see #wakeUp
979      * @see #goToSleep
980      *
981      * @removed Requires signature or system permission.
982      * @deprecated Use {@link #userActivity(long, int, int)}.
983      */
984     @Deprecated
userActivity(long when, boolean noChangeLights)985     public void userActivity(long when, boolean noChangeLights) {
986         userActivity(when, USER_ACTIVITY_EVENT_OTHER,
987                 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
988     }
989 
990     /**
991      * Notifies the power manager that user activity happened.
992      * <p>
993      * Resets the auto-off timer and brightens the screen if the device
994      * is not asleep.  This is what happens normally when a key or the touch
995      * screen is pressed or when some other user activity occurs.
996      * This method does not wake up the device if it has been put to sleep.
997      * </p><p>
998      * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
999      * {@link android.Manifest.permission#USER_ACTIVITY} permission.
1000      * </p>
1001      *
1002      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
1003      * time base.  This timestamp is used to correctly order the user activity request with
1004      * other power management functions.  It should be set
1005      * to the timestamp of the input event that caused the user activity.
1006      * @param event The user activity event.
1007      * @param flags Optional user activity flags.
1008      *
1009      * @see #wakeUp
1010      * @see #goToSleep
1011      *
1012      * @hide Requires signature or system permission.
1013      */
1014     @SystemApi
1015     @RequiresPermission(anyOf = {
1016             android.Manifest.permission.DEVICE_POWER,
1017             android.Manifest.permission.USER_ACTIVITY
1018     })
userActivity(long when, int event, int flags)1019     public void userActivity(long when, int event, int flags) {
1020         try {
1021             mService.userActivity(when, event, flags);
1022         } catch (RemoteException e) {
1023             throw e.rethrowFromSystemServer();
1024         }
1025     }
1026 
1027    /**
1028      * Forces the device to go to sleep.
1029      * <p>
1030      * Overrides all the wake locks that are held.
1031      * This is what happens when the power key is pressed to turn off the screen.
1032      * </p><p>
1033      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1034      * </p>
1035      *
1036      * @param time The time when the request to go to sleep was issued, in the
1037      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1038      * order the go to sleep request with other power management functions.  It should be set
1039      * to the timestamp of the input event that caused the request to go to sleep.
1040      *
1041      * @see #userActivity
1042      * @see #wakeUp
1043      *
1044      * @removed Requires signature permission.
1045      */
goToSleep(long time)1046     public void goToSleep(long time) {
1047         goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
1048     }
1049 
1050     /**
1051      * Forces the device to go to sleep.
1052      * <p>
1053      * Overrides all the wake locks that are held.
1054      * This is what happens when the power key is pressed to turn off the screen.
1055      * </p><p>
1056      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1057      * </p>
1058      *
1059      * @param time The time when the request to go to sleep was issued, in the
1060      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1061      * order the go to sleep request with other power management functions.  It should be set
1062      * to the timestamp of the input event that caused the request to go to sleep.
1063      * @param reason The reason the device is going to sleep.
1064      * @param flags Optional flags to apply when going to sleep.
1065      *
1066      * @see #userActivity
1067      * @see #wakeUp
1068      *
1069      * @hide Requires signature permission.
1070      */
1071     @UnsupportedAppUsage
goToSleep(long time, int reason, int flags)1072     public void goToSleep(long time, int reason, int flags) {
1073         try {
1074             mService.goToSleep(time, reason, flags);
1075         } catch (RemoteException e) {
1076             throw e.rethrowFromSystemServer();
1077         }
1078     }
1079 
1080     /**
1081      * Forces the device to wake up from sleep.
1082      * <p>
1083      * If the device is currently asleep, wakes it up, otherwise does nothing.
1084      * This is what happens when the power key is pressed to turn on the screen.
1085      * </p><p>
1086      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1087      * </p>
1088      *
1089      * @param time The time when the request to wake up was issued, in the
1090      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1091      * order the wake up request with other power management functions.  It should be set
1092      * to the timestamp of the input event that caused the request to wake up.
1093      *
1094      * @see #userActivity
1095      * @see #goToSleep
1096      *
1097      * @deprecated Use {@link #wakeUp(long, int, String)} instead.
1098      * @removed Requires signature permission.
1099      */
1100     @Deprecated
wakeUp(long time)1101     public void wakeUp(long time) {
1102         wakeUp(time, WAKE_REASON_UNKNOWN, "wakeUp");
1103     }
1104 
1105     /**
1106      * Forces the device to wake up from sleep.
1107      * <p>
1108      * If the device is currently asleep, wakes it up, otherwise does nothing.
1109      * This is what happens when the power key is pressed to turn on the screen.
1110      * </p><p>
1111      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1112      * </p>
1113      *
1114      * @param time The time when the request to wake up was issued, in the
1115      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1116      * order the wake up request with other power management functions.  It should be set
1117      * to the timestamp of the input event that caused the request to wake up.
1118      *
1119      * @param details A free form string to explain the specific details behind the wake up for
1120      *                debugging purposes.
1121      *
1122      * @see #userActivity
1123      * @see #goToSleep
1124      *
1125      * @deprecated Use {@link #wakeUp(long, int, String)} instead.
1126      * @hide
1127      */
1128     @UnsupportedAppUsage
1129     @Deprecated
wakeUp(long time, String details)1130     public void wakeUp(long time, String details) {
1131         wakeUp(time, WAKE_REASON_UNKNOWN, details);
1132     }
1133 
1134     /**
1135      * Forces the device to wake up from sleep.
1136      * <p>
1137      * If the device is currently asleep, wakes it up, otherwise does nothing.
1138      * This is what happens when the power key is pressed to turn on the screen.
1139      * </p><p>
1140      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1141      * </p>
1142      *
1143      * @param time The time when the request to wake up was issued, in the
1144      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1145      * order the wake up request with other power management functions.  It should be set
1146      * to the timestamp of the input event that caused the request to wake up.
1147      *
1148      * @param reason The reason for the wake up.
1149      *
1150      * @param details A free form string to explain the specific details behind the wake up for
1151      *                debugging purposes.
1152      *
1153      * @see #userActivity
1154      * @see #goToSleep
1155      * @hide
1156      */
wakeUp(long time, @WakeReason int reason, String details)1157     public void wakeUp(long time, @WakeReason int reason, String details) {
1158         try {
1159             mService.wakeUp(time, reason, details, mContext.getOpPackageName());
1160         } catch (RemoteException e) {
1161             throw e.rethrowFromSystemServer();
1162         }
1163     }
1164 
1165     /**
1166      * Forces the device to start napping.
1167      * <p>
1168      * If the device is currently awake, starts dreaming, otherwise does nothing.
1169      * When the dream ends or if the dream cannot be started, the device will
1170      * either wake up or go to sleep depending on whether there has been recent
1171      * user activity.
1172      * </p><p>
1173      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1174      * </p>
1175      *
1176      * @param time The time when the request to nap was issued, in the
1177      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1178      * order the nap request with other power management functions.  It should be set
1179      * to the timestamp of the input event that caused the request to nap.
1180      *
1181      * @see #wakeUp
1182      * @see #goToSleep
1183      *
1184      * @hide Requires signature permission.
1185      */
nap(long time)1186     public void nap(long time) {
1187         try {
1188             mService.nap(time);
1189         } catch (RemoteException e) {
1190             throw e.rethrowFromSystemServer();
1191         }
1192     }
1193 
1194     /**
1195      * Requests the device to start dreaming.
1196      * <p>
1197      * If dream can not be started, for example if another {@link PowerManager} transition is in
1198      * progress, does nothing. Unlike {@link #nap(long)}, this does not put device to sleep when
1199      * dream ends.
1200      * </p><p>
1201      * Requires the {@link android.Manifest.permission#READ_DREAM_STATE} and
1202      * {@link android.Manifest.permission#WRITE_DREAM_STATE} permissions.
1203      * </p>
1204      *
1205      * @param time The time when the request to nap was issued, in the
1206      * {@link SystemClock#uptimeMillis()} time base.  This timestamp may be used to correctly
1207      * order the dream request with other power management functions.  It should be set
1208      * to the timestamp of the input event that caused the request to dream.
1209      *
1210      * @hide
1211      */
1212     @SystemApi
1213     @RequiresPermission(allOf = {
1214             android.Manifest.permission.READ_DREAM_STATE,
1215             android.Manifest.permission.WRITE_DREAM_STATE })
dream(long time)1216     public void dream(long time) {
1217         Sandman.startDreamByUserRequest(mContext);
1218     }
1219 
1220     /**
1221      * Boosts the brightness of the screen to maximum for a predetermined
1222      * period of time.  This is used to make the screen more readable in bright
1223      * daylight for a short duration.
1224      * <p>
1225      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1226      * </p>
1227      *
1228      * @param time The time when the request to boost was issued, in the
1229      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1230      * order the boost request with other power management functions.  It should be set
1231      * to the timestamp of the input event that caused the request to boost.
1232      *
1233      * @hide Requires signature permission.
1234      */
boostScreenBrightness(long time)1235     public void boostScreenBrightness(long time) {
1236         try {
1237             mService.boostScreenBrightness(time);
1238         } catch (RemoteException e) {
1239             throw e.rethrowFromSystemServer();
1240         }
1241     }
1242 
1243     /**
1244      * Returns whether the screen brightness is currently boosted to maximum, caused by a call
1245      * to {@link #boostScreenBrightness(long)}.
1246      * @return {@code True} if the screen brightness is currently boosted. {@code False} otherwise.
1247      *
1248      * @deprecated This call is rarely used and will be phased out soon.
1249      * @hide
1250      * @removed
1251      */
1252     @SystemApi @Deprecated
isScreenBrightnessBoosted()1253     public boolean isScreenBrightnessBoosted() {
1254         return false;
1255     }
1256 
1257    /**
1258      * Returns true if the specified wake lock level is supported.
1259      *
1260      * @param level The wake lock level to check.
1261      * @return True if the specified wake lock level is supported.
1262      */
isWakeLockLevelSupported(int level)1263     public boolean isWakeLockLevelSupported(int level) {
1264         try {
1265             return mService.isWakeLockLevelSupported(level);
1266         } catch (RemoteException e) {
1267             throw e.rethrowFromSystemServer();
1268         }
1269     }
1270 
1271     /**
1272       * Returns true if the device is in an interactive state.
1273       * <p>
1274       * For historical reasons, the name of this method refers to the power state of
1275       * the screen but it actually describes the overall interactive state of
1276       * the device.  This method has been replaced by {@link #isInteractive}.
1277       * </p><p>
1278       * The value returned by this method only indicates whether the device is
1279       * in an interactive state which may have nothing to do with the screen being
1280       * on or off.  To determine the actual state of the screen,
1281       * use {@link android.view.Display#getState}.
1282       * </p>
1283       *
1284       * @return True if the device is in an interactive state.
1285       *
1286       * @deprecated Use {@link #isInteractive} instead.
1287       */
1288     @Deprecated
isScreenOn()1289     public boolean isScreenOn() {
1290         return isInteractive();
1291     }
1292 
1293     /**
1294      * Returns true if the device is in an interactive state.
1295      * <p>
1296      * When this method returns true, the device is awake and ready to interact
1297      * with the user (although this is not a guarantee that the user is actively
1298      * interacting with the device just this moment).  The main screen is usually
1299      * turned on while in this state.  Certain features, such as the proximity
1300      * sensor, may temporarily turn off the screen while still leaving the device in an
1301      * interactive state.  Note in particular that the device is still considered
1302      * to be interactive while dreaming (since dreams can be interactive) but not
1303      * when it is dozing or asleep.
1304      * </p><p>
1305      * When this method returns false, the device is dozing or asleep and must
1306      * be awoken before it will become ready to interact with the user again.  The
1307      * main screen is usually turned off while in this state.  Certain features,
1308      * such as "ambient mode" may cause the main screen to remain on (albeit in a
1309      * low power state) to display system-provided content while the device dozes.
1310      * </p><p>
1311      * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
1312      * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
1313      * whenever the interactive state of the device changes.  For historical reasons,
1314      * the names of these broadcasts refer to the power state of the screen
1315      * but they are actually sent in response to changes in the overall interactive
1316      * state of the device, as described by this method.
1317      * </p><p>
1318      * Services may use the non-interactive state as a hint to conserve power
1319      * since the user is not present.
1320      * </p>
1321      *
1322      * @return True if the device is in an interactive state.
1323      *
1324      * @see android.content.Intent#ACTION_SCREEN_ON
1325      * @see android.content.Intent#ACTION_SCREEN_OFF
1326      */
isInteractive()1327     public boolean isInteractive() {
1328         try {
1329             return mService.isInteractive();
1330         } catch (RemoteException e) {
1331             throw e.rethrowFromSystemServer();
1332         }
1333     }
1334 
1335 
1336     /**
1337      * Returns {@code true} if this device supports rebooting userspace.
1338      *
1339      * <p>This method exists solely for the sake of re-using same logic between {@code PowerManager}
1340      * and {@code PowerManagerService}.
1341      *
1342      * @hide
1343      */
isRebootingUserspaceSupportedImpl()1344     public static boolean isRebootingUserspaceSupportedImpl() {
1345         return InitProperties.is_userspace_reboot_supported().orElse(false);
1346     }
1347 
1348     /**
1349      * Returns {@code true} if this device supports rebooting userspace.
1350      */
1351     // TODO(b/138605180): add link to documentation once it's ready.
isRebootingUserspaceSupported()1352     public boolean isRebootingUserspaceSupported() {
1353         return isRebootingUserspaceSupportedImpl();
1354     }
1355 
1356     /**
1357      * Reboot the device.  Will not return if the reboot is successful.
1358      * <p>
1359      * Requires the {@link android.Manifest.permission#REBOOT} permission.
1360      * </p>
1361      *
1362      * @param reason code to pass to the kernel (e.g., "recovery") to
1363      *               request special boot modes, or null.
1364      * @throws UnsupportedOperationException if userspace reboot was requested on a device that
1365      *                                       doesn't support it.
1366      */
1367     @RequiresPermission(permission.REBOOT)
reboot(@ullable String reason)1368     public void reboot(@Nullable String reason) {
1369         if (REBOOT_USERSPACE.equals(reason) && !isRebootingUserspaceSupported()) {
1370             throw new UnsupportedOperationException(
1371                     "Attempted userspace reboot on a device that doesn't support it");
1372         }
1373         try {
1374             mService.reboot(false, reason, true);
1375         } catch (RemoteException e) {
1376             throw e.rethrowFromSystemServer();
1377         }
1378     }
1379 
1380     /**
1381      * Reboot the device. Will not return if the reboot is successful.
1382      * <p>
1383      * Requires the {@link android.Manifest.permission#REBOOT} permission.
1384      * </p>
1385      * @hide
1386      */
1387     @RequiresPermission(permission.REBOOT)
rebootSafeMode()1388     public void rebootSafeMode() {
1389         try {
1390             mService.rebootSafeMode(false, true);
1391         } catch (RemoteException e) {
1392             throw e.rethrowFromSystemServer();
1393         }
1394     }
1395 
1396     /**
1397      * Returns true if the device is currently in power save mode.  When in this mode,
1398      * applications should reduce their functionality in order to conserve battery as
1399      * much as possible.  You can monitor for changes to this state with
1400      * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
1401      *
1402      * @return Returns true if currently in low power mode, else false.
1403      */
isPowerSaveMode()1404     public boolean isPowerSaveMode() {
1405         try {
1406             return mService.isPowerSaveMode();
1407         } catch (RemoteException e) {
1408             throw e.rethrowFromSystemServer();
1409         }
1410     }
1411 
1412     /**
1413      * Set the current power save mode.
1414      *
1415      * @return True if the set was allowed.
1416      *
1417      * @hide
1418      * @see #isPowerSaveMode()
1419      */
1420     @SystemApi
1421     @TestApi
1422     @RequiresPermission(anyOf = {
1423             android.Manifest.permission.DEVICE_POWER,
1424             android.Manifest.permission.POWER_SAVER
1425     })
setPowerSaveModeEnabled(boolean mode)1426     public boolean setPowerSaveModeEnabled(boolean mode) {
1427         try {
1428             return mService.setPowerSaveModeEnabled(mode);
1429         } catch (RemoteException e) {
1430             throw e.rethrowFromSystemServer();
1431         }
1432     }
1433 
1434     /**
1435      * Updates the current state of dynamic power savings and disable threshold. This is
1436      * a signal to the system which an app can update to serve as an indicator that
1437      * the user will be in a battery critical situation before being able to plug in.
1438      * Only apps with the {@link android.Manifest.permission#POWER_SAVER} permission may do this.
1439      * This is a device global state, not a per user setting.
1440      *
1441      * <p>When enabled, the system may enact various measures for reducing power consumption in
1442      * order to help ensure that the user will make it to their next charging point. The most
1443      * visible of these will be the automatic enabling of battery saver if the user has set
1444      * their battery saver mode to "automatic". Note
1445      * that this is NOT simply an on/off switch for features, but rather a hint for the
1446      * system to consider enacting these power saving features, some of which have additional
1447      * logic around when to activate based on this signal.
1448      *
1449      * <p>The provided threshold is the percentage the system should consider itself safe at given
1450      * the current state of the device. The value is an integer representing a battery level.
1451      *
1452      * <p>The threshold is meant to set an explicit stopping point for dynamic power savings
1453      * functionality so that the dynamic power savings itself remains a signal rather than becoming
1454      * an on/off switch for a subset of features.
1455      * @hide
1456      *
1457      * @param powerSaveHint A signal indicating to the system if it believes the
1458      * dynamic power savings behaviors should be activated.
1459      * @param disableThreshold When the suggesting app believes it would be safe to disable dynamic
1460      * power savings behaviors.
1461      * @return True if the update was allowed and succeeded.
1462      *
1463      * @hide
1464      */
1465     @SystemApi
1466     @TestApi
1467     @RequiresPermission(permission.POWER_SAVER)
setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold)1468     public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
1469         try {
1470             return mService.setDynamicPowerSaveHint(powerSaveHint, disableThreshold);
1471         } catch (RemoteException e) {
1472             throw e.rethrowFromSystemServer();
1473         }
1474     }
1475 
1476     /**
1477      * Sets the policy for adaptive power save.
1478      *
1479      * @return true if there was an effectual change. If full battery saver is enabled or the
1480      * adaptive policy is not enabled, then this will return false.
1481      *
1482      * @hide
1483      */
1484     @SystemApi
1485     @RequiresPermission(anyOf = {
1486             android.Manifest.permission.DEVICE_POWER,
1487             android.Manifest.permission.POWER_SAVER
1488     })
setAdaptivePowerSavePolicy(@onNull BatterySaverPolicyConfig config)1489     public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
1490         try {
1491             return mService.setAdaptivePowerSavePolicy(config);
1492         } catch (RemoteException e) {
1493             throw e.rethrowFromSystemServer();
1494         }
1495     }
1496 
1497     /**
1498      * Enables or disables adaptive power save.
1499      *
1500      * @return true if there was an effectual change. If full battery saver is enabled, then this
1501      * will return false.
1502      *
1503      * @hide
1504      */
1505     @SystemApi
1506     @RequiresPermission(anyOf = {
1507             android.Manifest.permission.DEVICE_POWER,
1508             android.Manifest.permission.POWER_SAVER
1509     })
setAdaptivePowerSaveEnabled(boolean enabled)1510     public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
1511         try {
1512             return mService.setAdaptivePowerSaveEnabled(enabled);
1513         } catch (RemoteException e) {
1514             throw e.rethrowFromSystemServer();
1515         }
1516     }
1517 
1518     /**
1519      * Indicates automatic battery saver toggling by the system will be based on percentage.
1520      *
1521      * @see PowerManager#getPowerSaveModeTrigger()
1522      *
1523      *  @hide
1524      */
1525     @SystemApi
1526     @TestApi
1527     public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0;
1528 
1529     /**
1530      * Indicates automatic battery saver toggling by the system will be based on the state
1531      * of the dynamic power savings signal.
1532      *
1533      * @see PowerManager#setDynamicPowerSaveHint(boolean, int)
1534      * @see PowerManager#getPowerSaveModeTrigger()
1535      *
1536      *  @hide
1537      */
1538     @SystemApi
1539     @TestApi
1540     public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1;
1541 
1542     /** @hide */
1543     @Retention(RetentionPolicy.SOURCE)
1544     @IntDef(value = {
1545         POWER_SAVE_MODE_TRIGGER_PERCENTAGE,
1546         POWER_SAVE_MODE_TRIGGER_DYNAMIC
1547 
1548     })
1549     public @interface AutoPowerSaveModeTriggers {}
1550 
1551 
1552     /**
1553      * Returns the current battery saver control mode. Values it may return are defined in
1554      * AutoPowerSaveModeTriggers. Note that this is a global device state, not a per user setting.
1555      *
1556      * @return The current value power saver mode for the system.
1557      *
1558      * @see AutoPowerSaveModeTriggers
1559      * @see PowerManager#getPowerSaveModeTrigger()
1560      * @hide
1561      */
1562     @AutoPowerSaveModeTriggers
1563     @SystemApi
1564     @TestApi
1565     @RequiresPermission(android.Manifest.permission.POWER_SAVER)
getPowerSaveModeTrigger()1566     public int getPowerSaveModeTrigger() {
1567         try {
1568             return mService.getPowerSaveModeTrigger();
1569         } catch (RemoteException e) {
1570             throw e.rethrowFromSystemServer();
1571         }
1572     }
1573 
1574     /**
1575      * Get data about the battery saver mode for a specific service
1576      * @param serviceType unique key for the service, one of {@link ServiceType}
1577      * @return Battery saver state data.
1578      *
1579      * @hide
1580      * @see com.android.server.power.batterysaver.BatterySaverPolicy
1581      * @see PowerSaveState
1582      */
getPowerSaveState(@erviceType int serviceType)1583     public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
1584         try {
1585             return mService.getPowerSaveState(serviceType);
1586         } catch (RemoteException e) {
1587             throw e.rethrowFromSystemServer();
1588         }
1589     }
1590 
1591     /**
1592      * Returns how location features should behave when battery saver is on. When battery saver
1593      * is off, this will always return {@link #LOCATION_MODE_NO_CHANGE}.
1594      *
1595      * <p>This API is normally only useful for components that provide location features.
1596      *
1597      * @see #isPowerSaveMode()
1598      * @see #ACTION_POWER_SAVE_MODE_CHANGED
1599      */
1600     @LocationPowerSaveMode
getLocationPowerSaveMode()1601     public int getLocationPowerSaveMode() {
1602         final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.LOCATION);
1603         if (!powerSaveState.batterySaverEnabled) {
1604             return LOCATION_MODE_NO_CHANGE;
1605         }
1606         return powerSaveState.locationMode;
1607     }
1608 
1609     /**
1610      * Returns true if the device is currently in idle mode.  This happens when a device
1611      * has been sitting unused and unmoving for a sufficiently long period of time, so that
1612      * it decides to go into a lower power-use state.  This may involve things like turning
1613      * off network access to apps.  You can monitor for changes to this state with
1614      * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
1615      *
1616      * @return Returns true if currently in active device idle mode, else false.  This is
1617      * when idle mode restrictions are being actively applied; it will return false if the
1618      * device is in a long-term idle mode but currently running a maintenance window where
1619      * restrictions have been lifted.
1620      */
isDeviceIdleMode()1621     public boolean isDeviceIdleMode() {
1622         try {
1623             return mService.isDeviceIdleMode();
1624         } catch (RemoteException e) {
1625             throw e.rethrowFromSystemServer();
1626         }
1627     }
1628 
1629     /**
1630      * Returns true if the device is currently in light idle mode.  This happens when a device
1631      * has had its screen off for a short time, switching it into a batching mode where we
1632      * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
1633      * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
1634      *
1635      * @return Returns true if currently in active light device idle mode, else false.  This is
1636      * when light idle mode restrictions are being actively applied; it will return false if the
1637      * device is in a long-term idle mode but currently running a maintenance window where
1638      * restrictions have been lifted.
1639      * @hide
1640      */
1641     @UnsupportedAppUsage
isLightDeviceIdleMode()1642     public boolean isLightDeviceIdleMode() {
1643         try {
1644             return mService.isLightDeviceIdleMode();
1645         } catch (RemoteException e) {
1646             throw e.rethrowFromSystemServer();
1647         }
1648     }
1649 
1650     /**
1651      * Return whether the given application package name is on the device's power whitelist.
1652      * Apps can be placed on the whitelist through the settings UI invoked by
1653      * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
1654      */
isIgnoringBatteryOptimizations(String packageName)1655     public boolean isIgnoringBatteryOptimizations(String packageName) {
1656         synchronized (this) {
1657             if (mIDeviceIdleController == null) {
1658                 mIDeviceIdleController = IDeviceIdleController.Stub.asInterface(
1659                         ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
1660             }
1661         }
1662         try {
1663             return mIDeviceIdleController.isPowerSaveWhitelistApp(packageName);
1664         } catch (RemoteException e) {
1665             throw e.rethrowFromSystemServer();
1666         }
1667     }
1668 
1669     /**
1670      * Turn off the device.
1671      *
1672      * @param confirm If true, shows a shutdown confirmation dialog.
1673      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
1674      * @param wait If true, this call waits for the shutdown to complete and does not return.
1675      *
1676      * @hide
1677      */
shutdown(boolean confirm, String reason, boolean wait)1678     public void shutdown(boolean confirm, String reason, boolean wait) {
1679         try {
1680             mService.shutdown(confirm, reason, wait);
1681         } catch (RemoteException e) {
1682             throw e.rethrowFromSystemServer();
1683         }
1684     }
1685 
1686     /**
1687      * This function checks if the device has implemented Sustained Performance
1688      * Mode. This needs to be checked only once and is constant for a particular
1689      * device/release.
1690      *
1691      * Sustained Performance Mode is intended to provide a consistent level of
1692      * performance for prolonged amount of time.
1693      *
1694      * Applications should check if the device supports this mode, before using
1695      * {@link android.view.Window#setSustainedPerformanceMode}.
1696      *
1697      * @return Returns True if the device supports it, false otherwise.
1698      *
1699      * @see android.view.Window#setSustainedPerformanceMode
1700      */
isSustainedPerformanceModeSupported()1701     public boolean isSustainedPerformanceModeSupported() {
1702         return mContext.getResources().getBoolean(
1703                 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
1704     }
1705 
1706     /**
1707      * Thermal status code: Not under throttling.
1708      */
1709     public static final int THERMAL_STATUS_NONE = Temperature.THROTTLING_NONE;
1710 
1711     /**
1712      * Thermal status code: Light throttling where UX is not impacted.
1713      */
1714     public static final int THERMAL_STATUS_LIGHT = Temperature.THROTTLING_LIGHT;
1715 
1716     /**
1717      * Thermal status code: Moderate throttling where UX is not largely impacted.
1718      */
1719     public static final int THERMAL_STATUS_MODERATE = Temperature.THROTTLING_MODERATE;
1720 
1721     /**
1722      * Thermal status code: Severe throttling where UX is largely impacted.
1723      */
1724     public static final int THERMAL_STATUS_SEVERE = Temperature.THROTTLING_SEVERE;
1725 
1726     /**
1727      * Thermal status code: Platform has done everything to reduce power.
1728      */
1729     public static final int THERMAL_STATUS_CRITICAL = Temperature.THROTTLING_CRITICAL;
1730 
1731     /**
1732      * Thermal status code: Key components in platform are shutting down due to thermal condition.
1733      * Device functionalities will be limited.
1734      */
1735     public static final int THERMAL_STATUS_EMERGENCY = Temperature.THROTTLING_EMERGENCY;
1736 
1737     /**
1738      * Thermal status code: Need shutdown immediately.
1739      */
1740     public static final int THERMAL_STATUS_SHUTDOWN = Temperature.THROTTLING_SHUTDOWN;
1741 
1742     /** @hide */
1743     @IntDef(prefix = { "THERMAL_STATUS_" }, value = {
1744             THERMAL_STATUS_NONE,
1745             THERMAL_STATUS_LIGHT,
1746             THERMAL_STATUS_MODERATE,
1747             THERMAL_STATUS_SEVERE,
1748             THERMAL_STATUS_CRITICAL,
1749             THERMAL_STATUS_EMERGENCY,
1750             THERMAL_STATUS_SHUTDOWN,
1751     })
1752     @Retention(RetentionPolicy.SOURCE)
1753     public @interface ThermalStatus {}
1754 
1755     /**
1756      * This function returns the current thermal status of the device.
1757      *
1758      * @return thermal status as int, {@link #THERMAL_STATUS_NONE} if device in not under
1759      * thermal throttling.
1760      */
getCurrentThermalStatus()1761     public @ThermalStatus int getCurrentThermalStatus() {
1762         synchronized (this) {
1763             if (mThermalService == null) {
1764                 mThermalService = IThermalService.Stub.asInterface(
1765                         ServiceManager.getService(Context.THERMAL_SERVICE));
1766             }
1767             try {
1768                 return mThermalService.getCurrentThermalStatus();
1769             } catch (RemoteException e) {
1770                 throw e.rethrowFromSystemServer();
1771             }
1772         }
1773 
1774     }
1775 
1776     /**
1777      * Listener passed to
1778      * {@link PowerManager#addThermalStatusListener} and
1779      * {@link PowerManager#removeThermalStatusListener}
1780      * to notify caller of thermal status has changed.
1781      */
1782     public interface OnThermalStatusChangedListener {
1783 
1784         /**
1785          * Called when overall thermal throttling status changed.
1786          * @param status defined in {@link android.os.Temperature}.
1787          */
onThermalStatusChanged(@hermalStatus int status)1788         void onThermalStatusChanged(@ThermalStatus int status);
1789     }
1790 
1791 
1792     /**
1793      * This function adds a listener for thermal status change, listen call back will be
1794      * enqueued tasks on the main thread
1795      *
1796      * @param listener listener to be added,
1797      */
addThermalStatusListener(@onNull OnThermalStatusChangedListener listener)1798     public void addThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
1799         Preconditions.checkNotNull(listener, "listener cannot be null");
1800         synchronized (this) {
1801             if (mThermalService == null) {
1802                 mThermalService = IThermalService.Stub.asInterface(
1803                         ServiceManager.getService(Context.THERMAL_SERVICE));
1804             }
1805             this.addThermalStatusListener(mContext.getMainExecutor(), listener);
1806         }
1807     }
1808 
1809     /**
1810      * This function adds a listener for thermal status change.
1811      *
1812      * @param executor {@link Executor} to handle listener callback.
1813      * @param listener listener to be added.
1814      */
addThermalStatusListener(@onNull @allbackExecutor Executor executor, @NonNull OnThermalStatusChangedListener listener)1815     public void addThermalStatusListener(@NonNull @CallbackExecutor Executor executor,
1816             @NonNull OnThermalStatusChangedListener listener) {
1817         Preconditions.checkNotNull(listener, "listener cannot be null");
1818         Preconditions.checkNotNull(executor, "executor cannot be null");
1819         synchronized (this) {
1820             if (mThermalService == null) {
1821                 mThermalService = IThermalService.Stub.asInterface(
1822                         ServiceManager.getService(Context.THERMAL_SERVICE));
1823             }
1824             Preconditions.checkArgument(!mListenerMap.containsKey(listener),
1825                     "Listener already registered: " + listener);
1826             IThermalStatusListener internalListener = new IThermalStatusListener.Stub() {
1827                 @Override
1828                 public void onStatusChange(int status) {
1829                     final long token = Binder.clearCallingIdentity();
1830                     try {
1831                         executor.execute(() -> {
1832                             listener.onThermalStatusChanged(status);
1833                         });
1834                     } finally {
1835                         Binder.restoreCallingIdentity(token);
1836                     }
1837                 }
1838             };
1839             try {
1840                 if (mThermalService.registerThermalStatusListener(internalListener)) {
1841                     mListenerMap.put(listener, internalListener);
1842                 } else {
1843                     throw new RuntimeException("Listener failed to set");
1844                 }
1845             } catch (RemoteException e) {
1846                 throw e.rethrowFromSystemServer();
1847             }
1848         }
1849     }
1850 
1851     /**
1852      * This function removes a listener for thermal status change
1853      *
1854      * @param listener listener to be removed
1855      */
removeThermalStatusListener(@onNull OnThermalStatusChangedListener listener)1856     public void removeThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
1857         Preconditions.checkNotNull(listener, "listener cannot be null");
1858         synchronized (this) {
1859             if (mThermalService == null) {
1860                 mThermalService = IThermalService.Stub.asInterface(
1861                         ServiceManager.getService(Context.THERMAL_SERVICE));
1862             }
1863             IThermalStatusListener internalListener = mListenerMap.get(listener);
1864             Preconditions.checkArgument(internalListener != null, "Listener was not added");
1865             try {
1866                 if (mThermalService.unregisterThermalStatusListener(internalListener)) {
1867                     mListenerMap.remove(listener);
1868                 } else {
1869                     throw new RuntimeException("Listener failed to remove");
1870                 }
1871             } catch (RemoteException e) {
1872                 throw e.rethrowFromSystemServer();
1873             }
1874         }
1875     }
1876 
1877     /**
1878      * If true, the doze component is not started until after the screen has been
1879      * turned off and the screen off animation has been performed.
1880      * @hide
1881      */
setDozeAfterScreenOff(boolean dozeAfterScreenOf)1882     public void setDozeAfterScreenOff(boolean dozeAfterScreenOf) {
1883         try {
1884             mService.setDozeAfterScreenOff(dozeAfterScreenOf);
1885         } catch (RemoteException e) {
1886             throw e.rethrowFromSystemServer();
1887         }
1888     }
1889 
1890     /**
1891      * Returns the reason the phone was last shutdown. Calling app must have the
1892      * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information.
1893      * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could
1894      * not be accessed.
1895      * @hide
1896      */
1897     @ShutdownReason
getLastShutdownReason()1898     public int getLastShutdownReason() {
1899         try {
1900             return mService.getLastShutdownReason();
1901         } catch (RemoteException e) {
1902             throw e.rethrowFromSystemServer();
1903         }
1904     }
1905 
1906     /**
1907      * Returns the reason the device last went to sleep (i.e. the last value of
1908      * the second argument of {@link #goToSleep(long, int, int) goToSleep}).
1909      *
1910      * @return One of the {@code GO_TO_SLEEP_REASON_*} constants.
1911      *
1912      * @hide
1913      */
getLastSleepReason()1914     public int getLastSleepReason() {
1915         try {
1916             return mService.getLastSleepReason();
1917         } catch (RemoteException e) {
1918             throw e.rethrowFromSystemServer();
1919         }
1920     }
1921 
1922     /**
1923      * Forces the device to go to suspend, even if there are currently wakelocks being held.
1924      * <b>Caution</b>
1925      * This is a very dangerous command as it puts the device to sleep immediately. Apps and parts
1926      * of the system will not be notified and will not have an opportunity to save state prior to
1927      * the device going to suspend.
1928      * This method should only be used in very rare circumstances where the device is intended
1929      * to appear as completely off to the user and they have a well understood, reliable way of
1930      * re-enabling it.
1931      * </p><p>
1932      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1933      * </p>
1934      *
1935      * @return true on success, false otherwise.
1936      * @hide
1937      */
1938     @SystemApi
1939     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
forceSuspend()1940     public boolean forceSuspend() {
1941         try {
1942             return mService.forceSuspend();
1943         } catch (RemoteException e) {
1944             throw e.rethrowFromSystemServer();
1945         }
1946     }
1947 
1948     /**
1949      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1950      * This broadcast is only sent to registered receivers.
1951      */
1952     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1953     public static final String ACTION_POWER_SAVE_MODE_CHANGED
1954             = "android.os.action.POWER_SAVE_MODE_CHANGED";
1955 
1956     /**
1957      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1958      * @hide
1959      */
1960     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1961     public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
1962             = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
1963 
1964     /**
1965      * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1966      * This broadcast is only sent to registered receivers.
1967      */
1968     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1969     public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
1970             = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
1971 
1972     /**
1973      * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1974      * This broadcast is only sent to registered receivers.
1975      * @hide
1976      */
1977     @UnsupportedAppUsage
1978     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1979     public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
1980             = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
1981 
1982     /**
1983      * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
1984      * This broadcast is only sent to registered receivers.
1985      */
1986     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1987     public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
1988             = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
1989 
1990     /**
1991      * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
1992      * This broadcast is only sent to registered receivers.
1993      */
1994     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1995     public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
1996             = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
1997 
1998     /**
1999      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
2000      * This broadcast is only sent to registered receivers.
2001      *
2002      * @hide
2003      */
2004     @UnsupportedAppUsage
2005     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
2006     public static final String ACTION_POWER_SAVE_MODE_CHANGING
2007             = "android.os.action.POWER_SAVE_MODE_CHANGING";
2008 
2009     /** @hide */
2010     @UnsupportedAppUsage
2011     public static final String EXTRA_POWER_SAVE_MODE = "mode";
2012 
2013     /**
2014      * Intent that is broadcast when the state of {@link #isScreenBrightnessBoosted()} has changed.
2015      * This broadcast is only sent to registered receivers.
2016      *
2017      * @deprecated This intent is rarely used and will be phased out soon.
2018      * @hide
2019      * @removed
2020      **/
2021     @SystemApi @Deprecated
2022     public static final String ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED
2023             = "android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED";
2024 
2025     /**
2026      * Constant for PreIdleTimeout normal mode (default mode, not short nor extend timeout) .
2027      * @hide
2028      */
2029     public static final int PRE_IDLE_TIMEOUT_MODE_NORMAL = 0;
2030 
2031     /**
2032      * Constant for PreIdleTimeout long mode (extend timeout to keep in inactive mode
2033      * longer).
2034      * @hide
2035      */
2036     public static final int PRE_IDLE_TIMEOUT_MODE_LONG = 1;
2037 
2038     /**
2039      * Constant for PreIdleTimeout short mode (short timeout to go to doze mode quickly)
2040      * @hide
2041      */
2042     public static final int PRE_IDLE_TIMEOUT_MODE_SHORT = 2;
2043 
2044     /**
2045      * A wake lock is a mechanism to indicate that your application needs
2046      * to have the device stay on.
2047      * <p>
2048      * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
2049      * permission in an {@code <uses-permission>} element of the application's manifest.
2050      * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
2051      * </p><p>
2052      * Call {@link #acquire()} to acquire the wake lock and force the device to stay
2053      * on at the level that was requested when the wake lock was created.
2054      * </p><p>
2055      * Call {@link #release()} when you are done and don't need the lock anymore.
2056      * It is very important to do this as soon as possible to avoid running down the
2057      * device's battery excessively.
2058      * </p>
2059      */
2060     public final class WakeLock {
2061         @UnsupportedAppUsage
2062         private int mFlags;
2063         @UnsupportedAppUsage
2064         private String mTag;
2065         private final String mPackageName;
2066         private final IBinder mToken;
2067         private int mInternalCount;
2068         private int mExternalCount;
2069         private boolean mRefCounted = true;
2070         private boolean mHeld;
2071         private WorkSource mWorkSource;
2072         private String mHistoryTag;
2073         private final String mTraceName;
2074 
2075         private final Runnable mReleaser = new Runnable() {
2076             public void run() {
2077                 release(RELEASE_FLAG_TIMEOUT);
2078             }
2079         };
2080 
WakeLock(int flags, String tag, String packageName)2081         WakeLock(int flags, String tag, String packageName) {
2082             mFlags = flags;
2083             mTag = tag;
2084             mPackageName = packageName;
2085             mToken = new Binder();
2086             mTraceName = "WakeLock (" + mTag + ")";
2087         }
2088 
2089         @Override
finalize()2090         protected void finalize() throws Throwable {
2091             synchronized (mToken) {
2092                 if (mHeld) {
2093                     Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
2094                     Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
2095                     try {
2096                         mService.releaseWakeLock(mToken, 0);
2097                     } catch (RemoteException e) {
2098                         throw e.rethrowFromSystemServer();
2099                     }
2100                 }
2101             }
2102         }
2103 
2104         /**
2105          * Sets whether this WakeLock is reference counted.
2106          * <p>
2107          * Wake locks are reference counted by default.  If a wake lock is
2108          * reference counted, then each call to {@link #acquire()} must be
2109          * balanced by an equal number of calls to {@link #release()}.  If a wake
2110          * lock is not reference counted, then one call to {@link #release()} is
2111          * sufficient to undo the effect of all previous calls to {@link #acquire()}.
2112          * </p>
2113          *
2114          * @param value True to make the wake lock reference counted, false to
2115          * make the wake lock non-reference counted.
2116          */
setReferenceCounted(boolean value)2117         public void setReferenceCounted(boolean value) {
2118             synchronized (mToken) {
2119                 mRefCounted = value;
2120             }
2121         }
2122 
2123         /**
2124          * Acquires the wake lock.
2125          * <p>
2126          * Ensures that the device is on at the level requested when
2127          * the wake lock was created.
2128          * </p>
2129          */
acquire()2130         public void acquire() {
2131             synchronized (mToken) {
2132                 acquireLocked();
2133             }
2134         }
2135 
2136         /**
2137          * Acquires the wake lock with a timeout.
2138          * <p>
2139          * Ensures that the device is on at the level requested when
2140          * the wake lock was created.  The lock will be released after the given timeout
2141          * expires.
2142          * </p>
2143          *
2144          * @param timeout The timeout after which to release the wake lock, in milliseconds.
2145          */
acquire(long timeout)2146         public void acquire(long timeout) {
2147             synchronized (mToken) {
2148                 acquireLocked();
2149                 mHandler.postDelayed(mReleaser, timeout);
2150             }
2151         }
2152 
acquireLocked()2153         private void acquireLocked() {
2154             mInternalCount++;
2155             mExternalCount++;
2156             if (!mRefCounted || mInternalCount == 1) {
2157                 // Do this even if the wake lock is already thought to be held (mHeld == true)
2158                 // because non-reference counted wake locks are not always properly released.
2159                 // For example, the keyguard's wake lock might be forcibly released by the
2160                 // power manager without the keyguard knowing.  A subsequent call to acquire
2161                 // should immediately acquire the wake lock once again despite never having
2162                 // been explicitly released by the keyguard.
2163                 mHandler.removeCallbacks(mReleaser);
2164                 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
2165                 try {
2166                     mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
2167                             mHistoryTag);
2168                 } catch (RemoteException e) {
2169                     throw e.rethrowFromSystemServer();
2170                 }
2171                 mHeld = true;
2172             }
2173         }
2174 
2175         /**
2176          * Releases the wake lock.
2177          * <p>
2178          * This method releases your claim to the CPU or screen being on.
2179          * The screen may turn off shortly after you release the wake lock, or it may
2180          * not if there are other wake locks still held.
2181          * </p>
2182          */
release()2183         public void release() {
2184             release(0);
2185         }
2186 
2187         /**
2188          * Releases the wake lock with flags to modify the release behavior.
2189          * <p>
2190          * This method releases your claim to the CPU or screen being on.
2191          * The screen may turn off shortly after you release the wake lock, or it may
2192          * not if there are other wake locks still held.
2193          * </p>
2194          *
2195          * @param flags Combination of flag values to modify the release behavior.
2196          * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
2197          * Passing 0 is equivalent to calling {@link #release()}.
2198          */
release(int flags)2199         public void release(int flags) {
2200             synchronized (mToken) {
2201                 if (mInternalCount > 0) {
2202                     // internal count must only be decreased if it is > 0 or state of
2203                     // the WakeLock object is broken.
2204                     mInternalCount--;
2205                 }
2206                 if ((flags & RELEASE_FLAG_TIMEOUT) == 0) {
2207                     mExternalCount--;
2208                 }
2209                 if (!mRefCounted || mInternalCount == 0) {
2210                     mHandler.removeCallbacks(mReleaser);
2211                     if (mHeld) {
2212                         Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
2213                         try {
2214                             mService.releaseWakeLock(mToken, flags);
2215                         } catch (RemoteException e) {
2216                             throw e.rethrowFromSystemServer();
2217                         }
2218                         mHeld = false;
2219                     }
2220                 }
2221                 if (mRefCounted && mExternalCount < 0) {
2222                     throw new RuntimeException("WakeLock under-locked " + mTag);
2223                 }
2224             }
2225         }
2226 
2227         /**
2228          * Returns true if the wake lock has been acquired but not yet released.
2229          *
2230          * @return True if the wake lock is held.
2231          */
isHeld()2232         public boolean isHeld() {
2233             synchronized (mToken) {
2234                 return mHeld;
2235             }
2236         }
2237 
2238         /**
2239          * Sets the work source associated with the wake lock.
2240          * <p>
2241          * The work source is used to determine on behalf of which application
2242          * the wake lock is being held.  This is useful in the case where a
2243          * service is performing work on behalf of an application so that the
2244          * cost of that work can be accounted to the application.
2245          * </p>
2246          *
2247          * <p>
2248          * Make sure to follow the tag naming convention when using WorkSource
2249          * to make it easier for app developers to understand wake locks
2250          * attributed to them. See {@link PowerManager#newWakeLock(int, String)}
2251          * documentation.
2252          * </p>
2253          *
2254          * @param ws The work source, or null if none.
2255          */
setWorkSource(WorkSource ws)2256         public void setWorkSource(WorkSource ws) {
2257             synchronized (mToken) {
2258                 if (ws != null && ws.isEmpty()) {
2259                     ws = null;
2260                 }
2261 
2262                 final boolean changed;
2263                 if (ws == null) {
2264                     changed = mWorkSource != null;
2265                     mWorkSource = null;
2266                 } else if (mWorkSource == null) {
2267                     changed = true;
2268                     mWorkSource = new WorkSource(ws);
2269                 } else {
2270                     changed = !mWorkSource.equals(ws);
2271                     if (changed) {
2272                         mWorkSource.set(ws);
2273                     }
2274                 }
2275 
2276                 if (changed && mHeld) {
2277                     try {
2278                         mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
2279                     } catch (RemoteException e) {
2280                         throw e.rethrowFromSystemServer();
2281                     }
2282                 }
2283             }
2284         }
2285 
2286         /** @hide */
setTag(String tag)2287         public void setTag(String tag) {
2288             mTag = tag;
2289         }
2290 
2291         /** @hide */
getTag()2292         public String getTag() {
2293             return mTag;
2294         }
2295 
2296         /** @hide */
setHistoryTag(String tag)2297         public void setHistoryTag(String tag) {
2298             mHistoryTag = tag;
2299         }
2300 
2301         /** @hide */
setUnimportantForLogging(boolean state)2302         public void setUnimportantForLogging(boolean state) {
2303             if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
2304             else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
2305         }
2306 
2307         @Override
toString()2308         public String toString() {
2309             synchronized (mToken) {
2310                 return "WakeLock{"
2311                     + Integer.toHexString(System.identityHashCode(this))
2312                     + " held=" + mHeld + ", refCount=" + mInternalCount + "}";
2313             }
2314         }
2315 
2316         /** @hide */
writeToProto(ProtoOutputStream proto, long fieldId)2317         public void writeToProto(ProtoOutputStream proto, long fieldId) {
2318             synchronized (mToken) {
2319                 final long token = proto.start(fieldId);
2320                 proto.write(PowerManagerProto.WakeLock.TAG, mTag);
2321                 proto.write(PowerManagerProto.WakeLock.PACKAGE_NAME, mPackageName);
2322                 proto.write(PowerManagerProto.WakeLock.HELD, mHeld);
2323                 proto.write(PowerManagerProto.WakeLock.INTERNAL_COUNT, mInternalCount);
2324                 if (mWorkSource != null) {
2325                     mWorkSource.writeToProto(proto, PowerManagerProto.WakeLock.WORK_SOURCE);
2326                 }
2327                 proto.end(token);
2328             }
2329         }
2330 
2331         /**
2332          * Wraps a Runnable such that this method immediately acquires the wake lock and then
2333          * once the Runnable is done the wake lock is released.
2334          *
2335          * <p>Example:
2336          *
2337          * <pre>
2338          * mHandler.post(mWakeLock.wrap(() -> {
2339          *     // do things on handler, lock is held while we're waiting for this
2340          *     // to get scheduled and until the runnable is done executing.
2341          * });
2342          * </pre>
2343          *
2344          * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
2345          *    leak the wakelock!
2346          *
2347          * @hide
2348          */
wrap(Runnable r)2349         public Runnable wrap(Runnable r) {
2350             acquire();
2351             return () -> {
2352                 try {
2353                     r.run();
2354                 } finally {
2355                     release();
2356                 }
2357             };
2358         }
2359     }
2360 }
2361