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