• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static android.app.PropertyInvalidatedCache.MODULE_SYSTEM;
20 
21 import android.Manifest.permission;
22 import android.annotation.CallbackExecutor;
23 import android.annotation.CurrentTimeMillisLong;
24 import android.annotation.FlaggedApi;
25 import android.annotation.FloatRange;
26 import android.annotation.IntDef;
27 import android.annotation.IntRange;
28 import android.annotation.NonNull;
29 import android.annotation.Nullable;
30 import android.annotation.RequiresPermission;
31 import android.annotation.SdkConstant;
32 import android.annotation.SuppressLint;
33 import android.annotation.SystemApi;
34 import android.annotation.SystemService;
35 import android.annotation.TestApi;
36 import android.app.PropertyInvalidatedCache;
37 import android.compat.annotation.UnsupportedAppUsage;
38 import android.content.Context;
39 import android.os.IScreenTimeoutPolicyListener;
40 import android.service.dreams.Sandman;
41 import android.util.ArrayMap;
42 import android.util.ArraySet;
43 import android.util.Log;
44 import android.util.proto.ProtoOutputStream;
45 import android.view.Display;
46 
47 import com.android.internal.annotations.GuardedBy;
48 import com.android.internal.util.Preconditions;
49 
50 import java.lang.annotation.ElementType;
51 import java.lang.annotation.Retention;
52 import java.lang.annotation.RetentionPolicy;
53 import java.lang.annotation.Target;
54 import java.net.InetAddress;
55 import java.net.UnknownHostException;
56 import java.time.Duration;
57 import java.util.ArrayList;
58 import java.util.Collections;
59 import java.util.List;
60 import java.util.Map;
61 import java.util.Objects;
62 import java.util.Set;
63 import java.util.concurrent.Executor;
64 import java.util.concurrent.atomic.AtomicLong;
65 
66 /**
67  * This class lets you query and request control of aspects of the device's power state.
68  */
69 @SystemService(Context.POWER_SERVICE)
70 public final class PowerManager {
71     private static final String TAG = "PowerManager";
72 
73     /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
74      * combinations were actually supported so the bit field was removed.  This explains
75      * why the numbering scheme is so odd.  If adding a new wake lock level, any unused
76      * value (in frameworks/proto_logging/stats/enums/os/enums.proto) can be used.
77      */
78 
79     /**
80      * Wake lock level: Ensures that the CPU is running; the screen and keyboard
81      * backlight will be allowed to go off.
82      * <p>
83      * If the user presses the power button, then the screen will be turned off
84      * but the CPU will be kept on until all partial wake locks have been released.
85      * </p>
86      */
87     public static final int PARTIAL_WAKE_LOCK = OsProtoEnums.PARTIAL_WAKE_LOCK; // 0x00000001
88 
89     /**
90      * Wake lock level: Ensures that the screen is on (but may be dimmed);
91      * the keyboard backlight will be allowed to go off.
92      * <p>
93      * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
94      * implicitly released by the system, causing both the screen and the CPU to be turned off.
95      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
96      * </p>
97      *
98      * @deprecated Most applications should use
99      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
100      * of this type of wake lock, as it will be correctly managed by the platform
101      * as the user moves between applications and doesn't require a special permission.
102      */
103     @Deprecated
104     public static final int SCREEN_DIM_WAKE_LOCK = OsProtoEnums.SCREEN_DIM_WAKE_LOCK; // 0x00000006
105 
106     /**
107      * Wake lock level: Ensures that the screen is on at full brightness;
108      * the keyboard backlight will be allowed to go off.
109      * <p>
110      * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
111      * implicitly released by the system, causing both the screen and the CPU to be turned off.
112      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
113      * </p>
114      *
115      * @deprecated Most applications should use
116      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
117      * of this type of wake lock, as it will be correctly managed by the platform
118      * as the user moves between applications and doesn't require a special permission.
119      */
120     @Deprecated
121     public static final int SCREEN_BRIGHT_WAKE_LOCK =
122             OsProtoEnums.SCREEN_BRIGHT_WAKE_LOCK; // 0x0000000a
123 
124     /**
125      * Wake lock level: Ensures that the screen and keyboard backlight are on at
126      * full brightness.
127      * <p>
128      * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
129      * implicitly released by the system, causing both the screen and the CPU to be turned off.
130      * Contrast with {@link #PARTIAL_WAKE_LOCK}.
131      * </p>
132      *
133      * @deprecated Most applications should use
134      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
135      * of this type of wake lock, as it will be correctly managed by the platform
136      * as the user moves between applications and doesn't require a special permission.
137      */
138     @Deprecated
139     public static final int FULL_WAKE_LOCK = OsProtoEnums.FULL_WAKE_LOCK; // 0x0000001a
140 
141     /**
142      * Wake lock level: Turns the screen off when the proximity sensor activates.
143      * <p>
144      * If the proximity sensor detects that an object is nearby, the screen turns off
145      * immediately.  Shortly after the object moves away, the screen turns on again.
146      * </p><p>
147      * A proximity wake lock does not prevent the device from falling asleep
148      * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
149      * {@link #SCREEN_DIM_WAKE_LOCK}.  If there is no user activity and no other
150      * wake locks are held, then the device will fall asleep (and lock) as usual.
151      * However, the device will not fall asleep while the screen has been turned off
152      * by the proximity sensor because it effectively counts as ongoing user activity.
153      * </p><p>
154      * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
155      * to determine whether this wake lock level is supported.
156      * </p><p>
157      * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
158      * </p>
159      */
160     public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK =
161             OsProtoEnums.PROXIMITY_SCREEN_OFF_WAKE_LOCK; // 0x00000020
162 
163     /**
164      * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
165      * if no other wake locks are held.
166      * <p>
167      * This is used by the dream manager to implement doze mode.  It currently
168      * has no effect unless the power manager is in the dozing state.
169      * </p><p>
170      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
171      * </p>
172      *
173      * {@hide}
174      */
175     public static final int DOZE_WAKE_LOCK = OsProtoEnums.DOZE_WAKE_LOCK; // 0x00000040
176 
177     /**
178      * Wake lock level: Keep the device awake enough to allow drawing to occur.
179      * <p>
180      * This is used by the window manager to allow applications to draw while the
181      * system is dozing.  It currently has no effect unless the power manager is in
182      * the dozing state.
183      * </p><p>
184      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
185      * </p>
186      *
187      * {@hide}
188      */
189     public static final int DRAW_WAKE_LOCK = OsProtoEnums.DRAW_WAKE_LOCK; // 0x00000080
190 
191     /**
192      * Wake lock level: Override the current screen timeout.
193      * <p>
194      *  This is used by the system to allow {@code PowerManagerService} to override the current
195      *  screen timeout by config value.
196      *
197      *  config_screenTimeoutOverride in config.xml determines the screen timeout override value.
198      * </p><p>
199      * Requires the {@link android.Manifest.permission#SCREEN_TIMEOUT_OVERRIDE} permission.
200      * </p>
201      *
202      * @hide
203      */
204     public static final int SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK =
205             OsProtoEnums.SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK; // 0x00000100
206 
207     /**
208      * Mask for the wake lock level component of a combined wake lock level and flags integer.
209      *
210      * @hide
211      */
212     public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
213 
214     /**
215      * Wake lock flag: Turn the screen on when the wake lock is acquired.
216      * <p>
217      * This flag will require {@link android.Manifest.permission#TURN_SCREEN_ON} in future releases.
218      * </p><p>
219      * Normally wake locks don't actually wake the device, they just cause the screen to remain on
220      * once it's already on. This flag will cause the device to wake up when the wake lock is
221      * acquired.
222      * </p><p>
223      * Android TV playback devices attempt to turn on the HDMI-connected TV via HDMI-CEC on any
224      * wake-up, including wake-ups triggered by wake locks.
225      * </p><p>
226      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
227      * </p>
228      *
229      * @deprecated Most applications should use {@link android.R.attr#turnScreenOn} or
230      * {@link android.app.Activity#setTurnScreenOn(boolean)} instead, as this prevents the previous
231      * foreground app from being resumed first when the screen turns on.
232      */
233     @Deprecated
234     @RequiresPermission(value = android.Manifest.permission.TURN_SCREEN_ON, conditional = true)
235     public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
236 
237     /**
238      * Wake lock flag: When this wake lock is released, poke the user activity timer
239      * so the screen stays on for a little longer.
240      * <p>
241      * This will not turn the screen on if it is not already on.
242      * </p><p>
243      * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
244      * </p>
245      */
246     public static final int ON_AFTER_RELEASE = 0x20000000;
247 
248     /**
249      * Wake lock flag: This wake lock is not important for logging events.  If a later
250      * wake lock is acquired that is important, it will be considered the one to log.
251      * @hide
252      */
253     public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
254 
255     /**
256      * Wake lock flag: This wake lock should be held by the system.
257      *
258      * <p>Meant to allow tests to keep the device awake even when power restrictions are active.
259      *
260      * @hide
261      */
262     @TestApi
263     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
264     public static final int SYSTEM_WAKELOCK = 0x80000000;
265 
266     /**
267      * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
268      * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
269      * indicates that an object is not in close proximity.
270      */
271     public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1 << 0;
272 
273     /**
274      * Flag for {@link WakeLock#release(int)} when called due to timeout.
275      * @hide
276      */
277     public static final int RELEASE_FLAG_TIMEOUT = 1 << 16;
278 
279     /**
280      * Brightness value for fully on.
281      * @hide
282      */
283     @UnsupportedAppUsage
284     public static final int BRIGHTNESS_ON = 255;
285 
286     /**
287      * Brightness value for fully off.
288      * @hide
289      */
290     public static final int BRIGHTNESS_OFF = 0;
291 
292     /**
293      * Brightness value for default policy handling by the system.
294      * @hide
295      */
296     public static final int BRIGHTNESS_DEFAULT = -1;
297 
298     /**
299      * Brightness value for an invalid value having been stored.
300      * @hide
301      */
302     public static final int BRIGHTNESS_INVALID = -1;
303 
304     //Brightness values for new float implementation:
305     /**
306      * Brightness value for fully on as float.
307      * @hide
308      */
309     public static final float BRIGHTNESS_MAX = 1.0f;
310 
311     /**
312      * Brightness value for minimum valid brightness as float.
313      * @hide
314      */
315     public static final float BRIGHTNESS_MIN = 0.0f;
316 
317     /**
318      * Brightness value for fully off in float.
319      * @hide
320      */
321     public static final float BRIGHTNESS_OFF_FLOAT = -1.0f;
322 
323     /**
324      * Invalid brightness value.
325      * @hide
326      */
327     public static final float BRIGHTNESS_INVALID_FLOAT = Float.NaN;
328 
329     // Note: Be sure to update android.os.BatteryStats and PowerManager.h
330     // if adding or modifying user activity event constants.
331 
332     /**
333      * User activity event type: Unspecified event type.
334      * @hide
335      */
336     @SystemApi
337     public static final int USER_ACTIVITY_EVENT_OTHER = 0;
338 
339     /**
340      * User activity event type: Button or key pressed or released.
341      * @hide
342      */
343     @SystemApi
344     public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
345 
346     /**
347      * User activity event type: Touch down, move or up.
348      * @hide
349      */
350     @SystemApi
351     public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
352 
353     /**
354      * User activity event type: Accessibility taking action on behalf of user.
355      * @hide
356      */
357     @SystemApi
358     public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
359 
360     /**
361      * User activity event type: {@link android.service.attention.AttentionService} taking action
362      * on behalf of user.
363      * @hide
364      */
365     public static final int USER_ACTIVITY_EVENT_ATTENTION = 4;
366 
367     /**
368      * User activity event type: {@link com.android.server.power.FaceDownDetector} taking action
369      * on behalf of user.
370      * @hide
371      */
372     public static final int USER_ACTIVITY_EVENT_FACE_DOWN = 5;
373 
374     /**
375      * User activity event type: There is a change in the device state.
376      * @hide
377      */
378     public static final int USER_ACTIVITY_EVENT_DEVICE_STATE = 6;
379 
380     /**
381      * @hide
382      */
383     @IntDef(prefix = { "USER_ACTIVITY_EVENT_" }, value = {
384             USER_ACTIVITY_EVENT_OTHER,
385             USER_ACTIVITY_EVENT_BUTTON,
386             USER_ACTIVITY_EVENT_TOUCH,
387             USER_ACTIVITY_EVENT_ACCESSIBILITY,
388             USER_ACTIVITY_EVENT_ATTENTION,
389             USER_ACTIVITY_EVENT_FACE_DOWN,
390             USER_ACTIVITY_EVENT_DEVICE_STATE,
391     })
392     @Retention(RetentionPolicy.SOURCE)
393     public @interface UserActivityEvent{}
394 
395     /**
396      *
397      * Convert the user activity event to a string for debugging purposes.
398      * @hide
399      */
userActivityEventToString(@serActivityEvent int userActivityEvent)400     public static String userActivityEventToString(@UserActivityEvent int userActivityEvent) {
401         switch (userActivityEvent) {
402             case USER_ACTIVITY_EVENT_OTHER: return "other";
403             case USER_ACTIVITY_EVENT_BUTTON: return "button";
404             case USER_ACTIVITY_EVENT_TOUCH: return "touch";
405             case USER_ACTIVITY_EVENT_ACCESSIBILITY: return "accessibility";
406             case USER_ACTIVITY_EVENT_ATTENTION: return "attention";
407             case USER_ACTIVITY_EVENT_FACE_DOWN: return "faceDown";
408             case USER_ACTIVITY_EVENT_DEVICE_STATE: return "deviceState";
409             default: return Integer.toString(userActivityEvent);
410         }
411     }
412 
413     /**
414      * User activity flag: If already dimmed, extend the dim timeout
415      * but do not brighten.  This flag is useful for keeping the screen on
416      * a little longer without causing a visible change such as when
417      * the power key is pressed.
418      * @hide
419      */
420     @SystemApi
421     public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
422 
423     /**
424      * User activity flag: Note the user activity as usual but do not
425      * reset the user activity timeout.  This flag is useful for applying
426      * user activity power hints when interacting with the device indirectly
427      * on a secondary screen while allowing the primary screen to go to sleep.
428      * @hide
429      */
430     @SystemApi
431     public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
432 
433     /**
434      * @hide
435      */
436     public static final int GO_TO_SLEEP_REASON_MIN = 0;
437 
438     /**
439      * Go to sleep reason code: Going to sleep due by application request.
440      * @hide
441      */
442     public static final int GO_TO_SLEEP_REASON_APPLICATION = GO_TO_SLEEP_REASON_MIN;
443 
444     /**
445      * Go to sleep reason code: Going to sleep due by request of the
446      * device administration policy.
447      * @hide
448      */
449     public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
450 
451     /**
452      * Go to sleep reason code: Going to sleep due to a screen timeout.
453      * @hide
454      */
455     @UnsupportedAppUsage
456     public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
457 
458     /**
459      * Go to sleep reason code: Going to sleep due to the lid switch being closed.
460      * @hide
461      */
462     public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
463 
464     /**
465      * Go to sleep reason code: Going to sleep due to the power button being pressed.
466      * @hide
467      */
468     public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
469 
470     /**
471      * Go to sleep reason code: Going to sleep due to HDMI.
472      * @hide
473      */
474     public static final int GO_TO_SLEEP_REASON_HDMI = 5;
475 
476     /**
477      * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
478      * @hide
479      */
480     public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
481 
482     /**
483      * Go to sleep reason code: Going to sleep by request of an accessibility service
484      * @hide
485      */
486     public static final int GO_TO_SLEEP_REASON_ACCESSIBILITY = 7;
487 
488     /**
489      * Go to sleep reason code: Going to sleep due to force-suspend.
490      * @hide
491      */
492     public static final int GO_TO_SLEEP_REASON_FORCE_SUSPEND = 8;
493 
494     /**
495      * Go to sleep reason code: Going to sleep due to user inattentiveness.
496      * @hide
497      */
498     public static final int GO_TO_SLEEP_REASON_INATTENTIVE = 9;
499 
500     /**
501      * Go to sleep reason code: Going to sleep due to quiescent boot.
502      * @hide
503      */
504     public static final int GO_TO_SLEEP_REASON_QUIESCENT = 10;
505 
506     /**
507      * Go to sleep reason code: The last powered on display group has been removed.
508      * @hide
509      */
510     public static final int GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED = 11;
511 
512     /**
513      * Go to sleep reason code: Every display group has been turned off.
514      * @hide
515      */
516     public static final int GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF = 12;
517 
518     /**
519      * Go to sleep reason code: A foldable device has been folded.
520      * @hide
521      */
522     public static final int GO_TO_SLEEP_REASON_DEVICE_FOLD = 13;
523 
524     /**
525      * Go to sleep reason code: reason unknown.
526      * @hide
527      */
528     public static final int GO_TO_SLEEP_REASON_UNKNOWN = 14;
529 
530     /**
531      * @hide
532      */
533     public static final int GO_TO_SLEEP_REASON_MAX =  GO_TO_SLEEP_REASON_UNKNOWN;
534 
535     /**
536      * @hide
537      */
sleepReasonToString(@oToSleepReason int sleepReason)538     public static String sleepReasonToString(@GoToSleepReason int sleepReason) {
539         switch (sleepReason) {
540             case GO_TO_SLEEP_REASON_ACCESSIBILITY: return "accessibility";
541             case GO_TO_SLEEP_REASON_APPLICATION: return "application";
542             case GO_TO_SLEEP_REASON_DEVICE_ADMIN: return "device_admin";
543             case GO_TO_SLEEP_REASON_DEVICE_FOLD: return "device_folded";
544             case GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED: return "display_group_removed";
545             case GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF: return "display_groups_turned_off";
546             case GO_TO_SLEEP_REASON_FORCE_SUSPEND: return "force_suspend";
547             case GO_TO_SLEEP_REASON_HDMI: return "hdmi";
548             case GO_TO_SLEEP_REASON_INATTENTIVE: return "inattentive";
549             case GO_TO_SLEEP_REASON_LID_SWITCH: return "lid_switch";
550             case GO_TO_SLEEP_REASON_POWER_BUTTON: return "power_button";
551             case GO_TO_SLEEP_REASON_QUIESCENT: return "quiescent";
552             case GO_TO_SLEEP_REASON_SLEEP_BUTTON: return "sleep_button";
553             case GO_TO_SLEEP_REASON_TIMEOUT: return "timeout";
554             case GO_TO_SLEEP_REASON_UNKNOWN: return "unknown";
555             default: return Integer.toString(sleepReason);
556         }
557     }
558 
559     /**
560      * Go to sleep flag: Skip dozing state and directly go to full sleep.
561      * @hide
562      */
563     public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
564 
565     /**
566      * Go to sleep flag: Sleep softly, go to sleep only if there's no wakelock explicitly keeping
567      * the device awake.
568      * @hide
569      */
570     public static final int GO_TO_SLEEP_FLAG_SOFT_SLEEP = 1 << 1;
571 
572     /**
573      * @hide
574      */
575     @IntDef(prefix = { "BRIGHTNESS_CONSTRAINT_TYPE" }, value = {
576             BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM,
577             BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM,
578             BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT,
579             BRIGHTNESS_CONSTRAINT_TYPE_DIM
580     })
581     @Retention(RetentionPolicy.SOURCE)
582     public @interface BrightnessConstraint{}
583 
584     /**
585      * Brightness constraint type: minimum allowed value.
586      * @hide
587      */
588     public static final int BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM = 0;
589     /**
590      * Brightness constraint type: minimum allowed value.
591      * @hide
592      */
593     public static final int BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM = 1;
594 
595     /**
596      * Brightness constraint type: minimum allowed value.
597      * @hide
598      */
599     public static final int BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT = 2;
600 
601     /**
602      * Brightness constraint type: minimum allowed value.
603      * @hide
604      */
605     public static final int BRIGHTNESS_CONSTRAINT_TYPE_DIM = 3;
606 
607     /**
608      * @hide
609      */
610     @IntDef(prefix = { "WAKE_REASON_" }, value = {
611             WAKE_REASON_UNKNOWN,
612             WAKE_REASON_POWER_BUTTON,
613             WAKE_REASON_APPLICATION,
614             WAKE_REASON_PLUGGED_IN,
615             WAKE_REASON_GESTURE,
616             WAKE_REASON_CAMERA_LAUNCH,
617             WAKE_REASON_WAKE_KEY,
618             WAKE_REASON_WAKE_MOTION,
619             WAKE_REASON_HDMI,
620             WAKE_REASON_LID,
621             WAKE_REASON_DISPLAY_GROUP_ADDED,
622             WAKE_REASON_DISPLAY_GROUP_TURNED_ON,
623             WAKE_REASON_UNFOLD_DEVICE,
624             WAKE_REASON_DREAM_FINISHED,
625             WAKE_REASON_TILT,
626             WAKE_REASON_TAP,
627             WAKE_REASON_LIFT,
628             WAKE_REASON_BIOMETRIC,
629             WAKE_REASON_DOCK,
630     })
631     @Retention(RetentionPolicy.SOURCE)
632     public @interface WakeReason{}
633 
634     /**
635      * @hide
636      */
637     @IntDef(prefix = { "GO_TO_SLEEP_REASON_" }, value = {
638             GO_TO_SLEEP_REASON_ACCESSIBILITY,
639             GO_TO_SLEEP_REASON_APPLICATION,
640             GO_TO_SLEEP_REASON_DEVICE_ADMIN,
641             GO_TO_SLEEP_REASON_DEVICE_FOLD,
642             GO_TO_SLEEP_REASON_DISPLAY_GROUP_REMOVED,
643             GO_TO_SLEEP_REASON_DISPLAY_GROUPS_TURNED_OFF,
644             GO_TO_SLEEP_REASON_FORCE_SUSPEND,
645             GO_TO_SLEEP_REASON_HDMI,
646             GO_TO_SLEEP_REASON_INATTENTIVE,
647             GO_TO_SLEEP_REASON_LID_SWITCH,
648             GO_TO_SLEEP_REASON_POWER_BUTTON,
649             GO_TO_SLEEP_REASON_QUIESCENT,
650             GO_TO_SLEEP_REASON_SLEEP_BUTTON,
651             GO_TO_SLEEP_REASON_TIMEOUT,
652             GO_TO_SLEEP_REASON_UNKNOWN,
653     })
654     @Retention(RetentionPolicy.SOURCE)
655     public @interface GoToSleepReason{}
656 
657     /**
658      * Wake up reason code: Waking for an unknown reason.
659      * @hide
660      */
661     public static final int WAKE_REASON_UNKNOWN = 0;
662 
663     /**
664      * Wake up reason code: Waking up due to power button press.
665      * @hide
666      */
667     public static final int WAKE_REASON_POWER_BUTTON = 1;
668 
669     /**
670      * Wake up reason code: Waking up because an application requested it.
671      * @hide
672      */
673     public static final int WAKE_REASON_APPLICATION = 2;
674 
675     /**
676      * Wake up reason code: Waking up due to being plugged in or docked on a wireless charger.
677      * @hide
678      */
679     public static final int WAKE_REASON_PLUGGED_IN = 3;
680 
681     /**
682      * Wake up reason code: Waking up due to a user performed gesture. This includes user
683      * interactions with UI on the screen such as the notification shade. This does not include
684      * {@link WAKE_REASON_TAP} or {@link WAKE_REASON_LIFT}.
685      * @hide
686      */
687     public static final int WAKE_REASON_GESTURE = 4;
688 
689     /**
690      * Wake up reason code: Waking up due to the camera being launched.
691      * @hide
692      */
693     public static final int WAKE_REASON_CAMERA_LAUNCH = 5;
694 
695     /**
696      * Wake up reason code: Waking up because a wake key other than power was pressed.
697      * @hide
698      */
699     public static final int WAKE_REASON_WAKE_KEY = 6;
700 
701     /**
702      * Wake up reason code: Waking up because a wake motion was performed.
703      *
704      * For example, a trackball that was set to wake the device up was spun.
705      * @hide
706      */
707     public static final int WAKE_REASON_WAKE_MOTION = 7;
708 
709     /**
710      * Wake up reason code: Waking due to HDMI.
711      * @hide
712      */
713     public static final int WAKE_REASON_HDMI = 8;
714 
715     /**
716      * Wake up reason code: Waking due to the lid being opened.
717      * @hide
718      */
719     public static final int WAKE_REASON_LID = 9;
720 
721     /**
722      * Wake up reason code: Waking due to display group being added.
723      * @hide
724      */
725     public static final int WAKE_REASON_DISPLAY_GROUP_ADDED = 10;
726 
727     /**
728      * Wake up reason code: Waking due to display group being powered on.
729      * @hide
730      */
731     public static final int WAKE_REASON_DISPLAY_GROUP_TURNED_ON = 11;
732 
733     /**
734      * Wake up reason code: Waking the device due to unfolding of a foldable device.
735      * @hide
736      */
737     public static final int WAKE_REASON_UNFOLD_DEVICE = 12;
738 
739     /**
740      * Wake up reason code: Waking the device due to the dream finishing.
741      * @hide
742      */
743     public static final int WAKE_REASON_DREAM_FINISHED = 13;
744 
745     /**
746      * Wake up reason code: Waking due to tilt.
747      * @hide
748      */
749     public static final int WAKE_REASON_TILT = 14;
750     /**
751      * Wake up reason code: Waking up due to the user single or double tapping on the screen. This
752      * wake reason is used when the user is not tapping on a specific UI element; rather, the device
753      * wakes up due to a generic tap on the screen.
754      * @hide
755      */
756     public static final int WAKE_REASON_TAP = 15;
757 
758     /**
759      * Wake up reason code: Waking up due to a user performed lift gesture.
760      * @hide
761      */
762     public static final int WAKE_REASON_LIFT = 16;
763 
764     /**
765      * Wake up reason code: Waking up due to a user interacting with a biometric.
766      * @hide
767      */
768     public static final int WAKE_REASON_BIOMETRIC = 17;
769 
770     /**
771      * Wake up reason code: Waking up due to a user docking the device.
772      * @hide
773      */
774     public static final int WAKE_REASON_DOCK = 18;
775 
776     /**
777      * Convert the wake reason to a string for debugging purposes.
778      * @hide
779      */
wakeReasonToString(@akeReason int wakeReason)780     public static String wakeReasonToString(@WakeReason int wakeReason) {
781         switch (wakeReason) {
782             case WAKE_REASON_UNKNOWN: return "WAKE_REASON_UNKNOWN";
783             case WAKE_REASON_POWER_BUTTON: return "WAKE_REASON_POWER_BUTTON";
784             case WAKE_REASON_APPLICATION: return "WAKE_REASON_APPLICATION";
785             case WAKE_REASON_PLUGGED_IN: return "WAKE_REASON_PLUGGED_IN";
786             case WAKE_REASON_GESTURE: return "WAKE_REASON_GESTURE";
787             case WAKE_REASON_CAMERA_LAUNCH: return "WAKE_REASON_CAMERA_LAUNCH";
788             case WAKE_REASON_WAKE_KEY: return "WAKE_REASON_WAKE_KEY";
789             case WAKE_REASON_WAKE_MOTION: return "WAKE_REASON_WAKE_MOTION";
790             case WAKE_REASON_HDMI: return "WAKE_REASON_HDMI";
791             case WAKE_REASON_LID: return "WAKE_REASON_LID";
792             case WAKE_REASON_DISPLAY_GROUP_ADDED: return "WAKE_REASON_DISPLAY_GROUP_ADDED";
793             case WAKE_REASON_DISPLAY_GROUP_TURNED_ON: return "WAKE_REASON_DISPLAY_GROUP_TURNED_ON";
794             case WAKE_REASON_UNFOLD_DEVICE: return "WAKE_REASON_UNFOLD_DEVICE";
795             case WAKE_REASON_DREAM_FINISHED: return "WAKE_REASON_DREAM_FINISHED";
796             case WAKE_REASON_TILT: return "WAKE_REASON_TILT";
797             case WAKE_REASON_TAP: return "WAKE_REASON_TAP";
798             case WAKE_REASON_LIFT: return "WAKE_REASON_LIFT";
799             case WAKE_REASON_BIOMETRIC: return "WAKE_REASON_BIOMETRIC";
800             case WAKE_REASON_DOCK: return "WAKE_REASON_DOCK";
801             default: return Integer.toString(wakeReason);
802         }
803     }
804 
805     /**
806      * Information related to the device waking up, triggered by {@link #wakeUp}.
807      *
808      * @hide
809      */
810     public static class WakeData {
WakeData(long wakeTime, @WakeReason int wakeReason, long sleepDurationRealtime)811         public WakeData(long wakeTime, @WakeReason int wakeReason, long sleepDurationRealtime) {
812             this.wakeTime = wakeTime;
813             this.wakeReason = wakeReason;
814             this.sleepDurationRealtime = sleepDurationRealtime;
815         }
816         public final long wakeTime;
817         public final @WakeReason int wakeReason;
818         public final long sleepDurationRealtime;
819 
820         @Override
equals(@ullable Object o)821         public boolean equals(@Nullable Object o) {
822             if (o instanceof WakeData) {
823                 final WakeData other = (WakeData) o;
824                 return wakeTime == other.wakeTime && wakeReason == other.wakeReason
825                         && sleepDurationRealtime == other.sleepDurationRealtime;
826             }
827             return false;
828         }
829 
830         @Override
hashCode()831         public int hashCode() {
832             return Objects.hash(wakeTime, wakeReason, sleepDurationRealtime);
833         }
834     }
835 
836     /**
837      * Information related to the device going to sleep, triggered by {@link #goToSleep}.
838      *
839      * @hide
840      */
841     public static class SleepData {
SleepData(long goToSleepUptimeMillis, @GoToSleepReason int goToSleepReason)842         public SleepData(long goToSleepUptimeMillis, @GoToSleepReason int goToSleepReason) {
843             this.goToSleepUptimeMillis = goToSleepUptimeMillis;
844             this.goToSleepReason = goToSleepReason;
845         }
846         public final long goToSleepUptimeMillis;
847         public final @GoToSleepReason int goToSleepReason;
848 
849         @Override
equals(@ullable Object o)850         public boolean equals(@Nullable Object o) {
851             if (o instanceof SleepData) {
852                 final SleepData other = (SleepData) o;
853                 return goToSleepUptimeMillis == other.goToSleepUptimeMillis
854                         && goToSleepReason == other.goToSleepReason;
855             }
856             return false;
857         }
858 
859         @Override
hashCode()860         public int hashCode() {
861             return Objects.hash(goToSleepUptimeMillis, goToSleepReason);
862         }
863     }
864 
865     /**
866      * The value to pass as the 'reason' argument to reboot() to reboot into
867      * recovery mode for tasks other than applying system updates, such as
868      * doing factory resets.
869      * <p>
870      * Requires the {@link android.Manifest.permission#RECOVERY}
871      * permission (in addition to
872      * {@link android.Manifest.permission#REBOOT}).
873      * </p>
874      * @hide
875      */
876     public static final String REBOOT_RECOVERY = "recovery";
877 
878     /**
879      * The value to pass as the 'reason' argument to reboot() to reboot into
880      * recovery mode for applying system updates.
881      * <p>
882      * Requires the {@link android.Manifest.permission#RECOVERY}
883      * permission (in addition to
884      * {@link android.Manifest.permission#REBOOT}).
885      * </p>
886      * @hide
887      */
888     public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
889 
890     /**
891      * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
892      * the device.
893      * @hide
894      */
895     public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
896 
897     /**
898      * The 'reason' value used when rebooting in safe mode
899      * @hide
900      */
901     public static final String REBOOT_SAFE_MODE = "safemode";
902 
903     /**
904      * The 'reason' value used for rebooting userspace.
905      *
906      * @deprecated userspace reboot is not supported
907      * @hide
908      */
909     @SystemApi
910     public static final String REBOOT_USERSPACE = "userspace";
911 
912     /**
913      * The 'reason' value used when rebooting the device without turning on the screen.
914      * @hide
915      */
916     public static final String REBOOT_QUIESCENT = "quiescent";
917 
918     /**
919      * The value to pass as the 'reason' argument to android_reboot().
920      * @hide
921      */
922     public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
923 
924     /**
925      * The value to pass as the 'reason' argument to android_reboot() when battery temperature
926      * is too high.
927      * @hide
928      */
929     public static final String SHUTDOWN_BATTERY_THERMAL_STATE = "thermal,battery";
930 
931     /**
932      * The value to pass as the 'reason' argument to android_reboot() when device temperature
933      * is too high.
934      * @hide
935      */
936     public static final String SHUTDOWN_THERMAL_STATE = "thermal";
937 
938     /**
939      * The value to pass as the 'reason' argument to android_reboot() when device is running
940      * critically low on battery.
941      * @hide
942      */
943     public static final String SHUTDOWN_LOW_BATTERY = "battery";
944 
945     /**
946      * @hide
947      */
948     @Retention(RetentionPolicy.SOURCE)
949     @IntDef(prefix = { "SHUTDOWN_REASON_" }, value = {
950             SHUTDOWN_REASON_UNKNOWN,
951             SHUTDOWN_REASON_SHUTDOWN,
952             SHUTDOWN_REASON_REBOOT,
953             SHUTDOWN_REASON_USER_REQUESTED,
954             SHUTDOWN_REASON_THERMAL_SHUTDOWN,
955             SHUTDOWN_REASON_LOW_BATTERY,
956             SHUTDOWN_REASON_BATTERY_THERMAL
957     })
958     public @interface ShutdownReason {}
959 
960     /**
961      * constant for shutdown reason being unknown.
962      * @hide
963      */
964     public static final int SHUTDOWN_REASON_UNKNOWN = 0;
965 
966     /**
967      * constant for shutdown reason being normal shutdown.
968      * @hide
969      */
970     public static final int SHUTDOWN_REASON_SHUTDOWN = 1;
971 
972     /**
973      * constant for shutdown reason being reboot.
974      * @hide
975      */
976     public static final int SHUTDOWN_REASON_REBOOT = 2;
977 
978     /**
979      * constant for shutdown reason being user requested.
980      * @hide
981      */
982     public static final int SHUTDOWN_REASON_USER_REQUESTED = 3;
983 
984     /**
985      * constant for shutdown reason being overheating.
986      * @hide
987      */
988     public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4;
989 
990     /**
991      * constant for shutdown reason being low battery.
992      * @hide
993      */
994     public static final int SHUTDOWN_REASON_LOW_BATTERY = 5;
995 
996     /**
997      * constant for shutdown reason being critical battery thermal state.
998      * @hide
999      */
1000     public static final int SHUTDOWN_REASON_BATTERY_THERMAL = 6;
1001 
1002     /**
1003      * @hide
1004      */
1005     @Retention(RetentionPolicy.SOURCE)
1006     @IntDef({ServiceType.LOCATION,
1007             ServiceType.VIBRATION,
1008             ServiceType.ANIMATION,
1009             ServiceType.FULL_BACKUP,
1010             ServiceType.KEYVALUE_BACKUP,
1011             ServiceType.NETWORK_FIREWALL,
1012             ServiceType.SCREEN_BRIGHTNESS,
1013             ServiceType.SOUND,
1014             ServiceType.BATTERY_STATS,
1015             ServiceType.DATA_SAVER,
1016             ServiceType.FORCE_ALL_APPS_STANDBY,
1017             ServiceType.FORCE_BACKGROUND_CHECK,
1018             ServiceType.OPTIONAL_SENSORS,
1019             ServiceType.AOD,
1020             ServiceType.QUICK_DOZE,
1021             ServiceType.NIGHT_MODE,
1022     })
1023     public @interface ServiceType {
1024         int NULL = 0;
1025         int LOCATION = 1;
1026         int VIBRATION = 2;
1027         int ANIMATION = 3;
1028         int FULL_BACKUP = 4;
1029         int KEYVALUE_BACKUP = 5;
1030         int NETWORK_FIREWALL = 6;
1031         int SCREEN_BRIGHTNESS = 7;
1032         int SOUND = 8;
1033         int BATTERY_STATS = 9;
1034         int DATA_SAVER = 10;
1035         int AOD = 14;
1036 
1037         /**
1038          * Whether to enable force-app-standby on all apps or not.
1039          */
1040         int FORCE_ALL_APPS_STANDBY = 11;
1041 
1042         /**
1043          * Whether to enable background check on all apps or not.
1044          */
1045         int FORCE_BACKGROUND_CHECK = 12;
1046 
1047         /**
1048          * Whether to disable non-essential sensors. (e.g. edge sensors.)
1049          */
1050         int OPTIONAL_SENSORS = 13;
1051 
1052         /**
1053          * Whether to go into Deep Doze as soon as the screen turns off or not.
1054          */
1055         int QUICK_DOZE = 15;
1056 
1057         /**
1058          * Whether to enable night mode when battery saver is enabled.
1059          */
1060         int NIGHT_MODE = 16;
1061     }
1062 
1063     /**
1064      * Screen timeout policy type: the screen turns off after a timeout
1065      * @hide
1066      */
1067     public static final int SCREEN_TIMEOUT_ACTIVE = 0;
1068 
1069     /**
1070      * Screen timeout policy type: the screen is kept 'on' (no timeout)
1071      * @hide
1072      */
1073     public static final int SCREEN_TIMEOUT_KEEP_DISPLAY_ON = 1;
1074 
1075     /**
1076      * @hide
1077      */
1078     @IntDef(prefix = { "SCREEN_TIMEOUT_" }, value = {
1079             SCREEN_TIMEOUT_ACTIVE,
1080             SCREEN_TIMEOUT_KEEP_DISPLAY_ON
1081     })
1082     @Retention(RetentionPolicy.SOURCE)
1083     public @interface ScreenTimeoutPolicy{}
1084 
1085 
1086     /**
1087      * Either the location providers shouldn't be affected by battery saver,
1088      * or battery saver is off.
1089      */
1090     public static final int LOCATION_MODE_NO_CHANGE = 0;
1091 
1092     /**
1093      * In this mode, the GPS based location provider should be disabled when battery saver is on and
1094      * the device is non-interactive.
1095      */
1096     public static final int LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 1;
1097 
1098     /**
1099      * All location providers should be disabled when battery saver is on and
1100      * the device is non-interactive.
1101      */
1102     public static final int LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 2;
1103 
1104     /**
1105      * In this mode, all the location providers will be kept available, but location fixes
1106      * should only be provided to foreground apps.
1107      */
1108     public static final int LOCATION_MODE_FOREGROUND_ONLY = 3;
1109 
1110     /**
1111      * In this mode, location will not be turned off, but LocationManager will throttle all
1112      * requests to providers when the device is non-interactive.
1113      */
1114     public static final int LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 4;
1115 
1116     /** @hide */
1117     public static final int MIN_LOCATION_MODE = LOCATION_MODE_NO_CHANGE;
1118     /** @hide */
1119     public static final int MAX_LOCATION_MODE = LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF;
1120 
1121     /**
1122      * @hide
1123      */
1124     @Retention(RetentionPolicy.SOURCE)
1125     @IntDef(prefix = {"LOCATION_MODE_"}, value = {
1126             LOCATION_MODE_NO_CHANGE,
1127             LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF,
1128             LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF,
1129             LOCATION_MODE_FOREGROUND_ONLY,
1130             LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF,
1131     })
1132     public @interface LocationPowerSaveMode {}
1133 
1134     /**
1135      * In this mode, all active SoundTrigger recognitions are enabled by the SoundTrigger system
1136      * service.
1137      * @hide
1138      */
1139     @SystemApi
1140     public static final int SOUND_TRIGGER_MODE_ALL_ENABLED = 0;
1141     /**
1142      * In this mode, only privileged components of the SoundTrigger system service should be
1143      * enabled. This functionality is to be used to limit SoundTrigger recognitions to those only
1144      * deemed necessary by the system.
1145      * @hide
1146      */
1147     @SystemApi
1148     public static final int SOUND_TRIGGER_MODE_CRITICAL_ONLY = 1;
1149     /**
1150      * In this mode, all active SoundTrigger recognitions should be disabled by the SoundTrigger
1151      * system service.
1152      * @hide
1153      */
1154     @SystemApi
1155     public static final int SOUND_TRIGGER_MODE_ALL_DISABLED = 2;
1156 
1157     /** @hide */
1158     public static final int MIN_SOUND_TRIGGER_MODE = SOUND_TRIGGER_MODE_ALL_ENABLED;
1159     /** @hide */
1160     public static final int MAX_SOUND_TRIGGER_MODE = SOUND_TRIGGER_MODE_ALL_DISABLED;
1161 
1162     /**
1163      * @hide
1164      */
1165     @Retention(RetentionPolicy.SOURCE)
1166     @IntDef(prefix = {"SOUND_TRIGGER_MODE_"}, value = {
1167             SOUND_TRIGGER_MODE_ALL_ENABLED,
1168             SOUND_TRIGGER_MODE_CRITICAL_ONLY,
1169             SOUND_TRIGGER_MODE_ALL_DISABLED,
1170     })
1171     public @interface SoundTriggerPowerSaveMode {}
1172 
1173     /** @hide */
locationPowerSaveModeToString(@ocationPowerSaveMode int mode)1174     public static String locationPowerSaveModeToString(@LocationPowerSaveMode int mode) {
1175         switch (mode) {
1176             case LOCATION_MODE_NO_CHANGE:
1177                 return "NO_CHANGE";
1178             case LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF:
1179                 return "GPS_DISABLED_WHEN_SCREEN_OFF";
1180             case LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF:
1181                 return "ALL_DISABLED_WHEN_SCREEN_OFF";
1182             case LOCATION_MODE_FOREGROUND_ONLY:
1183                 return "FOREGROUND_ONLY";
1184             case LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF:
1185                 return "THROTTLE_REQUESTS_WHEN_SCREEN_OFF";
1186             default:
1187                 return Integer.toString(mode);
1188         }
1189     }
1190 
1191     private static final String CACHE_KEY_IS_POWER_SAVE_MODE_API = "is_power_save_mode";
1192 
1193     private static final String CACHE_KEY_IS_INTERACTIVE_API = "is_interactive";
1194 
1195     private static final int MAX_CACHE_ENTRIES = 1;
1196 
getCacheArgs(String api)1197     private static PropertyInvalidatedCache.Args getCacheArgs(String api) {
1198         return new PropertyInvalidatedCache.Args(MODULE_SYSTEM)
1199                 .maxEntries(MAX_CACHE_ENTRIES)
1200                 .isolateUids(false)
1201                 .cacheNulls(false)
1202                 .api(api);
1203     }
1204 
1205     private final PropertyInvalidatedCache<Void, Boolean> mPowerSaveModeCache =
1206             new PropertyInvalidatedCache<>(getCacheArgs(CACHE_KEY_IS_POWER_SAVE_MODE_API),
1207                     CACHE_KEY_IS_POWER_SAVE_MODE_API, null) {
1208                 @Override
1209                 public Boolean recompute(Void query) {
1210                     try {
1211                         return mService.isPowerSaveMode();
1212                     } catch (RemoteException e) {
1213                         throw e.rethrowFromSystemServer();
1214                     }
1215                 }
1216             };
1217 
1218     private final PropertyInvalidatedCache<Integer, Boolean> mInteractiveCache =
1219             new PropertyInvalidatedCache<>(getCacheArgs(CACHE_KEY_IS_INTERACTIVE_API),
1220                     CACHE_KEY_IS_INTERACTIVE_API, null) {
1221                 @Override
1222                 public Boolean recompute(Integer displayId) {
1223                     try {
1224                         if (displayId == null) {
1225                             return mService.isInteractive();
1226                         } else {
1227                             return mService.isDisplayInteractive(displayId);
1228                         }
1229                     } catch (RemoteException e) {
1230                         throw e.rethrowFromSystemServer();
1231                     }
1232                 }
1233             };
1234 
1235     final Context mContext;
1236     @UnsupportedAppUsage
1237     final IPowerManager mService;
1238     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1239     final Handler mHandler;
1240     final IThermalService mThermalService;
1241 
1242     /** We lazily initialize it.*/
1243     private PowerExemptionManager mPowerExemptionManager;
1244 
1245     @GuardedBy("mThermalStatusListenerMap")
1246     private final ArrayMap<OnThermalStatusChangedListener, IThermalStatusListener>
1247             mThermalStatusListenerMap = new ArrayMap<>();
1248     @GuardedBy("mThermalHeadroomListenerMap")
1249     private final ArrayMap<OnThermalHeadroomChangedListener, IThermalHeadroomListener>
1250             mThermalHeadroomListenerMap = new ArrayMap<>();
1251 
1252     private final ArrayMap<ScreenTimeoutPolicyListener, IScreenTimeoutPolicyListener>
1253             mScreenTimeoutPolicyListeners = new ArrayMap<>();
1254 
1255     /**
1256      * {@hide}
1257      */
PowerManager(Context context, IPowerManager service, IThermalService thermalService, Handler handler)1258     public PowerManager(Context context, IPowerManager service, IThermalService thermalService,
1259             Handler handler) {
1260         mContext = context;
1261         mService = service;
1262         mThermalService = thermalService;
1263         mHandler = handler;
1264     }
1265 
getPowerExemptionManager()1266     private PowerExemptionManager getPowerExemptionManager() {
1267         if (mPowerExemptionManager == null) {
1268             // No need for synchronization; getSystemService() will return the same object anyway.
1269             mPowerExemptionManager = mContext.getSystemService(PowerExemptionManager.class);
1270         }
1271         return mPowerExemptionManager;
1272     }
1273 
1274     /**
1275      * Gets the minimum supported screen brightness setting.
1276      * The screen may be allowed to become dimmer than this value but
1277      * this is the minimum value that can be set by the user.
1278      * @hide
1279      */
1280     @UnsupportedAppUsage
getMinimumScreenBrightnessSetting()1281     public int getMinimumScreenBrightnessSetting() {
1282         return mContext.getResources().getInteger(
1283                 com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
1284     }
1285 
1286     /**
1287      * Gets the maximum supported screen brightness setting.
1288      * The screen may be allowed to become dimmer than this value but
1289      * this is the maximum value that can be set by the user.
1290      * @hide
1291      */
1292     @UnsupportedAppUsage
getMaximumScreenBrightnessSetting()1293     public int getMaximumScreenBrightnessSetting() {
1294         return mContext.getResources().getInteger(
1295                 com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
1296     }
1297 
1298     /**
1299      * Gets the default screen brightness setting.
1300      * @hide
1301      */
1302     @UnsupportedAppUsage
getDefaultScreenBrightnessSetting()1303     public int getDefaultScreenBrightnessSetting() {
1304         return mContext.getResources().getInteger(
1305                 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
1306     }
1307 
1308     /**
1309      * Gets a float screen brightness setting.
1310      * @hide
1311      */
1312     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getBrightnessConstraint(@rightnessConstraint int constraint)1313     public float getBrightnessConstraint(@BrightnessConstraint int constraint) {
1314         return getBrightnessConstraint(Display.DEFAULT_DISPLAY, constraint);
1315     }
1316 
1317     /**
1318      * Gets a float screen brightness setting for a specific display.
1319      * @hide
1320      */
getBrightnessConstraint(int displayId, @BrightnessConstraint int constraint)1321     public float getBrightnessConstraint(int displayId, @BrightnessConstraint int constraint) {
1322         try {
1323             return mService.getBrightnessConstraint(displayId, constraint);
1324         } catch (RemoteException e) {
1325             throw e.rethrowFromSystemServer();
1326         }
1327     }
1328 
1329     /**
1330      * Creates a new wake lock with the specified level and flags.
1331      * <p>
1332      * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
1333      * combined using the logical OR operator.
1334      * </p><p>
1335      * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
1336      * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
1337      * and {@link #SCREEN_BRIGHT_WAKE_LOCK}.  Exactly one wake lock level must be
1338      * specified as part of the {@code levelAndFlags} parameter.
1339      * </p>
1340      * <p>
1341      * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
1342      * and {@link #ON_AFTER_RELEASE}.  Multiple flags can be combined as part of the
1343      * {@code levelAndFlags} parameters.
1344      * </p><p>
1345      * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
1346      * wake lock, and {@link WakeLock#release release()} when you are done.
1347      * </p><p>
1348      * {@samplecode
1349      * PowerManager pm = mContext.getSystemService(PowerManager.class);
1350      * PowerManager.WakeLock wl = pm.newWakeLock(
1351      *                                      PowerManager.SCREEN_DIM_WAKE_LOCK
1352      *                                      | PowerManager.ON_AFTER_RELEASE,
1353      *                                      TAG);
1354      * wl.acquire();
1355      * // ... do work...
1356      * wl.release();
1357      * }
1358      * </p><p>
1359      * Although a wake lock can be created without special permissions,
1360      * the {@link android.Manifest.permission#WAKE_LOCK} permission is
1361      * required to actually acquire or release the wake lock that is returned.
1362      *
1363      * </p><p>
1364      * <b>Device battery life will be significantly affected by the use of this API.</b>
1365      * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
1366      * possible, and be sure to release them as soon as possible.
1367      * </p><p class="note">
1368      * If using this to keep the screen on, you should strongly consider using
1369      * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
1370      * This window flag will be correctly managed by the platform
1371      * as the user moves between applications and doesn't require a special permission.
1372      * Additionally using the flag will keep only the appropriate screen on in a
1373      * multi-display scenario while using a wake lock will keep every screen powered on.
1374      * </p>
1375      *
1376      * <p>
1377      * Recommended naming conventions for tags to make debugging easier:
1378      * <ul>
1379      * <li>use a unique prefix delimited by a colon for your app/library (e.g.
1380      * gmail:mytag) to make it easier to understand where the wake locks comes
1381      * from. This namespace will also avoid collision for tags inside your app
1382      * coming from different libraries which will make debugging easier.
1383      * <li>use constants (e.g. do not include timestamps in the tag) to make it
1384      * easier for tools to aggregate similar wake locks. When collecting
1385      * debugging data, the platform only monitors a finite number of tags,
1386      * using constants will help tools to provide better debugging data.
1387      * <li>avoid using Class#getName() or similar method since this class name
1388      * can be transformed by java optimizer and obfuscator tools.
1389      * <li>avoid wrapping the tag or a prefix to avoid collision with wake lock
1390      * tags from the platform (e.g. *alarm*).
1391      * <li>never include personally identifiable information for privacy
1392      * reasons.
1393      * </ul>
1394      * </p>
1395      *
1396      * @param levelAndFlags Combination of wake lock level and flag values defining
1397      * the requested behavior of the WakeLock.
1398      * @param tag Your class name (or other tag) for debugging purposes.
1399      *
1400      * @see WakeLock#acquire()
1401      * @see WakeLock#release()
1402      * @see #PARTIAL_WAKE_LOCK
1403      * @see #FULL_WAKE_LOCK
1404      * @see #SCREEN_DIM_WAKE_LOCK
1405      * @see #SCREEN_BRIGHT_WAKE_LOCK
1406      * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
1407      * @see #ACQUIRE_CAUSES_WAKEUP
1408      * @see #ON_AFTER_RELEASE
1409      */
newWakeLock(int levelAndFlags, String tag)1410     public WakeLock newWakeLock(int levelAndFlags, String tag) {
1411         if (android.companion.virtualdevice.flags.Flags.displayPowerManagerApis()) {
1412             return newWakeLock(levelAndFlags, tag, mContext.getDisplayId());
1413         }
1414         validateWakeLockParameters(levelAndFlags, tag);
1415         return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName(),
1416                 Display.INVALID_DISPLAY);
1417     }
1418 
1419     /**
1420      * Creates a new wake lock with the specified level and flags.
1421      * <p>
1422      * The wakelock will only apply to the {@link com.android.server.display.DisplayGroup} of the
1423      * provided {@code displayId}. If {@code displayId} is {@link Display#INVALID_DISPLAY} then it
1424      * will apply to all {@link com.android.server.display.DisplayGroup DisplayGroups}.
1425      *
1426      * @param levelAndFlags Combination of wake lock level and flag values defining
1427      * the requested behavior of the WakeLock.
1428      * @param tag Your class name (or other tag) for debugging purposes.
1429      * @param displayId The display id to which this wake lock is tied.
1430      *
1431      * @hide
1432      */
newWakeLock(int levelAndFlags, String tag, int displayId)1433     public WakeLock newWakeLock(int levelAndFlags, String tag, int displayId) {
1434         validateWakeLockParameters(levelAndFlags, tag);
1435         return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName(), displayId);
1436     }
1437 
1438     /** @hide */
1439     @UnsupportedAppUsage
validateWakeLockParameters(int levelAndFlags, String tag)1440     public static void validateWakeLockParameters(int levelAndFlags, String tag) {
1441         switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
1442             case PARTIAL_WAKE_LOCK:
1443             case SCREEN_DIM_WAKE_LOCK:
1444             case SCREEN_BRIGHT_WAKE_LOCK:
1445             case FULL_WAKE_LOCK:
1446             case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1447             case DOZE_WAKE_LOCK:
1448             case DRAW_WAKE_LOCK:
1449             case SCREEN_TIMEOUT_OVERRIDE_WAKE_LOCK:
1450                 break;
1451             default:
1452                 throw new IllegalArgumentException("Must specify a valid wake lock level.");
1453         }
1454         if (tag == null) {
1455             throw new IllegalArgumentException("The tag must not be null.");
1456         }
1457     }
1458 
1459     /**
1460      * Notifies the power manager that user activity happened.
1461      * <p>
1462      * Resets the auto-off timer and brightens the screen if the device
1463      * is not asleep.  This is what happens normally when a key or the touch
1464      * screen is pressed or when some other user activity occurs.
1465      * This method does not wake up the device if it has been put to sleep.
1466      * </p><p>
1467      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1468      * </p>
1469      *
1470      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
1471      * time base.  This timestamp is used to correctly order the user activity request with
1472      * other power management functions.  It should be set
1473      * to the timestamp of the input event that caused the user activity.
1474      * @param noChangeLights If true, does not cause the keyboard backlight to turn on
1475      * because of this event.  This is set when the power key is pressed.
1476      * We want the device to stay on while the button is down, but we're about
1477      * to turn off the screen so we don't want the keyboard backlight to turn on again.
1478      * Otherwise the lights flash on and then off and it looks weird.
1479      *
1480      * @see #wakeUp
1481      * @see #goToSleep
1482      *
1483      * @removed Requires signature or system permission.
1484      * @deprecated Use {@link #userActivity(long, int, int)}.
1485      */
1486     @Deprecated
userActivity(long when, boolean noChangeLights)1487     public void userActivity(long when, boolean noChangeLights) {
1488         userActivity(when, USER_ACTIVITY_EVENT_OTHER,
1489                 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
1490     }
1491 
1492     /**
1493      * Notifies the power manager that user activity happened.
1494      * <p>
1495      * Resets the auto-off timer and brightens the screen if the device
1496      * is not asleep.  This is what happens normally when a key or the touch
1497      * screen is pressed or when some other user activity occurs.
1498      * This method does not wake up the device if it has been put to sleep.
1499      * </p><p>
1500      * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
1501      * {@link android.Manifest.permission#USER_ACTIVITY} permission.
1502      * </p>
1503      *
1504      * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
1505      * time base.  This timestamp is used to correctly order the user activity request with
1506      * other power management functions.  It should be set
1507      * to the timestamp of the input event that caused the user activity.
1508      * @param event The user activity event.
1509      * @param flags Optional user activity flags.
1510      *
1511      * @see #wakeUp
1512      * @see #goToSleep
1513      *
1514      * @hide Requires signature or system permission.
1515      */
1516     @SystemApi
1517     @RequiresPermission(anyOf = {
1518             android.Manifest.permission.DEVICE_POWER,
1519             android.Manifest.permission.USER_ACTIVITY
1520     })
userActivity(long when, int event, int flags)1521     public void userActivity(long when, int event, int flags) {
1522         try {
1523             mService.userActivity(mContext.getDisplayId(), when, event, flags);
1524         } catch (RemoteException e) {
1525             throw e.rethrowFromSystemServer();
1526         }
1527     }
1528 
1529     /**
1530      * Forces the {@link android.view.Display#DEFAULT_DISPLAY_GROUP default display group}
1531      * to turn off.
1532      *
1533      * <p>If the {@link android.view.Display#DEFAULT_DISPLAY_GROUP default display group} is
1534      * turned on it will be turned off. If all displays are off as a result of this action the
1535      * device will be put to sleep. If the {@link android.view.Display#DEFAULT_DISPLAY_GROUP
1536      * default display group} is already off then nothing will happen.
1537      *
1538      * <p>If the device is an Android TV playback device and the current active source on the
1539      * HDMI-connected TV, it will attempt to turn off that TV via HDMI-CEC.
1540      *
1541      * <p>
1542      * Overrides all the wake locks that are held.
1543      * This is what happens when the power key is pressed to turn off the screen.
1544      * </p><p>
1545      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1546      * </p>
1547      *
1548      * @param time The time when the request to go to sleep was issued, in the
1549      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1550      * order the go to sleep request with other power management functions.  It should be set
1551      * to the timestamp of the input event that caused the request to go to sleep.
1552      *
1553      * @see #userActivity
1554      * @see #wakeUp
1555      *
1556      * @removed Requires signature permission.
1557      */
goToSleep(long time)1558     public void goToSleep(long time) {
1559         goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
1560     }
1561 
1562     /**
1563      * Forces the {@link android.view.Display#DEFAULT_DISPLAY_GROUP default display group}
1564      * to turn off.
1565      *
1566      * <p>If the {@link android.view.Display#DEFAULT_DISPLAY_GROUP default display group} is
1567      * turned on it will be turned off. If all displays are off as a result of this action the
1568      * device will be put to sleep. If the {@link android.view.Display#DEFAULT_DISPLAY_GROUP
1569      * default display group} is already off then nothing will happen.
1570      *
1571      * <p>
1572      * Overrides all the wake locks that are held.
1573      * This is what happens when the power key is pressed to turn off the screen.
1574      * </p><p>
1575      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1576      * </p>
1577      *
1578      * @param time The time when the request to go to sleep was issued, in the
1579      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1580      * order the go to sleep request with other power management functions.  It should be set
1581      * to the timestamp of the input event that caused the request to go to sleep.
1582      * @param reason The reason the device is going to sleep.
1583      * @param flags Optional flags to apply when going to sleep.
1584      *
1585      * @see #userActivity
1586      * @see #wakeUp
1587      *
1588      * @hide Requires signature permission.
1589      */
1590     @UnsupportedAppUsage
goToSleep(long time, int reason, int flags)1591     public void goToSleep(long time, int reason, int flags) {
1592         try {
1593             mService.goToSleep(time, reason, flags);
1594         } catch (RemoteException e) {
1595             throw e.rethrowFromSystemServer();
1596         }
1597     }
1598 
1599     /**
1600      * Forces the {@link com.android.server.display.DisplayGroup} of the provided {@code displayId}
1601      * to turn off.
1602      *
1603      * <p>If the {@link com.android.server.display.DisplayGroup} of the provided {@code displayId}
1604      * is turned on it will be turned off. If all displays are off as a result of this action the
1605      * device will be put to sleep. If the {@link com.android.server.display.DisplayGroup} of
1606      * the provided {@code displayId} is already off then nothing will happen.
1607      *
1608      * <p>Overrides all the wake locks that are held.
1609      * This is what happens when the power key is pressed to turn off the screen.
1610      *
1611      * <p>Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1612      *
1613      * @param displayId The display ID to turn off. If {@code displayId} is
1614      * {@link Display#INVALID_DISPLAY}, then all displays are turned off.
1615      * @param time The time when the request to go to sleep was issued, in the
1616      * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1617      * order the go to sleep request with other power management functions.  It should be set
1618      * to the timestamp of the input event that caused the request to go to sleep.
1619      * @param reason The reason the device is going to sleep.
1620      * @param flags Optional flags to apply when going to sleep.
1621      *
1622      * @see #userActivity
1623      * @see #wakeUp
1624      *
1625      * @hide Requires signature permission.
1626      */
1627     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
goToSleep(int displayId, long time, @GoToSleepReason int reason, int flags)1628     public void goToSleep(int displayId, long time, @GoToSleepReason int reason, int flags) {
1629         try {
1630             mService.goToSleepWithDisplayId(displayId, time, reason, flags);
1631         } catch (RemoteException e) {
1632             throw e.rethrowFromSystemServer();
1633         }
1634     }
1635 
1636     /**
1637      * Forces the {@link android.view.Display#DEFAULT_DISPLAY default display} to turn on.
1638      *
1639      * @see #wakeUp(long, int, String, int)
1640      *
1641      * @deprecated Use {@link #wakeUp(long, int, String)} instead.
1642      * @removed Requires signature permission.
1643      */
1644     @Deprecated
wakeUp(long time)1645     public void wakeUp(long time) {
1646         wakeUp(time, WAKE_REASON_UNKNOWN, "wakeUp");
1647     }
1648 
1649     /**
1650      * Forces the {@link android.view.Display#DEFAULT_DISPLAY default display} to turn on.
1651      *
1652      * @see #wakeUp(long, int, String, int)
1653      *
1654      * @deprecated Use {@link #wakeUp(long, int, String)} instead.
1655      * @hide
1656      */
1657     @UnsupportedAppUsage
1658     @Deprecated
wakeUp(long time, String details)1659     public void wakeUp(long time, String details) {
1660         wakeUp(time, WAKE_REASON_UNKNOWN, details);
1661     }
1662 
1663     /**
1664      * Forces the {@link android.view.Display#DEFAULT_DISPLAY default display} to turn on.
1665      *
1666      * @see #wakeUp(long, int, String, int)
1667      * @hide
1668      */
wakeUp(long time, @WakeReason int reason, String details)1669     public void wakeUp(long time, @WakeReason int reason, String details) {
1670         try {
1671             mService.wakeUp(time, reason, details, mContext.getOpPackageName());
1672         } catch (RemoteException e) {
1673             throw e.rethrowFromSystemServer();
1674         }
1675     }
1676 
1677     /**
1678      * Forces the display with the supplied displayId to turn on.
1679      *
1680      * <p>If the corresponding display is turned off, it will be turned on. Additionally, if the
1681      * device is asleep it will be awoken. If the corresponding display is already on then nothing
1682      * will happen. If the corresponding display does not exist, then nothing will happen.
1683      *
1684      * <p>If the device is an Android TV playback device, it will attempt to turn on the
1685      * HDMI-connected TV and become the current active source via the HDMI-CEC One Touch Play
1686      * feature.
1687      *
1688      * <p>
1689      * This is what happens when the power key is pressed to turn on the screen.
1690      * </p><p>
1691      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1692      * </p>
1693      *
1694      * @param time The time when the request to wake up was issued, in the
1695      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1696      * order the wake up request with other power management functions.  It should be set
1697      * to the timestamp of the input event that caused the request to wake up.
1698      *
1699      * @param reason The reason for the wake up.
1700      *
1701      * @param details A free form string to explain the specific details behind the wake up for
1702      *                debugging purposes.
1703      * @param displayId The displayId of the display to be woken up.
1704      *
1705      * @see #userActivity
1706      * @see #goToSleep
1707      * @hide
1708      */
wakeUp(long time, @WakeReason int reason, String details, int displayId)1709     public void wakeUp(long time, @WakeReason int reason, String details, int displayId) {
1710         try {
1711             mService.wakeUpWithDisplayId(time, reason, details, mContext.getOpPackageName(),
1712                     displayId);
1713         } catch (RemoteException e) {
1714             throw e.rethrowFromSystemServer();
1715         }
1716     }
1717 
1718     /**
1719      * Forces the device to start napping.
1720      * <p>
1721      * If the device is currently awake, starts dreaming, otherwise does nothing.
1722      * When the dream ends or if the dream cannot be started, the device will
1723      * either wake up or go to sleep depending on whether there has been recent
1724      * user activity.
1725      * </p><p>
1726      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1727      * </p>
1728      *
1729      * @param time The time when the request to nap was issued, in the
1730      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1731      * order the nap request with other power management functions.  It should be set
1732      * to the timestamp of the input event that caused the request to nap.
1733      *
1734      * @see #wakeUp
1735      * @see #goToSleep
1736      *
1737      * @hide Requires signature permission.
1738      */
nap(long time)1739     public void nap(long time) {
1740         try {
1741             mService.nap(time);
1742         } catch (RemoteException e) {
1743             throw e.rethrowFromSystemServer();
1744         }
1745     }
1746 
1747     /**
1748      * Requests the device to start dreaming.
1749      * <p>
1750      * If dream can not be started, for example if another {@link PowerManager} transition is in
1751      * progress, does nothing. Unlike {@link #nap(long)}, this does not put device to sleep when
1752      * dream ends.
1753      * </p><p>
1754      * Requires the {@link android.Manifest.permission#READ_DREAM_STATE} and
1755      * {@link android.Manifest.permission#WRITE_DREAM_STATE} permissions.
1756      * </p>
1757      *
1758      * @param time The time when the request to nap was issued, in the
1759      * {@link SystemClock#uptimeMillis()} time base.  This timestamp may be used to correctly
1760      * order the dream request with other power management functions.  It should be set
1761      * to the timestamp of the input event that caused the request to dream.
1762      *
1763      * @hide
1764      */
1765     @SystemApi
1766     @RequiresPermission(allOf = {
1767             android.Manifest.permission.READ_DREAM_STATE,
1768             android.Manifest.permission.WRITE_DREAM_STATE })
dream(long time)1769     public void dream(long time) {
1770         Sandman.startDreamByUserRequest(mContext);
1771     }
1772 
1773     /**
1774      * Boosts the brightness of the screen to maximum for a predetermined
1775      * period of time.  This is used to make the screen more readable in bright
1776      * daylight for a short duration.
1777      * <p>
1778      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1779      * </p>
1780      *
1781      * @param time The time when the request to boost was issued, in the
1782      * {@link SystemClock#uptimeMillis()} time base.  This timestamp is used to correctly
1783      * order the boost request with other power management functions.  It should be set
1784      * to the timestamp of the input event that caused the request to boost.
1785      *
1786      * @hide Requires signature permission.
1787      */
boostScreenBrightness(long time)1788     public void boostScreenBrightness(long time) {
1789         try {
1790             mService.boostScreenBrightness(time);
1791         } catch (RemoteException e) {
1792             throw e.rethrowFromSystemServer();
1793         }
1794     }
1795 
1796     /**
1797      * Adds a listener to be notified about changes in screen timeout policy.
1798      *
1799      * <p>The screen timeout policy determines the behavior of the device's screen
1800      * after a period of inactivity. It can be used to understand if the display is going
1801      * to be turned off after a timeout to conserve power, or if it will be kept on indefinitely.
1802      * For example, it might be useful for adjusting display switch conditions on foldable
1803      * devices based on the current timeout policy.
1804      *
1805      * <p>See {@link ScreenTimeoutPolicy} for possible values.
1806      *
1807      * <p>The listener will be fired with the initial state upon subscribing.
1808      *
1809      * <p>IScreenTimeoutPolicyListener is called on either system server's main thread or
1810      * on a binder thread if subscribed outside the system service process.
1811      *
1812      * @param displayId display id for which to be notified about screen timeout policy changes
1813      * @param executor executor on which to execute ScreenTimeoutPolicyListener methods
1814      * @param listener listener that will be fired on screem timeout policy updates
1815      * @hide
1816      */
1817     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
addScreenTimeoutPolicyListener(int displayId, @NonNull @CallbackExecutor Executor executor, @NonNull ScreenTimeoutPolicyListener listener)1818     public void addScreenTimeoutPolicyListener(int displayId,
1819             @NonNull @CallbackExecutor Executor executor,
1820             @NonNull ScreenTimeoutPolicyListener listener) {
1821         Objects.requireNonNull(listener, "listener cannot be null");
1822         Objects.requireNonNull(executor, "executor cannot be null");
1823         Preconditions.checkArgument(!mScreenTimeoutPolicyListeners.containsKey(listener),
1824                 "Listener already registered: %s", listener);
1825 
1826         final IScreenTimeoutPolicyListener stub = new IScreenTimeoutPolicyListener.Stub() {
1827             public void onScreenTimeoutPolicyChanged(int screenTimeoutPolicy) {
1828                 final long token = Binder.clearCallingIdentity();
1829                 try {
1830                     executor.execute(() ->
1831                             listener.onScreenTimeoutPolicyChanged(screenTimeoutPolicy));
1832                 } finally {
1833                     Binder.restoreCallingIdentity(token);
1834                 }
1835             }
1836         };
1837 
1838         try {
1839             mService.addScreenTimeoutPolicyListener(displayId, stub);
1840             mScreenTimeoutPolicyListeners.put(listener, stub);
1841         } catch (RemoteException e) {
1842             throw e.rethrowFromSystemServer();
1843         }
1844     }
1845 
1846     /**
1847      * Removes a listener that is used to listen for screen timeout policy changes.
1848      * @see PowerManager#addScreenTimeoutPolicyListener(int, ScreenTimeoutPolicyListener)
1849      * @param displayId display id for which to be notified about screen timeout changes
1850      * @hide
1851      */
1852     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
removeScreenTimeoutPolicyListener(int displayId, @NonNull ScreenTimeoutPolicyListener listener)1853     public void removeScreenTimeoutPolicyListener(int displayId,
1854             @NonNull ScreenTimeoutPolicyListener listener) {
1855         Objects.requireNonNull(listener, "listener cannot be null");
1856         IScreenTimeoutPolicyListener internalListener = mScreenTimeoutPolicyListeners.get(listener);
1857         Preconditions.checkArgument(internalListener != null, "Listener was not added");
1858 
1859         try {
1860             mService.removeScreenTimeoutPolicyListener(displayId, internalListener);
1861             mScreenTimeoutPolicyListeners.remove(listener);
1862         } catch (RemoteException e) {
1863             throw e.rethrowFromSystemServer();
1864         }
1865     }
1866 
1867    /**
1868      * Returns true if the specified wake lock level is supported.
1869      *
1870      * @param level The wake lock level to check.
1871      * @return True if the specified wake lock level is supported.
1872      */
isWakeLockLevelSupported(int level)1873     public boolean isWakeLockLevelSupported(int level) {
1874         try {
1875             if (android.companion.virtualdevice.flags.Flags.displayPowerManagerApis()) {
1876                 return mService.isWakeLockLevelSupportedWithDisplayId(
1877                         level, mContext.getDisplayId());
1878             }
1879             return mService.isWakeLockLevelSupported(level);
1880         } catch (RemoteException e) {
1881             throw e.rethrowFromSystemServer();
1882         }
1883     }
1884 
1885     /**
1886       * Returns true if the device is in an interactive state.
1887       * <p>
1888       * For historical reasons, the name of this method refers to the power state of
1889       * the screen but it actually describes the overall interactive state of
1890       * the device.  This method has been replaced by {@link #isInteractive}.
1891       * </p><p>
1892       * The value returned by this method only indicates whether the device is
1893       * in an interactive state which may have nothing to do with the screen being
1894       * on or off.  To determine the actual state of the screen,
1895       * use {@link android.view.Display#getState}.
1896       * </p>
1897       *
1898       * @return True if the device is in an interactive state.
1899       *
1900       * @deprecated Use {@link #isInteractive} instead.
1901       */
1902     @Deprecated
isScreenOn()1903     public boolean isScreenOn() {
1904         return isInteractive();
1905     }
1906 
1907     /**
1908      * Returns true if the device is in an interactive state.
1909      * <p>
1910      * When this method returns true, the device is awake and ready to interact
1911      * with the user (although this is not a guarantee that the user is actively
1912      * interacting with the device just this moment).  The main screen is usually
1913      * turned on while in this state.  Certain features, such as the proximity
1914      * sensor, may temporarily turn off the screen while still leaving the device in an
1915      * interactive state.  Note in particular that the device is still considered
1916      * to be interactive while dreaming (since dreams can be interactive) but not
1917      * when it is dozing or asleep.
1918      * </p><p>
1919      * When this method returns false, the device is dozing or asleep and must
1920      * be awoken before it will become ready to interact with the user again.  The
1921      * main screen is usually turned off while in this state.  Certain features,
1922      * such as "ambient mode" may cause the main screen to remain on (albeit in a
1923      * low power state) to display system-provided content while the device dozes.
1924      * </p><p>
1925      * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
1926      * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
1927      * whenever the interactive state of the device changes.  For historical reasons,
1928      * the names of these broadcasts refer to the power state of the screen
1929      * but they are actually sent in response to changes in the overall interactive
1930      * state of the device, as described by this method.
1931      * </p><p>
1932      * Services may use the non-interactive state as a hint to conserve power
1933      * since the user is not present.
1934      * </p>
1935      *
1936      * @return True if the device is in an interactive state.
1937      *
1938      * @see android.content.Intent#ACTION_SCREEN_ON
1939      * @see android.content.Intent#ACTION_SCREEN_OFF
1940      */
isInteractive()1941     public boolean isInteractive() {
1942         if (android.companion.virtualdevice.flags.Flags.displayPowerManagerApis()) {
1943             return isInteractive(mContext.getDisplayId());
1944         }
1945         return mInteractiveCache.query(null);
1946     }
1947 
1948     /**
1949      * Returns true if the specified display is in an interactive state. This may not be the
1950      * same as the global wakefulness (which is true when any display is interactive).
1951      * @see #isInteractive()
1952      *
1953      * @param displayId The Display ID to check for interactivity.
1954      * @return True if the display is in an interactive state.
1955      *
1956      * @hide
1957      */
1958     @TestApi
isInteractive(int displayId)1959     public boolean isInteractive(int displayId) {
1960         return mInteractiveCache.query(displayId);
1961     }
1962 
1963     /**
1964      * Returns {@code true} if this device supports rebooting userspace.
1965      *
1966      * <p>This method exists solely for the sake of re-using same logic between {@code PowerManager}
1967      * and {@code PowerManagerService}.
1968      *
1969      * @deprecated TODO(b/292469129): remove this method.
1970      * @hide
1971      */
isRebootingUserspaceSupportedImpl()1972     public static boolean isRebootingUserspaceSupportedImpl() {
1973         return false;
1974     }
1975 
1976     /**
1977      * Returns {@code true} if this device supports rebooting userspace.
1978      *
1979      * @deprecated userspace reboot is deprecated, this method always returns {@code false}.
1980      */
isRebootingUserspaceSupported()1981     public boolean isRebootingUserspaceSupported() {
1982         return isRebootingUserspaceSupportedImpl();
1983     }
1984 
1985     /**
1986      * Reboot the device.  Will not return if the reboot is successful.
1987      * <p>
1988      * Requires the {@link android.Manifest.permission#REBOOT} permission.
1989      * </p>
1990      * <p>
1991      * If the {@code reason} string contains ",quiescent", then the screen stays off during reboot
1992      * and is not turned on again until the user triggers the device to wake up (for example,
1993      * by pressing the power key).
1994      * This behavior applies to Android TV devices launched on Android 11 (API level 30) or higher.
1995      * </p>
1996      *
1997      * @param reason code to pass to the kernel (e.g., "recovery") to
1998      *               request special boot modes, or null.
1999      * @throws UnsupportedOperationException if userspace reboot was requested on a device that
2000      *                                       doesn't support it.
2001      */
2002     @RequiresPermission(permission.REBOOT)
reboot(@ullable String reason)2003     public void reboot(@Nullable String reason) {
2004         if (REBOOT_USERSPACE.equals(reason) && !isRebootingUserspaceSupported()) {
2005             throw new UnsupportedOperationException(
2006                     "Attempted userspace reboot on a device that doesn't support it");
2007         }
2008         try {
2009             mService.reboot(false, reason, true);
2010         } catch (RemoteException e) {
2011             throw e.rethrowFromSystemServer();
2012         }
2013     }
2014 
2015     /**
2016      * Reboot the device. Will not return if the reboot is successful.
2017      * <p>
2018      * Requires the {@link android.Manifest.permission#REBOOT} permission.
2019      * </p>
2020      * @hide
2021      */
2022     @RequiresPermission(permission.REBOOT)
rebootSafeMode()2023     public void rebootSafeMode() {
2024         try {
2025             mService.rebootSafeMode(false, true);
2026         } catch (RemoteException e) {
2027             throw e.rethrowFromSystemServer();
2028         }
2029     }
2030 
2031     /**
2032      * Returns true if the platform has auto power save modes (eg. Doze & app standby) enabled.
2033      * This doesn't necessarily mean that the individual features are enabled. For example, if this
2034      * returns true, Doze might be enabled while app standby buckets remain disabled.
2035      * @hide
2036      */
2037     @TestApi
areAutoPowerSaveModesEnabled()2038     public boolean areAutoPowerSaveModesEnabled() {
2039         try {
2040             return mService.areAutoPowerSaveModesEnabled();
2041         } catch (RemoteException e) {
2042             throw e.rethrowFromSystemServer();
2043         }
2044     }
2045 
2046     /**
2047      * Returns true if the device is currently in power save mode.  When in this mode,
2048      * applications should reduce their functionality in order to conserve battery as
2049      * much as possible.  You can monitor for changes to this state with
2050      * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
2051      *
2052      * @return Returns true if currently in low power mode, else false.
2053      */
isPowerSaveMode()2054     public boolean isPowerSaveMode() {
2055         return mPowerSaveModeCache.query(null);
2056     }
2057 
2058     /**
2059      * Set the current power save mode.
2060      *
2061      * @return True if the set was allowed.
2062      *
2063      * @hide
2064      * @see #isPowerSaveMode()
2065      */
2066     @SystemApi
2067     @RequiresPermission(anyOf = {
2068             android.Manifest.permission.DEVICE_POWER,
2069             android.Manifest.permission.POWER_SAVER
2070     })
setPowerSaveModeEnabled(boolean mode)2071     public boolean setPowerSaveModeEnabled(boolean mode) {
2072         try {
2073             return mService.setPowerSaveModeEnabled(mode);
2074         } catch (RemoteException e) {
2075             throw e.rethrowFromSystemServer();
2076         }
2077     }
2078 
2079     /**
2080      * Returns true if Battery Saver is supported on this device.
2081      *
2082      * @hide
2083      */
2084     @FlaggedApi(android.os.Flags.FLAG_BATTERY_SAVER_SUPPORTED_CHECK_API)
2085     @TestApi
isBatterySaverSupported()2086     public boolean isBatterySaverSupported() {
2087         try {
2088             return mService.isBatterySaverSupported();
2089         } catch (RemoteException e) {
2090             throw e.rethrowFromSystemServer();
2091         }
2092     }
2093 
2094     /**
2095      * Gets the current policy for full power save mode.
2096      *
2097      * @return The {@link BatterySaverPolicyConfig} which is currently set for the full power save
2098      *          policy level.
2099      *
2100      * @hide
2101      */
2102     @SystemApi
2103     @NonNull
getFullPowerSavePolicy()2104     public BatterySaverPolicyConfig getFullPowerSavePolicy() {
2105         try {
2106             return mService.getFullPowerSavePolicy();
2107         } catch (RemoteException e) {
2108             throw e.rethrowFromSystemServer();
2109         }
2110     }
2111 
2112     /**
2113      * Sets the policy for full power save mode.
2114      *
2115      * Any settings set by this API will persist for only one session of full battery saver mode.
2116      * The settings set by this API are cleared upon exit of full battery saver mode, and the
2117      * caller is expected to set the desired values again for the next full battery saver mode
2118      * session if desired.
2119      *
2120      * Use-cases:
2121      * 1. Set policy outside of full battery saver mode
2122      *     - full policy set -> enter BS -> policy setting applied -> exit BS -> setting cleared
2123      * 2. Set policy inside of full battery saver mode
2124      *     - enter BS -> full policy set -> policy setting applied -> exit BS -> setting cleared
2125      *
2126      * This API is intended to be used with {@link #getFullPowerSavePolicy()} API when a client only
2127      * wants to modify a specific setting(s) and leave the remaining policy attributes the same.
2128      * Example:
2129      * BatterySaverPolicyConfig newFullPolicyConfig =
2130      *     new BatterySaverPolicyConfig.Builder(powerManager.getFullPowerSavePolicy())
2131      *         .setSoundTriggerMode(PowerManager.SOUND_TRIGGER_MODE_ALL_DISABLED)
2132      *         .build();
2133      * powerManager.setFullPowerSavePolicy(newFullPolicyConfig);
2134      *
2135      * @return true if there was an effectual change. If full battery saver is enabled, then this
2136      * will return true.
2137      *
2138      * @hide
2139      */
2140     @SystemApi
2141     @RequiresPermission(anyOf = {
2142             android.Manifest.permission.DEVICE_POWER,
2143             android.Manifest.permission.POWER_SAVER
2144     })
setFullPowerSavePolicy(@onNull BatterySaverPolicyConfig config)2145     public boolean setFullPowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
2146         try {
2147             return mService.setFullPowerSavePolicy(config);
2148         } catch (RemoteException e) {
2149             throw e.rethrowFromSystemServer();
2150         }
2151     }
2152 
2153     /**
2154      * Updates the current state of dynamic power savings and disable threshold. This is
2155      * a signal to the system which an app can update to serve as an indicator that
2156      * the user will be in a battery critical situation before being able to plug in.
2157      * Only apps with the {@link android.Manifest.permission#POWER_SAVER} permission may do this.
2158      * This is a device global state, not a per user setting.
2159      *
2160      * <p>When enabled, the system may enact various measures for reducing power consumption in
2161      * order to help ensure that the user will make it to their next charging point. The most
2162      * visible of these will be the automatic enabling of battery saver if the user has set
2163      * their battery saver mode to "automatic". Note
2164      * that this is NOT simply an on/off switch for features, but rather a hint for the
2165      * system to consider enacting these power saving features, some of which have additional
2166      * logic around when to activate based on this signal.
2167      *
2168      * <p>The provided threshold is the percentage the system should consider itself safe at given
2169      * the current state of the device. The value is an integer representing a battery level.
2170      *
2171      * <p>The threshold is meant to set an explicit stopping point for dynamic power savings
2172      * functionality so that the dynamic power savings itself remains a signal rather than becoming
2173      * an on/off switch for a subset of features.
2174      * @hide
2175      *
2176      * @param powerSaveHint A signal indicating to the system if it believes the
2177      * dynamic power savings behaviors should be activated.
2178      * @param disableThreshold When the suggesting app believes it would be safe to disable dynamic
2179      * power savings behaviors.
2180      * @return True if the update was allowed and succeeded.
2181      *
2182      * @hide
2183      */
2184     @SystemApi
2185     @RequiresPermission(permission.POWER_SAVER)
setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold)2186     public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
2187         try {
2188             return mService.setDynamicPowerSaveHint(powerSaveHint, disableThreshold);
2189         } catch (RemoteException e) {
2190             throw e.rethrowFromSystemServer();
2191         }
2192     }
2193 
2194     /**
2195      * Sets the policy for adaptive power save.
2196      *
2197      * @return true if there was an effectual change. If full battery saver is enabled or the
2198      * adaptive policy is not enabled, then this will return false.
2199      *
2200      * @hide
2201      */
2202     @SystemApi
2203     @RequiresPermission(anyOf = {
2204             android.Manifest.permission.DEVICE_POWER,
2205             android.Manifest.permission.POWER_SAVER
2206     })
setAdaptivePowerSavePolicy(@onNull BatterySaverPolicyConfig config)2207     public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
2208         try {
2209             return mService.setAdaptivePowerSavePolicy(config);
2210         } catch (RemoteException e) {
2211             throw e.rethrowFromSystemServer();
2212         }
2213     }
2214 
2215     /**
2216      * Enables or disables adaptive power save.
2217      *
2218      * @return true if there was an effectual change. If full battery saver is enabled, then this
2219      * will return false.
2220      *
2221      * @hide
2222      */
2223     @SystemApi
2224     @RequiresPermission(anyOf = {
2225             android.Manifest.permission.DEVICE_POWER,
2226             android.Manifest.permission.POWER_SAVER
2227     })
setAdaptivePowerSaveEnabled(boolean enabled)2228     public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
2229         try {
2230             return mService.setAdaptivePowerSaveEnabled(enabled);
2231         } catch (RemoteException e) {
2232             throw e.rethrowFromSystemServer();
2233         }
2234     }
2235 
2236     /**
2237      * Indicates automatic battery saver toggling by the system will be based on percentage.
2238      *
2239      * @see PowerManager#getPowerSaveModeTrigger()
2240      *
2241      *  @hide
2242      */
2243     @SystemApi
2244     public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0;
2245 
2246     /**
2247      * Indicates automatic battery saver toggling by the system will be based on the state
2248      * of the dynamic power savings signal.
2249      *
2250      * @see PowerManager#setDynamicPowerSaveHint(boolean, int)
2251      * @see PowerManager#getPowerSaveModeTrigger()
2252      *
2253      *  @hide
2254      */
2255     @SystemApi
2256     public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1;
2257 
2258     /** @hide */
2259     @Retention(RetentionPolicy.SOURCE)
2260     @IntDef(value = {
2261         POWER_SAVE_MODE_TRIGGER_PERCENTAGE,
2262         POWER_SAVE_MODE_TRIGGER_DYNAMIC
2263 
2264     })
2265     public @interface AutoPowerSaveModeTriggers {}
2266 
2267 
2268     /**
2269      * Returns the current battery saver control mode. Values it may return are defined in
2270      * AutoPowerSaveModeTriggers. Note that this is a global device state, not a per user setting.
2271      *
2272      * <p>Note: Prior to Android version {@link Build.VERSION_CODES#S}, any app calling this method
2273      * was required to hold the {@link android.Manifest.permission#POWER_SAVER} permission. Starting
2274      * from Android version {@link Build.VERSION_CODES#S}, that permission is no longer required.
2275      *
2276      * @return The current value power saver mode for the system.
2277      *
2278      * @see AutoPowerSaveModeTriggers
2279      * @see PowerManager#getPowerSaveModeTrigger()
2280      * @hide
2281      */
2282     @AutoPowerSaveModeTriggers
2283     @SystemApi
getPowerSaveModeTrigger()2284     public int getPowerSaveModeTrigger() {
2285         try {
2286             return mService.getPowerSaveModeTrigger();
2287         } catch (RemoteException e) {
2288             throw e.rethrowFromSystemServer();
2289         }
2290     }
2291 
2292     /**
2293      * Allows an app to tell the system how long it believes the battery will last and whether
2294      * this estimate is customized based on historical device usage or on a generic configuration.
2295      * These estimates will be displayed on system UI surfaces in place of the system computed
2296      * value.
2297      *
2298      * Calling this requires either the {@link android.Manifest.permission#DEVICE_POWER} or the
2299      * {@link android.Manifest.permission#BATTERY_PREDICTION} permissions.
2300      *
2301      * @param timeRemaining  The time remaining as a {@link Duration}.
2302      * @param isPersonalized true if personalized based on device usage history, false otherwise.
2303      * @throws IllegalStateException if the device is powered or currently charging
2304      * @hide
2305      */
2306     @SystemApi
2307     @RequiresPermission(anyOf = {
2308             android.Manifest.permission.BATTERY_PREDICTION,
2309             android.Manifest.permission.DEVICE_POWER
2310     })
setBatteryDischargePrediction(@onNull Duration timeRemaining, boolean isPersonalized)2311     public void setBatteryDischargePrediction(@NonNull Duration timeRemaining,
2312             boolean isPersonalized) {
2313         if (timeRemaining == null) {
2314             throw new IllegalArgumentException("time remaining must not be null");
2315         }
2316         try {
2317             mService.setBatteryDischargePrediction(new ParcelDuration(timeRemaining),
2318                     isPersonalized);
2319         } catch (RemoteException e) {
2320             throw e.rethrowFromSystemServer();
2321         }
2322     }
2323 
2324     /**
2325      * Returns the current battery life remaining estimate.
2326      *
2327      * @return The estimated battery life remaining as a {@link Duration}. Will be {@code null} if
2328      * the device is powered, charging, or an error was encountered.
2329      */
2330     @Nullable
getBatteryDischargePrediction()2331     public Duration getBatteryDischargePrediction() {
2332         try {
2333             final ParcelDuration parcelDuration = mService.getBatteryDischargePrediction();
2334             if (parcelDuration == null) {
2335                 return null;
2336             }
2337             return parcelDuration.getDuration();
2338         } catch (RemoteException e) {
2339             throw e.rethrowFromSystemServer();
2340         }
2341     }
2342 
2343     /**
2344      * Returns whether the current battery life remaining estimate is personalized based on device
2345      * usage history or not. This value does not take a device's powered or charging state into
2346      * account.
2347      *
2348      * @return A boolean indicating if the current discharge estimate is personalized based on
2349      * historical device usage or not.
2350      */
isBatteryDischargePredictionPersonalized()2351     public boolean isBatteryDischargePredictionPersonalized() {
2352         try {
2353             return mService.isBatteryDischargePredictionPersonalized();
2354         } catch (RemoteException e) {
2355             throw e.rethrowFromSystemServer();
2356         }
2357     }
2358 
2359     /**
2360      * Get data about the battery saver mode for a specific service
2361      * @param serviceType unique key for the service, one of {@link ServiceType}
2362      * @return Battery saver state data.
2363      *
2364      * @hide
2365      * @see com.android.server.power.batterysaver.BatterySaverPolicy
2366      * @see PowerSaveState
2367      */
getPowerSaveState(@erviceType int serviceType)2368     public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
2369         try {
2370             return mService.getPowerSaveState(serviceType);
2371         } catch (RemoteException e) {
2372             throw e.rethrowFromSystemServer();
2373         }
2374     }
2375 
2376     /**
2377      * Returns how location features should behave when battery saver is on. When battery saver
2378      * is off, this will always return {@link #LOCATION_MODE_NO_CHANGE}.
2379      *
2380      * <p>This API is normally only useful for components that provide location features.
2381      *
2382      * @see #isPowerSaveMode()
2383      * @see #ACTION_POWER_SAVE_MODE_CHANGED
2384      */
2385     @LocationPowerSaveMode
getLocationPowerSaveMode()2386     public int getLocationPowerSaveMode() {
2387         final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.LOCATION);
2388         if (!powerSaveState.batterySaverEnabled) {
2389             return LOCATION_MODE_NO_CHANGE;
2390         }
2391         return powerSaveState.locationMode;
2392     }
2393 
2394     /**
2395      * Returns how SoundTrigger features should behave when battery saver is on. When battery saver
2396      * is off, this will always return {@link #SOUND_TRIGGER_MODE_ALL_ENABLED}.
2397      *
2398      * <p>This API is normally only useful for components that provide use SoundTrigger features.
2399      *
2400      * @see #isPowerSaveMode()
2401      * @see #ACTION_POWER_SAVE_MODE_CHANGED
2402      *
2403      * @hide
2404      */
2405     @SoundTriggerPowerSaveMode
getSoundTriggerPowerSaveMode()2406     public int getSoundTriggerPowerSaveMode() {
2407         final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.SOUND);
2408         if (!powerSaveState.batterySaverEnabled) {
2409             return SOUND_TRIGGER_MODE_ALL_ENABLED;
2410         }
2411         return powerSaveState.soundTriggerMode;
2412     }
2413 
2414     /**
2415      * Returns true if the device is currently in idle mode.  This happens when a device
2416      * has been sitting unused and unmoving for a sufficiently long period of time, so that
2417      * it decides to go into a lower power-use state.  This may involve things like turning
2418      * off network access to apps.  You can monitor for changes to this state with
2419      * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
2420      *
2421      * @return Returns true if currently in active device idle mode, else false.  This is
2422      * when idle mode restrictions are being actively applied; it will return false if the
2423      * device is in a long-term idle mode but currently running a maintenance window where
2424      * restrictions have been lifted.
2425      */
isDeviceIdleMode()2426     public boolean isDeviceIdleMode() {
2427         try {
2428             return mService.isDeviceIdleMode();
2429         } catch (RemoteException e) {
2430             throw e.rethrowFromSystemServer();
2431         }
2432     }
2433 
2434     /**
2435      * Returns true if the device is currently in light idle mode.  This happens when a device
2436      * has had its screen off for a short time, switching it into a batching mode where we
2437      * execute jobs, syncs, networking on a batching schedule.  You can monitor for changes to
2438      * this state with {@link #ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED}.
2439      *
2440      * @return Returns true if currently in active device light idle mode, else false.  This is
2441      * when light idle mode restrictions are being actively applied; it will return false if the
2442      * device is in a long-term idle mode but currently running a maintenance window where
2443      * restrictions have been lifted.
2444      */
isDeviceLightIdleMode()2445     public boolean isDeviceLightIdleMode() {
2446         try {
2447             return mService.isLightDeviceIdleMode();
2448         } catch (RemoteException e) {
2449             throw e.rethrowFromSystemServer();
2450         }
2451     }
2452 
2453     /**
2454      * @see #isDeviceLightIdleMode()
2455      * @deprecated
2456      * @hide
2457      */
2458     @Deprecated
2459     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.S,
2460             publicAlternatives = "Use {@link #isDeviceLightIdleMode()} instead.")
isLightDeviceIdleMode()2461     public boolean isLightDeviceIdleMode() {
2462         return isDeviceLightIdleMode();
2463     }
2464 
2465     /**
2466      * Returns true if Low Power Standby is supported on this device.
2467      *
2468      * @hide
2469      */
2470     @SystemApi
2471     @RequiresPermission(anyOf = {
2472             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2473             android.Manifest.permission.DEVICE_POWER
2474     })
isLowPowerStandbySupported()2475     public boolean isLowPowerStandbySupported() {
2476         try {
2477             return mService.isLowPowerStandbySupported();
2478         } catch (RemoteException e) {
2479             throw e.rethrowFromSystemServer();
2480         }
2481     }
2482 
2483     /**
2484      * Returns true if Low Power Standby is enabled.
2485      *
2486      * <p>When Low Power Standby is enabled, apps (including apps running foreground services) are
2487      * subject to additional restrictions while the device is non-interactive, outside of device
2488      * idle maintenance windows: Their network access is disabled, and any wakelocks they hold are
2489      * ignored.
2490      *
2491      * <p>When Low Power Standby is enabled or disabled, a Intent with action
2492      * {@link #ACTION_LOW_POWER_STANDBY_ENABLED_CHANGED} is broadcast to registered receivers.
2493      */
isLowPowerStandbyEnabled()2494     public boolean isLowPowerStandbyEnabled() {
2495         try {
2496             return mService.isLowPowerStandbyEnabled();
2497         } catch (RemoteException e) {
2498             throw e.rethrowFromSystemServer();
2499         }
2500     }
2501 
2502     /**
2503      * Set whether Low Power Standby is enabled.
2504      * Does nothing if Low Power Standby is not supported.
2505      *
2506      * @see #isLowPowerStandbySupported()
2507      * @see #isLowPowerStandbyEnabled()
2508      * @hide
2509      */
2510     @SystemApi
2511     @RequiresPermission(anyOf = {
2512             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2513             android.Manifest.permission.DEVICE_POWER
2514     })
setLowPowerStandbyEnabled(boolean enabled)2515     public void setLowPowerStandbyEnabled(boolean enabled) {
2516         try {
2517             mService.setLowPowerStandbyEnabled(enabled);
2518         } catch (RemoteException e) {
2519             throw e.rethrowFromSystemServer();
2520         }
2521     }
2522 
2523     /**
2524      * Set whether Low Power Standby should be active during doze maintenance mode.
2525      * Does nothing if Low Power Standby is not supported.
2526      *
2527      * @see #isLowPowerStandbySupported()
2528      * @see #isLowPowerStandbyEnabled()
2529      * @hide
2530      */
2531     @SystemApi
2532     @RequiresPermission(anyOf = {
2533             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2534             android.Manifest.permission.DEVICE_POWER
2535     })
setLowPowerStandbyActiveDuringMaintenance(boolean activeDuringMaintenance)2536     public void setLowPowerStandbyActiveDuringMaintenance(boolean activeDuringMaintenance) {
2537         try {
2538             mService.setLowPowerStandbyActiveDuringMaintenance(activeDuringMaintenance);
2539         } catch (RemoteException e) {
2540             throw e.rethrowFromSystemServer();
2541         }
2542     }
2543 
2544     /**
2545      * Force Low Power Standby restrictions to be active.
2546      * Does nothing if Low Power Standby is not supported.
2547      *
2548      * @see #isLowPowerStandbySupported()
2549      * @hide
2550      */
2551     @TestApi
2552     @RequiresPermission(anyOf = {
2553             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2554             android.Manifest.permission.DEVICE_POWER
2555     })
forceLowPowerStandbyActive(boolean active)2556     public void forceLowPowerStandbyActive(boolean active) {
2557         try {
2558             mService.forceLowPowerStandbyActive(active);
2559         } catch (RemoteException e) {
2560             throw e.rethrowFromSystemServer();
2561         }
2562     }
2563 
2564     /**
2565      * Sets the current Low Power Standby policy.
2566      *
2567      * When the policy changes {@link #ACTION_LOW_POWER_STANDBY_POLICY_CHANGED} is broadcast to
2568      * registered receivers.
2569      *
2570      * @param policy The policy to set. If null, resets to the default policy.
2571      * @see #getLowPowerStandbyPolicy
2572      * @hide
2573      */
2574     @SystemApi
2575     @RequiresPermission(anyOf = {
2576             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2577             android.Manifest.permission.DEVICE_POWER
2578     })
setLowPowerStandbyPolicy(@ullable LowPowerStandbyPolicy policy)2579     public void setLowPowerStandbyPolicy(@Nullable LowPowerStandbyPolicy policy) {
2580         try {
2581             mService.setLowPowerStandbyPolicy(LowPowerStandbyPolicy.toParcelable(policy));
2582         } catch (RemoteException e) {
2583             throw e.rethrowFromSystemServer();
2584         }
2585     }
2586 
2587     /**
2588      * Get the current Low Power Standby policy.
2589      *
2590      * When the policy changes {@link #ACTION_LOW_POWER_STANDBY_POLICY_CHANGED} is broadcast to
2591      * registered receivers.
2592      *
2593      * @see #setLowPowerStandbyPolicy
2594      * @hide
2595      */
2596     @SystemApi
2597     @Nullable
2598     @RequiresPermission(anyOf = {
2599             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2600             android.Manifest.permission.DEVICE_POWER
2601     })
getLowPowerStandbyPolicy()2602     public LowPowerStandbyPolicy getLowPowerStandbyPolicy() {
2603         try {
2604             return LowPowerStandbyPolicy.fromParcelable(mService.getLowPowerStandbyPolicy());
2605         } catch (RemoteException e) {
2606             throw e.rethrowFromSystemServer();
2607         }
2608     }
2609 
2610     /**
2611      * Returns true if the calling package is exempt from Low Power Standby restrictions or
2612      * Low Power Standby is disabled (so Low Power Standby does not restrict apps),
2613      * false otherwise.
2614      */
isExemptFromLowPowerStandby()2615     public boolean isExemptFromLowPowerStandby() {
2616         try {
2617             return mService.isExemptFromLowPowerStandby();
2618         } catch (RemoteException e) {
2619             throw e.rethrowFromSystemServer();
2620         }
2621     }
2622 
2623     /**
2624      * Returns true if Low Power Standby is disabled (so Low Power Standby does not restrict apps),
2625      * or apps may be automatically exempt from Low Power Standby restrictions for the given reason.
2626      *
2627      * The system may exempt apps from Low Power Standby restrictions when using allowed features.
2628      * For example, if {@link #LOW_POWER_STANDBY_ALLOWED_REASON_VOICE_INTERACTION} is allowed,
2629      * then apps with active voice interaction sessions are exempt from restrictions.
2630      */
isAllowedInLowPowerStandby(@owPowerStandbyAllowedReason int reason)2631     public boolean isAllowedInLowPowerStandby(@LowPowerStandbyAllowedReason int reason) {
2632         try {
2633             return mService.isReasonAllowedInLowPowerStandby(reason);
2634         } catch (RemoteException e) {
2635             throw e.rethrowFromSystemServer();
2636         }
2637     }
2638 
2639     /**
2640      * Returns true if Low Power Standby is disabled (so Low Power Standby does not restrict apps),
2641      * or apps are allowed to use a given feature during Low Power Standby.
2642      */
isAllowedInLowPowerStandby(@onNull String feature)2643     public boolean isAllowedInLowPowerStandby(@NonNull String feature) {
2644         try {
2645             return mService.isFeatureAllowedInLowPowerStandby(feature);
2646         } catch (RemoteException e) {
2647             throw e.rethrowFromSystemServer();
2648         }
2649     }
2650 
2651     /**
2652      * Creates a new Low Power Standby ports lock.
2653      *
2654      * <p>A Low Power Standby ports lock requests that the given ports remain open during
2655      * Low Power Standby.
2656      * Call {@link LowPowerStandbyPortsLock#acquire} to acquire the lock.
2657      * This request is only respected if the calling package is exempt
2658      * (see {@link #isExemptFromLowPowerStandby()}), and until the returned
2659      * {@code LowPowerStandbyPorts} object is destroyed or has
2660      * {@link LowPowerStandbyPortsLock#release} called on it.
2661      *
2662      * @hide
2663      */
2664     @SystemApi
2665     @RequiresPermission(android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS)
2666     @NonNull
newLowPowerStandbyPortsLock( @onNull List<LowPowerStandbyPortDescription> ports)2667     public LowPowerStandbyPortsLock newLowPowerStandbyPortsLock(
2668             @NonNull List<LowPowerStandbyPortDescription> ports) {
2669         LowPowerStandbyPortsLock standbyPorts = new LowPowerStandbyPortsLock(ports);
2670         return standbyPorts;
2671     }
2672 
2673     /**
2674      * Gets all ports that should remain open in standby.
2675      * Only includes ports requested by exempt packages (see {@link #getLowPowerStandbyPolicy()}).
2676      *
2677      * @hide
2678      */
2679     @SystemApi
2680     @RequiresPermission(anyOf = {
2681             android.Manifest.permission.MANAGE_LOW_POWER_STANDBY,
2682             android.Manifest.permission.DEVICE_POWER
2683     })
2684     @NonNull
getActiveLowPowerStandbyPorts()2685     public List<LowPowerStandbyPortDescription> getActiveLowPowerStandbyPorts() {
2686         try {
2687             return LowPowerStandbyPortDescription.fromParcelable(
2688                     mService.getActiveLowPowerStandbyPorts());
2689         } catch (RemoteException e) {
2690             throw e.rethrowFromSystemServer();
2691         }
2692     }
2693 
2694     /**
2695      * Return whether the given application package name is on the device's power allowlist.
2696      * Apps can be placed on the allowlist through the settings UI invoked by
2697      * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
2698      * <p>Being on the power allowlist means that the system will not apply most power saving
2699      * features to the app. Guardrails for extreme cases may still be applied.
2700      */
isIgnoringBatteryOptimizations(String packageName)2701     public boolean isIgnoringBatteryOptimizations(String packageName) {
2702         return getPowerExemptionManager().isAllowListed(packageName, true);
2703     }
2704 
2705     /**
2706      * Turn off the device.
2707      *
2708      * @param confirm If true, shows a shutdown confirmation dialog.
2709      * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
2710      * @param wait If true, this call waits for the shutdown to complete and does not return.
2711      *
2712      * @hide
2713      */
shutdown(boolean confirm, String reason, boolean wait)2714     public void shutdown(boolean confirm, String reason, boolean wait) {
2715         try {
2716             mService.shutdown(confirm, reason, wait);
2717         } catch (RemoteException e) {
2718             throw e.rethrowFromSystemServer();
2719         }
2720     }
2721 
2722     /**
2723      * This function checks if the device has implemented Sustained Performance
2724      * Mode. This needs to be checked only once and is constant for a particular
2725      * device/release.
2726      *
2727      * Sustained Performance Mode is intended to provide a consistent level of
2728      * performance for prolonged amount of time.
2729      *
2730      * Applications should check if the device supports this mode, before using
2731      * {@link android.view.Window#setSustainedPerformanceMode}.
2732      *
2733      * @return Returns True if the device supports it, false otherwise.
2734      *
2735      * @see android.view.Window#setSustainedPerformanceMode
2736      */
isSustainedPerformanceModeSupported()2737     public boolean isSustainedPerformanceModeSupported() {
2738         return mContext.getResources().getBoolean(
2739                 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
2740     }
2741 
2742     /**
2743      * Thermal status code: Not under throttling.
2744      */
2745     public static final int THERMAL_STATUS_NONE = Temperature.THROTTLING_NONE;
2746 
2747     /**
2748      * Thermal status code: Light throttling where UX is not impacted.
2749      */
2750     public static final int THERMAL_STATUS_LIGHT = Temperature.THROTTLING_LIGHT;
2751 
2752     /**
2753      * Thermal status code: Moderate throttling where UX is not largely impacted.
2754      */
2755     public static final int THERMAL_STATUS_MODERATE = Temperature.THROTTLING_MODERATE;
2756 
2757     /**
2758      * Thermal status code: Severe throttling where UX is largely impacted.
2759      */
2760     public static final int THERMAL_STATUS_SEVERE = Temperature.THROTTLING_SEVERE;
2761 
2762     /**
2763      * Thermal status code: Platform has done everything to reduce power.
2764      */
2765     public static final int THERMAL_STATUS_CRITICAL = Temperature.THROTTLING_CRITICAL;
2766 
2767     /**
2768      * Thermal status code: Key components in platform are shutting down due to thermal condition.
2769      * Device functionalities will be limited.
2770      */
2771     public static final int THERMAL_STATUS_EMERGENCY = Temperature.THROTTLING_EMERGENCY;
2772 
2773     /**
2774      * Thermal status code: Need shutdown immediately.
2775      */
2776     public static final int THERMAL_STATUS_SHUTDOWN = Temperature.THROTTLING_SHUTDOWN;
2777 
2778     /** @hide */
2779     @Target(ElementType.TYPE_USE)
2780     @IntDef(prefix = { "THERMAL_STATUS_" }, value = {
2781             THERMAL_STATUS_NONE,
2782             THERMAL_STATUS_LIGHT,
2783             THERMAL_STATUS_MODERATE,
2784             THERMAL_STATUS_SEVERE,
2785             THERMAL_STATUS_CRITICAL,
2786             THERMAL_STATUS_EMERGENCY,
2787             THERMAL_STATUS_SHUTDOWN,
2788     })
2789     @Retention(RetentionPolicy.SOURCE)
2790     public @interface ThermalStatus {}
2791 
2792     /**
2793      * This function returns the current thermal status of the device.
2794      *
2795      * @return thermal status as int, {@link #THERMAL_STATUS_NONE} if device in not under
2796      * thermal throttling.
2797      */
getCurrentThermalStatus()2798     public @ThermalStatus int getCurrentThermalStatus() {
2799         try {
2800             return mThermalService.getCurrentThermalStatus();
2801         } catch (RemoteException e) {
2802             throw e.rethrowFromSystemServer();
2803         }
2804     }
2805 
2806     /**
2807      * Listener passed to
2808      * {@link PowerManager#addThermalStatusListener} and
2809      * {@link PowerManager#removeThermalStatusListener}
2810      * to notify caller of thermal status has changed.
2811      */
2812     public interface OnThermalStatusChangedListener {
2813 
2814         /**
2815          * Called when overall thermal throttling status changed.
2816          * @param status the status
2817          */
onThermalStatusChanged(@hermalStatus int status)2818         void onThermalStatusChanged(@ThermalStatus int status);
2819     }
2820 
2821     /**
2822      * Listener passed to
2823      * {@link PowerManager#addThermalHeadroomListener} and
2824      * {@link PowerManager#removeThermalHeadroomListener}
2825      * to notify caller of Thermal headroom or thresholds changes.
2826      */
2827     @FlaggedApi(Flags.FLAG_ALLOW_THERMAL_THRESHOLDS_CALLBACK)
2828     public interface OnThermalHeadroomChangedListener {
2829 
2830         /**
2831          * Called when overall thermal headroom or headroom thresholds have significantly
2832          * changed that requires action.
2833          * <p>
2834          * This may not be used to fully replace the {@link #getThermalHeadroom(int)} API as it will
2835          * only notify on one of the conditions below that will significantly change one or both
2836          * values of current headroom and headroom thresholds since previous callback:
2837          *   1. thermal throttling events: when the skin temperature has cross any of the thresholds
2838          *      and there isn't a previous callback in a short time ago with similar values.
2839          *   2. skin temperature threshold change events: note that if the absolute °C threshold
2840          *      values change in a way that does not significantly change the current headroom nor
2841          *      headroom thresholds, it will not trigger any callback. The client should not
2842          *      need to take action in such case since the difference from temperature vs threshold
2843          *      hasn't changed.
2844          * <p>
2845          * By API version 36, it provides a forecast in the same call for developer's convenience
2846          * based on a {@code forecastSeconds} defined by the device, which can be static or dynamic
2847          * varied by OEM. Be aware that it will not notify on forecast temperature change but the
2848          * events mentioned above. So periodically polling against {@link #getThermalHeadroom(int)}
2849          * API should still be used to actively monitor temperature forecast in advance.
2850          * <p>
2851          * This serves as a more advanced option compared to thermal status listener, where the
2852          * latter will only notify on thermal throttling events with status update.
2853          *
2854          * @param headroom current headroom
2855          * @param forecastHeadroom forecasted headroom in future
2856          * @param forecastSeconds how many seconds in the future used in forecast
2857          * @param thresholds new headroom thresholds, see {@link #getThermalHeadroomThresholds()}
2858          */
onThermalHeadroomChanged( @loatRangefrom = 0f) float headroom, @FloatRange(from = 0f) float forecastHeadroom, @IntRange(from = 0) int forecastSeconds, @NonNull Map<@ThermalStatus Integer, Float> thresholds)2859         void onThermalHeadroomChanged(
2860                 @FloatRange(from = 0f) float headroom,
2861                 @FloatRange(from = 0f) float forecastHeadroom,
2862                 @IntRange(from = 0) int forecastSeconds,
2863                 @NonNull Map<@ThermalStatus Integer, Float> thresholds);
2864     }
2865 
2866     /**
2867      * This function adds a listener for thermal status change, listener callback will be
2868      * enqueued tasks on the main thread
2869      *
2870      * @param listener listener to be added,
2871      */
addThermalStatusListener(@onNull OnThermalStatusChangedListener listener)2872     public void addThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
2873         Objects.requireNonNull(listener, "Thermal status listener cannot be null");
2874         addThermalStatusListener(mContext.getMainExecutor(), listener);
2875     }
2876 
2877     /**
2878      * This function adds a listener for thermal status change.
2879      *
2880      * @param executor {@link Executor} to handle listener callback.
2881      * @param listener listener to be added.
2882      */
addThermalStatusListener(@onNull @allbackExecutor Executor executor, @NonNull OnThermalStatusChangedListener listener)2883     public void addThermalStatusListener(@NonNull @CallbackExecutor Executor executor,
2884             @NonNull OnThermalStatusChangedListener listener) {
2885         Objects.requireNonNull(listener, "Thermal status listener cannot be null");
2886         Objects.requireNonNull(executor, "Executor cannot be null");
2887         synchronized (mThermalStatusListenerMap) {
2888             Preconditions.checkArgument(!mThermalStatusListenerMap.containsKey(listener),
2889                     "Thermal status listener already registered: %s", listener);
2890             IThermalStatusListener internalListener = new IThermalStatusListener.Stub() {
2891                 @Override
2892                 public void onStatusChange(int status) {
2893                     final long token = Binder.clearCallingIdentity();
2894                     try {
2895                         executor.execute(() -> listener.onThermalStatusChanged(status));
2896                     } finally {
2897                         Binder.restoreCallingIdentity(token);
2898                     }
2899                 }
2900             };
2901             try {
2902                 if (mThermalService.registerThermalStatusListener(internalListener)) {
2903                     mThermalStatusListenerMap.put(listener, internalListener);
2904                 } else {
2905                     throw new RuntimeException("Thermal status listener failed to set");
2906                 }
2907             } catch (RemoteException e) {
2908                 throw e.rethrowFromSystemServer();
2909             }
2910         }
2911     }
2912 
2913     /**
2914      * This function removes a listener for thermal status change
2915      *
2916      * @param listener listener to be removed
2917      */
removeThermalStatusListener(@onNull OnThermalStatusChangedListener listener)2918     public void removeThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
2919         Objects.requireNonNull(listener, "Thermal status listener cannot be null");
2920         synchronized (mThermalStatusListenerMap) {
2921             IThermalStatusListener internalListener = mThermalStatusListenerMap.get(listener);
2922             Preconditions.checkArgument(internalListener != null,
2923                     "Thermal status listener was not added");
2924             try {
2925                 if (mThermalService.unregisterThermalStatusListener(internalListener)) {
2926                     mThermalStatusListenerMap.remove(listener);
2927                 } else {
2928                     throw new RuntimeException("Failed to unregister thermal status listener");
2929                 }
2930             } catch (RemoteException e) {
2931                 throw e.rethrowFromSystemServer();
2932             }
2933         }
2934     }
2935 
2936     /**
2937      * This function adds a listener for thermal headroom change, listener callback will be
2938      * enqueued tasks on the main thread
2939      *
2940      * @param listener listener to be added,
2941      */
2942     @FlaggedApi(Flags.FLAG_ALLOW_THERMAL_THRESHOLDS_CALLBACK)
addThermalHeadroomListener(@onNull OnThermalHeadroomChangedListener listener)2943     public void addThermalHeadroomListener(@NonNull OnThermalHeadroomChangedListener listener) {
2944         Objects.requireNonNull(listener, "Thermal headroom listener cannot be null");
2945         addThermalHeadroomListener(mContext.getMainExecutor(), listener);
2946     }
2947 
2948     /**
2949      * This function adds a listener for thermal headroom change.
2950      *
2951      * @param executor {@link Executor} to handle listener callback.
2952      * @param listener listener to be added.
2953      */
2954     @FlaggedApi(Flags.FLAG_ALLOW_THERMAL_THRESHOLDS_CALLBACK)
addThermalHeadroomListener(@onNull @allbackExecutor Executor executor, @NonNull OnThermalHeadroomChangedListener listener)2955     public void addThermalHeadroomListener(@NonNull @CallbackExecutor Executor executor,
2956             @NonNull OnThermalHeadroomChangedListener listener) {
2957         Objects.requireNonNull(listener, "Thermal headroom listener cannot be null");
2958         Objects.requireNonNull(executor, "Executor cannot be null");
2959         synchronized (mThermalHeadroomListenerMap) {
2960             Preconditions.checkArgument(!mThermalHeadroomListenerMap.containsKey(listener),
2961                     "Thermal headroom listener already registered: %s", listener);
2962             IThermalHeadroomListener internalListener = new IThermalHeadroomListener.Stub() {
2963                 @Override
2964                 public void onHeadroomChange(float headroom, float forecastHeadroom,
2965                         int forecastSeconds, float[] thresholds)
2966                         throws RemoteException {
2967                     final Map<Integer, Float> map = convertThresholdsToMap(thresholds);
2968                     final long token = Binder.clearCallingIdentity();
2969                     try {
2970                         executor.execute(() -> listener.onThermalHeadroomChanged(headroom,
2971                                 forecastHeadroom, forecastSeconds, map));
2972                     } finally {
2973                         Binder.restoreCallingIdentity(token);
2974                     }
2975                 }
2976             };
2977             try {
2978                 if (mThermalService.registerThermalHeadroomListener(internalListener)) {
2979                     mThermalHeadroomListenerMap.put(listener, internalListener);
2980                 } else {
2981                     throw new RuntimeException("Thermal headroom listener failed to set");
2982                 }
2983             } catch (RemoteException e) {
2984                 throw e.rethrowFromSystemServer();
2985             }
2986         }
2987     }
2988 
2989     /**
2990      * This function removes a listener for Thermal headroom change
2991      *
2992      * @param listener listener to be removed
2993      */
2994     @FlaggedApi(Flags.FLAG_ALLOW_THERMAL_THRESHOLDS_CALLBACK)
removeThermalHeadroomListener(@onNull OnThermalHeadroomChangedListener listener)2995     public void removeThermalHeadroomListener(@NonNull OnThermalHeadroomChangedListener listener) {
2996         Objects.requireNonNull(listener, "Thermal headroom listener cannot be null");
2997         synchronized (mThermalHeadroomListenerMap) {
2998             IThermalHeadroomListener internalListener = mThermalHeadroomListenerMap.get(listener);
2999             Preconditions.checkArgument(internalListener != null,
3000                     "Thermal headroom listener was not added");
3001             try {
3002                 if (mThermalService.unregisterThermalHeadroomListener(internalListener)) {
3003                     mThermalHeadroomListenerMap.remove(listener);
3004                 } else {
3005                     throw new RuntimeException("Failed to unregister thermal status listener");
3006                 }
3007             } catch (RemoteException e) {
3008                 throw e.rethrowFromSystemServer();
3009             }
3010         }
3011     }
3012 
3013 
3014     @CurrentTimeMillisLong
3015     private final AtomicLong mLastHeadroomUpdate = new AtomicLong(0L);
3016     private static final int MINIMUM_HEADROOM_TIME_MILLIS = 500;
3017 
3018     /**
3019      * Provides an estimate of how much thermal headroom the device currently has before hitting
3020      * severe throttling.
3021      *
3022      * Note that this only attempts to track the headroom of slow-moving sensors, such as the skin
3023      * temperature sensor. This means that there is no benefit to calling this function more
3024      * frequently than about once per second, and attempts to call significantly more frequently may
3025      * result in the function returning {@code NaN}.
3026      * <p>
3027      * In addition, in order to be able to provide an accurate forecast, the system does not attempt
3028      * to forecast until it has multiple temperature samples from which to extrapolate. This should
3029      * only take a few seconds from the time of the first call, but during this time, no forecasting
3030      * will occur, and the current headroom will be returned regardless of the value of
3031      * {@code forecastSeconds}.
3032      * <p>
3033      * The value returned is a non-negative float that represents how much of the thermal envelope
3034      * is in use (or is forecasted to be in use). A value of 1.0 indicates that the device is (or
3035      * will be) throttled at {@link #THERMAL_STATUS_SEVERE}. Such throttling can affect the CPU,
3036      * GPU, and other subsystems. Values may exceed 1.0, but there is no implied mapping to specific
3037      * thermal status levels beyond that point. This means that values greater than 1.0 may
3038      * correspond to {@link #THERMAL_STATUS_SEVERE}, but may also represent heavier throttling.
3039      * <p>
3040      * A value of 0.0 corresponds to a fixed distance from 1.0, but does not correspond to any
3041      * particular thermal status or temperature. Values on (0.0, 1.0] may be expected to scale
3042      * linearly with temperature, though temperature changes over time are typically not linear.
3043      * Negative values will be clamped to 0.0 before returning.
3044      *
3045      * @param forecastSeconds how many seconds in the future to forecast. Given that device
3046      *                        conditions may change at any time, forecasts from further in the
3047      *                        future will likely be less accurate than forecasts in the near future.
3048      * @return a value greater than or equal to 0.0 where 1.0 indicates the SEVERE throttling
3049      *         threshold, as described above. Returns NaN if the device does not support this
3050      *         functionality or if this function is called significantly faster than once per
3051      *         second.
3052      */
getThermalHeadroom( @ntRangefrom = 0, to = 60) int forecastSeconds)3053     public @FloatRange(from = 0f) float getThermalHeadroom(
3054             @IntRange(from = 0, to = 60) int forecastSeconds) {
3055         // Rate-limit calls into the thermal service
3056         long now = SystemClock.elapsedRealtime();
3057         long timeSinceLastUpdate = now - mLastHeadroomUpdate.get();
3058         if (timeSinceLastUpdate < MINIMUM_HEADROOM_TIME_MILLIS) {
3059             return Float.NaN;
3060         }
3061 
3062         try {
3063             float forecast = mThermalService.getThermalHeadroom(forecastSeconds);
3064             mLastHeadroomUpdate.set(SystemClock.elapsedRealtime());
3065             return forecast;
3066         } catch (RemoteException e) {
3067             throw e.rethrowFromSystemServer();
3068         }
3069     }
3070 
3071     /**
3072      * Gets the thermal headroom thresholds for all available thermal throttling status above
3073      * {@link #THERMAL_STATUS_NONE}.
3074      * <p>
3075      * A thermal status key in the returned map is only set if the device manufacturer has the
3076      * corresponding threshold defined for at least one of its sensors. If it's set, one should
3077      * expect to see that from {@link #getCurrentThermalStatus()} or
3078      * {@link OnThermalStatusChangedListener#onThermalStatusChanged(int)}.
3079      * <p>
3080      * The headroom threshold is used to interpret the possible thermal throttling status based on
3081      * the headroom prediction. For example, if the headroom threshold for
3082      * {@link #THERMAL_STATUS_LIGHT} is 0.7, and a headroom prediction in 10s returns 0.75
3083      * (or {@code getThermalHeadroom(10)=0.75}), one can expect that in 10 seconds the system could
3084      * be in lightly throttled state if the workload remains the same. The app can consider
3085      * taking actions according to the nearest throttling status the difference between the headroom
3086      * and the threshold.
3087      * <p>
3088      * For new devices it's guaranteed to have a single sensor, but for older devices with multiple
3089      * sensors reporting different threshold values, the minimum threshold is taken to be
3090      * conservative on predictions. Thus, when reading real-time headroom, it's not guaranteed that
3091      * a real-time value of 0.75 (or {@code getThermalHeadroom(0)}=0.75) exceeding the threshold of
3092      * 0.7 above will always come with lightly throttled state
3093      * (or {@code getCurrentThermalStatus()=THERMAL_STATUS_LIGHT}) but it can be lower
3094      * (or {@code getCurrentThermalStatus()=THERMAL_STATUS_NONE}). While it's always guaranteed that
3095      * the device won't be throttled heavier than the unmet threshold's state, so a real-time
3096      * headroom of 0.75 will never come with {@link #THERMAL_STATUS_MODERATE} but lower, and 0.65
3097      * will never come with {@link #THERMAL_STATUS_LIGHT} but {@link #THERMAL_STATUS_NONE}.
3098      * <p>
3099      * Starting at {@link android.os.Build.VERSION_CODES#BAKLAVA} the returned map of thresholds can
3100      * change between calls to this function, one could use the new
3101      * {@link #addThermalHeadroomListener(Executor, OnThermalHeadroomChangedListener)} API to
3102      * register a listener and get callback for changes to thresholds.
3103      * <p>
3104      *
3105      * @return map from each thermal status to its thermal headroom
3106      * @throws IllegalStateException if the thermal service is not ready
3107      * @throws UnsupportedOperationException if the feature is not enabled
3108      */
3109     @FlaggedApi(Flags.FLAG_ALLOW_THERMAL_HEADROOM_THRESHOLDS)
getThermalHeadroomThresholds()3110     public @NonNull Map<@ThermalStatus Integer, Float> getThermalHeadroomThresholds() {
3111         try {
3112             return convertThresholdsToMap(mThermalService.getThermalHeadroomThresholds());
3113         } catch (RemoteException e) {
3114             throw e.rethrowFromSystemServer();
3115         }
3116     }
3117 
convertThresholdsToMap(final float[] thresholds)3118     private Map<@ThermalStatus Integer, Float> convertThresholdsToMap(final float[] thresholds) {
3119         final ArrayMap<Integer, Float> ret = new ArrayMap<>(THERMAL_STATUS_SHUTDOWN);
3120         for (int status = THERMAL_STATUS_LIGHT; status <= THERMAL_STATUS_SHUTDOWN; status++) {
3121             if (!Float.isNaN(thresholds[status])) {
3122                 ret.put(status, thresholds[status]);
3123             }
3124         }
3125         return ret;
3126     }
3127 
3128     /**
3129      * If true, the doze component is not started until after the screen has been
3130      * turned off and the screen off animation has been performed.
3131      * @hide
3132      */
setDozeAfterScreenOff(boolean dozeAfterScreenOf)3133     public void setDozeAfterScreenOff(boolean dozeAfterScreenOf) {
3134         try {
3135             mService.setDozeAfterScreenOff(dozeAfterScreenOf);
3136         } catch (RemoteException e) {
3137             throw e.rethrowFromSystemServer();
3138         }
3139     }
3140 
3141     /**
3142      * Returns true if ambient display is available on the device.
3143      * @hide
3144      */
3145     @SystemApi
3146     @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE)
isAmbientDisplayAvailable()3147     public boolean isAmbientDisplayAvailable() {
3148         try {
3149             return mService.isAmbientDisplayAvailable();
3150         } catch (RemoteException e) {
3151             throw e.rethrowFromSystemServer();
3152         }
3153     }
3154 
3155     /**
3156      * If true, suppresses the current ambient display configuration and disables ambient display.
3157      *
3158      * <p>This method has no effect if {@link #isAmbientDisplayAvailable()} is false.
3159      *
3160      * @param token A persistable identifier for the ambient display suppression that is unique
3161      *              within the calling application.
3162      * @param suppress If set to {@code true}, ambient display will be suppressed. If set to
3163      *                 {@code false}, ambient display will no longer be suppressed for the given
3164      *                 token.
3165      * @hide
3166      */
3167     @SystemApi
3168     @RequiresPermission(android.Manifest.permission.WRITE_DREAM_STATE)
suppressAmbientDisplay(@onNull String token, boolean suppress)3169     public void suppressAmbientDisplay(@NonNull String token, boolean suppress) {
3170         try {
3171             mService.suppressAmbientDisplay(token, suppress);
3172         } catch (RemoteException e) {
3173             throw e.rethrowFromSystemServer();
3174         }
3175     }
3176 
3177     /**
3178      * Returns true if ambient display is suppressed by the calling app with the given
3179      * {@code token}.
3180      *
3181      * <p>This method will return false if {@link #isAmbientDisplayAvailable()} is false.
3182      *
3183      * @param token The identifier of the ambient display suppression.
3184      * @hide
3185      */
3186     @SystemApi
3187     @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE)
isAmbientDisplaySuppressedForToken(@onNull String token)3188     public boolean isAmbientDisplaySuppressedForToken(@NonNull String token) {
3189         try {
3190             return mService.isAmbientDisplaySuppressedForToken(token);
3191         } catch (RemoteException e) {
3192             throw e.rethrowFromSystemServer();
3193         }
3194     }
3195 
3196     /**
3197      * Returns true if ambient display is suppressed by <em>any</em> app with <em>any</em> token.
3198      *
3199      * <p>This method will return false if {@link #isAmbientDisplayAvailable()} is false.
3200      * @hide
3201      */
3202     @SystemApi
3203     @RequiresPermission(android.Manifest.permission.READ_DREAM_STATE)
isAmbientDisplaySuppressed()3204     public boolean isAmbientDisplaySuppressed() {
3205         try {
3206             return mService.isAmbientDisplaySuppressed();
3207         } catch (RemoteException e) {
3208             throw e.rethrowFromSystemServer();
3209         }
3210     }
3211 
3212     /**
3213      * Returns true if ambient display is suppressed by the given {@code appUid} with the given
3214      * {@code token}.
3215      *
3216      * <p>This method will return false if {@link #isAmbientDisplayAvailable()} is false.
3217      *
3218      * @param token The identifier of the ambient display suppression.
3219      * @param appUid The uid of the app that suppressed ambient display.
3220      * @hide
3221      */
3222     @RequiresPermission(allOf = {
3223             android.Manifest.permission.READ_DREAM_STATE,
3224             android.Manifest.permission.READ_DREAM_SUPPRESSION })
isAmbientDisplaySuppressedForTokenByApp(@onNull String token, int appUid)3225     public boolean isAmbientDisplaySuppressedForTokenByApp(@NonNull String token, int appUid) {
3226         try {
3227             return mService.isAmbientDisplaySuppressedForTokenByApp(token, appUid);
3228         } catch (RemoteException e) {
3229             throw e.rethrowFromSystemServer();
3230         }
3231     }
3232 
3233     /**
3234      * Returns the reason the phone was last shutdown. Calling app must have the
3235      * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information.
3236      * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could
3237      * not be accessed.
3238      * @hide
3239      */
3240     @ShutdownReason
getLastShutdownReason()3241     public int getLastShutdownReason() {
3242         try {
3243             return mService.getLastShutdownReason();
3244         } catch (RemoteException e) {
3245             throw e.rethrowFromSystemServer();
3246         }
3247     }
3248 
3249     /**
3250      * Returns the reason the device last went to sleep (i.e. the last value of
3251      * the second argument of {@link #goToSleep(long, int, int) goToSleep}).
3252      *
3253      * @return One of the {@code GO_TO_SLEEP_REASON_*} constants.
3254      *
3255      * @hide
3256      */
3257     @GoToSleepReason
getLastSleepReason()3258     public int getLastSleepReason() {
3259         try {
3260             return mService.getLastSleepReason();
3261         } catch (RemoteException e) {
3262             throw e.rethrowFromSystemServer();
3263         }
3264     }
3265 
3266     /**
3267      * Forces the device to go to suspend, even if there are currently wakelocks being held.
3268      * <b>Caution</b>
3269      * This is a very dangerous command as it puts the device to sleep immediately. Apps and parts
3270      * of the system will not be notified and will not have an opportunity to save state prior to
3271      * the device going to suspend.
3272      * This method should only be used in very rare circumstances where the device is intended
3273      * to appear as completely off to the user and they have a well understood, reliable way of
3274      * re-enabling it.
3275      * </p><p>
3276      * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
3277      * </p>
3278      *
3279      * @return true on success, false otherwise.
3280      * @hide
3281      */
3282     @SystemApi
3283     @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
forceSuspend()3284     public boolean forceSuspend() {
3285         try {
3286             return mService.forceSuspend();
3287         } catch (RemoteException e) {
3288             throw e.rethrowFromSystemServer();
3289         }
3290     }
3291 
3292     /**
3293      * Intent that is broadcast when the enhanced battery discharge prediction changes. The new
3294      * value can be retrieved via {@link #getBatteryDischargePrediction()}.
3295      * This broadcast is only sent to registered receivers.
3296      *
3297      * @hide
3298      */
3299     @TestApi
3300     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3301     public static final String ACTION_ENHANCED_DISCHARGE_PREDICTION_CHANGED =
3302             "android.os.action.ENHANCED_DISCHARGE_PREDICTION_CHANGED";
3303 
3304     /**
3305      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
3306      * This broadcast is only sent to registered receivers.
3307      */
3308     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3309     public static final String ACTION_POWER_SAVE_MODE_CHANGED
3310             = "android.os.action.POWER_SAVE_MODE_CHANGED";
3311 
3312     /**
3313      * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
3314      * @hide
3315      */
3316     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3317     public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
3318             = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
3319 
3320     /**
3321      * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
3322      * This broadcast is only sent to registered receivers.
3323      */
3324     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3325     public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
3326             = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
3327 
3328     /**
3329      * Intent that is broadcast when the state of {@link #isDeviceLightIdleMode()} changes.
3330      * This broadcast is only sent to registered receivers.
3331      */
3332     @SuppressLint("ActionValue") // Need to do "LIGHT_DEVICE_IDLE..." for legacy reasons
3333     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3334     public static final String ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED =
3335             // Use the old string so we don't break legacy apps.
3336             "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
3337 
3338     /**
3339      * @see #ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED
3340      * @deprecated
3341      * @hide
3342      */
3343     @Deprecated
3344     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553,
3345             publicAlternatives = "Use {@link #ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED} instead")
3346     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3347     public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED =
3348             ACTION_DEVICE_LIGHT_IDLE_MODE_CHANGED;
3349 
3350     /**
3351      * @hide Intent that is broadcast when the set of power save allowlist apps has changed.
3352      * This broadcast is only sent to registered receivers.
3353      */
3354     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3355     public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
3356             = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
3357 
3358     /**
3359      * @hide Intent that is broadcast when the set of temporarily allowlisted apps has changed.
3360      * This broadcast is only sent to registered receivers.
3361      */
3362     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3363     public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
3364             = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
3365 
3366     /**
3367      * Intent that is broadcast when Low Power Standby is enabled or disabled.
3368      * This broadcast is only sent to registered receivers and receivers holding
3369      * {@code android.permission.MANAGE_LOW_POWER_STANDBY}.
3370      *
3371      * @see #isLowPowerStandbyEnabled()
3372      */
3373     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3374     public static final String ACTION_LOW_POWER_STANDBY_ENABLED_CHANGED =
3375             "android.os.action.LOW_POWER_STANDBY_ENABLED_CHANGED";
3376 
3377     /**
3378      * Intent that is broadcast when Low Power Standby policy is changed.
3379      * This broadcast is only sent to registered receivers and receivers holding
3380      * {@code android.permission.MANAGE_LOW_POWER_STANDBY}.
3381      *
3382      * @see #isExemptFromLowPowerStandby()
3383      * @see #isAllowedInLowPowerStandby(int)
3384      * @see #isAllowedInLowPowerStandby(String)
3385      */
3386     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3387     public static final String ACTION_LOW_POWER_STANDBY_POLICY_CHANGED =
3388             "android.os.action.LOW_POWER_STANDBY_POLICY_CHANGED";
3389 
3390     /**
3391      * Intent that is broadcast when Low Power Standby exempt ports change.
3392      *
3393      * @see #getActiveLowPowerStandbyPorts
3394      * @hide
3395      */
3396     @SystemApi
3397     @RequiresPermission(android.Manifest.permission.MANAGE_LOW_POWER_STANDBY)
3398     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
3399     public static final String ACTION_LOW_POWER_STANDBY_PORTS_CHANGED =
3400             "android.os.action.LOW_POWER_STANDBY_PORTS_CHANGED";
3401 
3402     /**
3403      * Signals that wake-on-lan/wake-on-wlan is allowed in Low Power Standby.
3404      *
3405      * <p>If Low Power Standby is enabled ({@link #isLowPowerStandbyEnabled()}),
3406      * wake-on-lan/wake-on-wlan may not be available while in standby.
3407      * Use {@link #isAllowedInLowPowerStandby(String)} to determine whether the device allows this
3408      * feature to be used during Low Power Standby with the currently active Low Power Standby
3409      * policy.
3410      *
3411      * @see #isAllowedInLowPowerStandby(String)
3412      */
3413     public static final String FEATURE_WAKE_ON_LAN_IN_LOW_POWER_STANDBY =
3414             "com.android.lowpowerstandby.WAKE_ON_LAN";
3415 
3416     /**
3417      * @hide
3418      */
3419     @IntDef(prefix = { "LOW_POWER_STANDBY_ALLOWED_REASON_" }, flag = true, value = {
3420             LOW_POWER_STANDBY_ALLOWED_REASON_VOICE_INTERACTION,
3421             LOW_POWER_STANDBY_ALLOWED_REASON_TEMP_POWER_SAVE_ALLOWLIST,
3422             LOW_POWER_STANDBY_ALLOWED_REASON_ONGOING_CALL,
3423     })
3424     @Retention(RetentionPolicy.SOURCE)
3425     public @interface LowPowerStandbyAllowedReason {
3426     }
3427 
3428     /**
3429      * Exempts active Voice Interaction Sessions in Low Power Standby.
3430      *
3431      * @see #isAllowedInLowPowerStandby(int)
3432      */
3433     public static final int LOW_POWER_STANDBY_ALLOWED_REASON_VOICE_INTERACTION = 1 << 0;
3434 
3435     /**
3436      * Exempts apps on the temporary powersave allowlist.
3437      *
3438      * @see #isAllowedInLowPowerStandby(int)
3439      */
3440     public static final int LOW_POWER_STANDBY_ALLOWED_REASON_TEMP_POWER_SAVE_ALLOWLIST = 1 << 1;
3441 
3442     /**
3443      * Exempts apps with ongoing calls.
3444      *
3445      * <p>This includes apps with foreground services of type "phoneCall".
3446      *
3447      * @see #isAllowedInLowPowerStandby(int)
3448      */
3449     public static final int LOW_POWER_STANDBY_ALLOWED_REASON_ONGOING_CALL = 1 << 2;
3450 
3451     /** @hide */
lowPowerStandbyAllowedReasonsToString( @owPowerStandbyAllowedReason int allowedReasons)3452     public static String lowPowerStandbyAllowedReasonsToString(
3453             @LowPowerStandbyAllowedReason int allowedReasons) {
3454         ArrayList<String> allowedStrings = new ArrayList<>();
3455         if ((allowedReasons & LOW_POWER_STANDBY_ALLOWED_REASON_VOICE_INTERACTION) != 0) {
3456             allowedStrings.add("ALLOWED_REASON_VOICE_INTERACTION");
3457             allowedReasons &= ~LOW_POWER_STANDBY_ALLOWED_REASON_VOICE_INTERACTION;
3458         }
3459         if ((allowedReasons & LOW_POWER_STANDBY_ALLOWED_REASON_TEMP_POWER_SAVE_ALLOWLIST) != 0) {
3460             allowedStrings.add("ALLOWED_REASON_TEMP_POWER_SAVE_ALLOWLIST");
3461             allowedReasons &= ~LOW_POWER_STANDBY_ALLOWED_REASON_TEMP_POWER_SAVE_ALLOWLIST;
3462         }
3463         if ((allowedReasons & LOW_POWER_STANDBY_ALLOWED_REASON_ONGOING_CALL) != 0) {
3464             allowedStrings.add("ALLOWED_REASON_ONGOING_CALL");
3465             allowedReasons &= ~LOW_POWER_STANDBY_ALLOWED_REASON_ONGOING_CALL;
3466         }
3467         if (allowedReasons != 0) {
3468             allowedStrings.add(String.valueOf(allowedReasons));
3469         }
3470         return String.join(",", allowedStrings);
3471     }
3472 
3473     /**
3474      * Policy that defines the restrictions enforced by Low Power Standby.
3475      *
3476      * @hide
3477      */
3478     @SystemApi
3479     public static final class LowPowerStandbyPolicy {
3480         /** Name of the policy, used for debugging & metrics */
3481         @NonNull
3482         private final String mIdentifier;
3483 
3484         /** Packages that are exempt from Low Power Standby restrictions. */
3485         @NonNull
3486         private final Set<String> mExemptPackages;
3487 
3488         /**
3489          * Reasons that this policy allows apps to be automatically exempted
3490          * from Low Power Standby restrictions for.
3491          */
3492         @LowPowerStandbyAllowedReason
3493         private final int mAllowedReasons;
3494 
3495         /**
3496          * Features that are allowed to be used in Low Power Standby.
3497          *
3498          * @see #FEATURE_WAKE_ON_LAN_IN_LOW_POWER_STANDBY
3499          */
3500         @NonNull
3501         private final Set<String> mAllowedFeatures;
3502 
3503         /**
3504          * Create a policy that defines the restrictions enforced by Low Power Standby.
3505          *
3506          * @param identifier Name of the policy, used for debugging & metrics.
3507          * @param exemptPackages Packages that are exempt from Low Power Standby restrictions.
3508          * @param allowedReasons Reasons that this policy allows apps to be automatically exempted
3509          *                       from Low Power Standby restrictions for.
3510          * @param allowedFeatures Features that are allowed to be used in Low Power Standby.
3511          *                        Features are declared as strings, see
3512          *                        {@link #FEATURE_WAKE_ON_LAN_IN_LOW_POWER_STANDBY} as an example.
3513          */
LowPowerStandbyPolicy(@onNull String identifier, @NonNull Set<String> exemptPackages, @LowPowerStandbyAllowedReason int allowedReasons, @NonNull Set<String> allowedFeatures)3514         public LowPowerStandbyPolicy(@NonNull String identifier,
3515                 @NonNull Set<String> exemptPackages,
3516                 @LowPowerStandbyAllowedReason int allowedReasons,
3517                 @NonNull Set<String> allowedFeatures) {
3518             Objects.requireNonNull(identifier);
3519             Objects.requireNonNull(exemptPackages);
3520             Objects.requireNonNull(allowedFeatures);
3521 
3522             mIdentifier = identifier;
3523             mExemptPackages = Collections.unmodifiableSet(exemptPackages);
3524             mAllowedReasons = allowedReasons;
3525             mAllowedFeatures = Collections.unmodifiableSet(allowedFeatures);
3526         }
3527 
3528         @NonNull
getIdentifier()3529         public String getIdentifier() {
3530             return mIdentifier;
3531         }
3532 
3533         @NonNull
getExemptPackages()3534         public Set<String> getExemptPackages() {
3535             return mExemptPackages;
3536         }
3537 
3538         @LowPowerStandbyAllowedReason
getAllowedReasons()3539         public int getAllowedReasons() {
3540             return mAllowedReasons;
3541         }
3542 
3543         @NonNull
getAllowedFeatures()3544         public Set<String> getAllowedFeatures() {
3545             return mAllowedFeatures;
3546         }
3547 
3548         @Override
toString()3549         public String toString() {
3550             return "Policy{"
3551                     + "mIdentifier='" + mIdentifier + '\''
3552                     + ", mExemptPackages=" + String.join(",", mExemptPackages)
3553                     + ", mAllowedReasons=" + lowPowerStandbyAllowedReasonsToString(mAllowedReasons)
3554                     + ", mAllowedFeatures=" + String.join(",", mAllowedFeatures)
3555                     + '}';
3556         }
3557 
3558         @Override
equals(Object o)3559         public boolean equals(Object o) {
3560             if (this == o) return true;
3561             if (!(o instanceof LowPowerStandbyPolicy)) return false;
3562             LowPowerStandbyPolicy that = (LowPowerStandbyPolicy) o;
3563             return mAllowedReasons == that.mAllowedReasons && Objects.equals(mIdentifier,
3564                     that.mIdentifier) && Objects.equals(mExemptPackages, that.mExemptPackages)
3565                     && Objects.equals(mAllowedFeatures, that.mAllowedFeatures);
3566         }
3567 
3568         @Override
hashCode()3569         public int hashCode() {
3570             return Objects.hash(mIdentifier, mExemptPackages, mAllowedReasons,
3571                     mAllowedFeatures);
3572         }
3573 
3574         /** @hide */
toParcelable( LowPowerStandbyPolicy policy)3575         public static IPowerManager.LowPowerStandbyPolicy toParcelable(
3576                 LowPowerStandbyPolicy policy) {
3577             if (policy == null) {
3578                 return null;
3579             }
3580 
3581             IPowerManager.LowPowerStandbyPolicy parcelablePolicy =
3582                     new IPowerManager.LowPowerStandbyPolicy();
3583             parcelablePolicy.identifier = policy.mIdentifier;
3584             parcelablePolicy.exemptPackages = new ArrayList<>(policy.mExemptPackages);
3585             parcelablePolicy.allowedReasons = policy.mAllowedReasons;
3586             parcelablePolicy.allowedFeatures = new ArrayList<>(policy.mAllowedFeatures);
3587             return parcelablePolicy;
3588         }
3589 
3590         /** @hide */
fromParcelable( IPowerManager.LowPowerStandbyPolicy parcelablePolicy)3591         public static LowPowerStandbyPolicy fromParcelable(
3592                 IPowerManager.LowPowerStandbyPolicy parcelablePolicy) {
3593             if (parcelablePolicy == null) {
3594                 return null;
3595             }
3596 
3597             return new LowPowerStandbyPolicy(
3598                     parcelablePolicy.identifier,
3599                     new ArraySet<>(parcelablePolicy.exemptPackages),
3600                     parcelablePolicy.allowedReasons,
3601                     new ArraySet<>(parcelablePolicy.allowedFeatures));
3602         }
3603     }
3604 
3605     /**
3606      * Describes ports that may be requested to remain open during Low Power Standby.
3607      *
3608      * @hide
3609      */
3610     @SystemApi
3611     public static final class LowPowerStandbyPortDescription {
3612         /** @hide */
3613         @IntDef(prefix = { "PROTOCOL_" }, value = {
3614                 PROTOCOL_TCP,
3615                 PROTOCOL_UDP,
3616         })
3617         @Retention(RetentionPolicy.SOURCE)
3618         public @interface Protocol {
3619         }
3620 
3621         /**
3622          * Constant to indicate the {@link LowPowerStandbyPortDescription} refers to a TCP port.
3623          */
3624         public static final int PROTOCOL_TCP = 6;
3625         /**
3626          * Constant to indicate the {@link LowPowerStandbyPortDescription} refers to a UDP port.
3627          */
3628         public static final int PROTOCOL_UDP = 17;
3629 
3630         /** @hide */
3631         @IntDef(prefix = { "MATCH_PORT_" }, value = {
3632                 MATCH_PORT_LOCAL,
3633                 MATCH_PORT_REMOTE,
3634         })
3635         @Retention(RetentionPolicy.SOURCE)
3636         public @interface PortMatcher {
3637         }
3638         /**
3639          * Constant to indicate the {@link LowPowerStandbyPortDescription}'s port number is to be
3640          * matched against the socket's local port number (the destination port number of an
3641          * incoming packet).
3642          */
3643         public static final int MATCH_PORT_LOCAL = 1;
3644         /**
3645          * Constant to indicate the {@link LowPowerStandbyPortDescription}'s port number is to be
3646          * matched against the socket's remote port number (the source port number of an
3647          * incoming packet).
3648          */
3649         public static final int MATCH_PORT_REMOTE = 2;
3650 
3651         @Protocol
3652         private final int mProtocol;
3653         @PortMatcher
3654         private final int mPortMatcher;
3655         private final int mPortNumber;
3656         @Nullable
3657         private final InetAddress mLocalAddress;
3658 
3659         /**
3660          * Describes a port.
3661          *
3662          * @param protocol The protocol of the port to match, {@link #PROTOCOL_TCP} or
3663          *                 {@link #PROTOCOL_UDP}.
3664          * @param portMatcher Whether to match the source port number of an incoming packet
3665          *                    ({@link #MATCH_PORT_REMOTE}), or the destination port
3666          *                    ({@link #MATCH_PORT_LOCAL}).
3667          * @param portNumber The port number to match.
3668          *
3669          * @see #newLowPowerStandbyPortsLock(List)
3670          */
LowPowerStandbyPortDescription(@rotocol int protocol, @PortMatcher int portMatcher, int portNumber)3671         public LowPowerStandbyPortDescription(@Protocol int protocol, @PortMatcher int portMatcher,
3672                 int portNumber) {
3673             this.mProtocol = protocol;
3674             this.mPortMatcher = portMatcher;
3675             this.mPortNumber = portNumber;
3676             this.mLocalAddress = null;
3677         }
3678 
3679         /**
3680          * Describes a port.
3681          *
3682          * @param protocol The protocol of the port to match, {@link #PROTOCOL_TCP} or
3683          *                 {@link #PROTOCOL_UDP}.
3684          * @param portMatcher Whether to match the source port number of an incoming packet
3685          *                    ({@link #MATCH_PORT_REMOTE}), or the destination port
3686          *                    ({@link #MATCH_PORT_LOCAL}).
3687          * @param portNumber The port number to match.
3688          * @param localAddress The local address to match.
3689          *
3690          * @see #newLowPowerStandbyPortsLock(List)
3691          */
LowPowerStandbyPortDescription(@rotocol int protocol, @PortMatcher int portMatcher, int portNumber, @Nullable InetAddress localAddress)3692         public LowPowerStandbyPortDescription(@Protocol int protocol, @PortMatcher int portMatcher,
3693                 int portNumber, @Nullable InetAddress localAddress) {
3694             this.mProtocol = protocol;
3695             this.mPortMatcher = portMatcher;
3696             this.mPortNumber = portNumber;
3697             this.mLocalAddress = localAddress;
3698         }
3699 
protocolToString(int protocol)3700         private String protocolToString(int protocol) {
3701             switch (protocol) {
3702                 case PROTOCOL_TCP: return "TCP";
3703                 case PROTOCOL_UDP: return "UDP";
3704             }
3705             return String.valueOf(protocol);
3706         }
3707 
portMatcherToString(int portMatcher)3708         private String portMatcherToString(int portMatcher) {
3709             switch (portMatcher) {
3710                 case MATCH_PORT_LOCAL: return "MATCH_PORT_LOCAL";
3711                 case MATCH_PORT_REMOTE: return "MATCH_PORT_REMOTE";
3712             }
3713             return String.valueOf(portMatcher);
3714         }
3715 
3716         /**
3717          * Returns the described port's protocol,
3718          * either {@link #PROTOCOL_TCP} or {@link #PROTOCOL_UDP}.
3719          *
3720          * @see #PROTOCOL_TCP
3721          * @see #PROTOCOL_UDP
3722          * @see #getPortNumber()
3723          * @see #getPortMatcher()
3724          */
3725         @Protocol
getProtocol()3726         public int getProtocol() {
3727             return mProtocol;
3728         }
3729 
3730         /**
3731          * Returns how the port number ({@link #getPortNumber()}) should be matched against
3732          * incoming packets.
3733          * Either {@link #PROTOCOL_TCP} or {@link #PROTOCOL_UDP}.
3734          *
3735          * @see #PROTOCOL_TCP
3736          * @see #PROTOCOL_UDP
3737          * @see #getPortNumber()
3738          * @see #getProtocol()
3739          */
3740         @PortMatcher
getPortMatcher()3741         public int getPortMatcher() {
3742             return mPortMatcher;
3743         }
3744 
3745         /**
3746          * Returns how the port number that incoming packets should be matched against.
3747          *
3748          * @see #getPortMatcher()
3749          * @see #getProtocol()
3750          */
getPortNumber()3751         public int getPortNumber() {
3752             return mPortNumber;
3753         }
3754 
3755         /**
3756          * Returns the bind address to match against, or {@code null} if matching against any
3757          * bind address.
3758          *
3759          * @see #getPortMatcher()
3760          * @see #getProtocol()
3761          */
3762         @Nullable
getLocalAddress()3763         public InetAddress getLocalAddress() {
3764             return mLocalAddress;
3765         }
3766 
3767         @Override
toString()3768         public String toString() {
3769             return "PortDescription{"
3770                     + "mProtocol=" + protocolToString(mProtocol)
3771                     + ", mPortMatcher=" + portMatcherToString(mPortMatcher)
3772                     + ", mPortNumber=" + mPortNumber
3773                     + ", mLocalAddress=" + mLocalAddress
3774                     + '}';
3775         }
3776 
3777         @Override
equals(Object o)3778         public boolean equals(Object o) {
3779             if (this == o) return true;
3780             if (!(o instanceof LowPowerStandbyPortDescription)) return false;
3781             LowPowerStandbyPortDescription that = (LowPowerStandbyPortDescription) o;
3782             return mProtocol == that.mProtocol && mPortMatcher == that.mPortMatcher
3783                     && mPortNumber == that.mPortNumber && Objects.equals(mLocalAddress,
3784                     that.mLocalAddress);
3785         }
3786 
3787         @Override
hashCode()3788         public int hashCode() {
3789             return Objects.hash(mProtocol, mPortMatcher, mPortNumber, mLocalAddress);
3790         }
3791 
3792         /** @hide */
toParcelable( LowPowerStandbyPortDescription portDescription)3793         public static IPowerManager.LowPowerStandbyPortDescription toParcelable(
3794                 LowPowerStandbyPortDescription portDescription) {
3795             if (portDescription == null) {
3796                 return null;
3797             }
3798 
3799             IPowerManager.LowPowerStandbyPortDescription parcelablePortDescription =
3800                     new IPowerManager.LowPowerStandbyPortDescription();
3801             parcelablePortDescription.protocol = portDescription.mProtocol;
3802             parcelablePortDescription.portMatcher = portDescription.mPortMatcher;
3803             parcelablePortDescription.portNumber = portDescription.mPortNumber;
3804             if (portDescription.mLocalAddress != null) {
3805                 parcelablePortDescription.localAddress = portDescription.mLocalAddress.getAddress();
3806             }
3807             return parcelablePortDescription;
3808         }
3809 
3810         /** @hide */
toParcelable( List<LowPowerStandbyPortDescription> portDescriptions)3811         public static List<IPowerManager.LowPowerStandbyPortDescription> toParcelable(
3812                 List<LowPowerStandbyPortDescription> portDescriptions) {
3813             if (portDescriptions == null) {
3814                 return null;
3815             }
3816 
3817             ArrayList<IPowerManager.LowPowerStandbyPortDescription> result = new ArrayList<>();
3818             for (LowPowerStandbyPortDescription port : portDescriptions) {
3819                 result.add(toParcelable(port));
3820             }
3821             return result;
3822         }
3823 
3824         /** @hide */
fromParcelable( IPowerManager.LowPowerStandbyPortDescription parcelablePortDescription)3825         public static LowPowerStandbyPortDescription fromParcelable(
3826                 IPowerManager.LowPowerStandbyPortDescription parcelablePortDescription) {
3827             if (parcelablePortDescription == null) {
3828                 return null;
3829             }
3830 
3831             InetAddress localAddress = null;
3832             if (parcelablePortDescription.localAddress != null) {
3833                 try {
3834                     localAddress = InetAddress.getByAddress(parcelablePortDescription.localAddress);
3835                 } catch (UnknownHostException e) {
3836                     Log.w(TAG, "Address has invalid length", e);
3837                 }
3838             }
3839             return new LowPowerStandbyPortDescription(
3840                     parcelablePortDescription.protocol,
3841                     parcelablePortDescription.portMatcher,
3842                     parcelablePortDescription.portNumber,
3843                     localAddress);
3844         }
3845 
3846         /** @hide */
fromParcelable( List<IPowerManager.LowPowerStandbyPortDescription> portDescriptions)3847         public static List<LowPowerStandbyPortDescription> fromParcelable(
3848                 List<IPowerManager.LowPowerStandbyPortDescription> portDescriptions) {
3849             if (portDescriptions == null) {
3850                 return null;
3851             }
3852 
3853             ArrayList<LowPowerStandbyPortDescription> result = new ArrayList<>();
3854             for (IPowerManager.LowPowerStandbyPortDescription port : portDescriptions) {
3855                 result.add(fromParcelable(port));
3856             }
3857             return result;
3858         }
3859     }
3860 
3861     /**
3862      * An object that can be used to request network ports to remain open during Low Power Standby.
3863      *
3864      * <p>Use {@link #newLowPowerStandbyPortsLock} to create a ports lock, and {@link #acquire()}
3865      * to request the ports to remain open. The request is only respected if the app requesting the
3866      * lock is exempt from Low Power Standby ({@link #isExemptFromLowPowerStandby()}).
3867      *
3868      * @hide
3869      */
3870     @SystemApi
3871     @SuppressLint("NotCloseable")
3872     public final class LowPowerStandbyPortsLock {
3873         private final IBinder mToken;
3874         private final List<LowPowerStandbyPortDescription> mPorts;
3875         private boolean mHeld;
3876 
LowPowerStandbyPortsLock(List<LowPowerStandbyPortDescription> ports)3877         LowPowerStandbyPortsLock(List<LowPowerStandbyPortDescription> ports) {
3878             mPorts = ports;
3879             mToken = new Binder();
3880         }
3881 
3882         /** Request the ports to remain open during standby. */
3883         @RequiresPermission(android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS)
acquire()3884         public void acquire() {
3885             synchronized (mToken) {
3886                 try {
3887                     mService.acquireLowPowerStandbyPorts(mToken,
3888                             LowPowerStandbyPortDescription.toParcelable(mPorts));
3889                     mHeld = true;
3890                 } catch (RemoteException e) {
3891                     throw e.rethrowFromSystemServer();
3892                 }
3893             }
3894         }
3895 
3896         /**
3897          * Release the request, allowing these ports to be blocked during standby.
3898          *
3899          * <p>Note: This lock is not reference counted, so calling this method will release the lock
3900          * regardless of how many times {@link #acquire()} has been called before.
3901          */
3902         @RequiresPermission(android.Manifest.permission.SET_LOW_POWER_STANDBY_PORTS)
release()3903         public void release() {
3904             synchronized (mToken) {
3905                 try {
3906                     mService.releaseLowPowerStandbyPorts(mToken);
3907                     mHeld = false;
3908                 } catch (RemoteException e) {
3909                     throw e.rethrowFromSystemServer();
3910                 }
3911             }
3912         }
3913 
3914         @Override
finalize()3915         protected void finalize() {
3916             synchronized (mToken) {
3917                 if (mHeld) {
3918                     Log.wtf(TAG, "LowPowerStandbyPorts finalized while still held");
3919                     release();
3920                 }
3921             }
3922         }
3923     }
3924 
3925     /**
3926      * A listener interface to get notified when the wakelock is enabled/disabled.
3927      */
3928     public interface WakeLockStateListener {
3929         /**
3930          * Frameworks could disable the wakelock because either device's power allowlist has
3931          * changed, or the app's wakelock has exceeded its quota, or the app goes into cached
3932          * state.
3933          * <p>
3934          * This callback is called whenever the wakelock's state has changed.
3935          * </p>
3936          *
3937          * @param enabled true is enabled, false is disabled.
3938          */
onStateChanged(boolean enabled)3939         void onStateChanged(boolean enabled);
3940     }
3941 
3942     /**
3943      * Listener for screen timeout policy changes
3944      * @see PowerManager#addScreenTimeoutPolicyListener(int, ScreenTimeoutPolicyListener)
3945      * @hide
3946      */
3947     public interface ScreenTimeoutPolicyListener {
3948         /**
3949          * Invoked on changes in screen timeout policy.
3950          *
3951          * @param screenTimeoutPolicy Screen timeout policy, one of {@link ScreenTimeoutPolicy}
3952          * @see PowerManager#addScreenTimeoutPolicyListener
3953          */
onScreenTimeoutPolicyChanged(@creenTimeoutPolicy int screenTimeoutPolicy)3954         void onScreenTimeoutPolicyChanged(@ScreenTimeoutPolicy int screenTimeoutPolicy);
3955     }
3956 
3957     /**
3958      * A wake lock is a mechanism to indicate that your application needs
3959      * to have the device stay on.
3960      * <p>
3961      * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
3962      * permission in an {@code <uses-permission>} element of the application's manifest.
3963      * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
3964      * </p><p>
3965      * Call {@link #acquire()} to acquire the wake lock and force the device to stay
3966      * on at the level that was requested when the wake lock was created.
3967      * </p><p>
3968      * Call {@link #release()} when you are done and don't need the lock anymore.
3969      * It is very important to do this as soon as possible to avoid running down the
3970      * device's battery excessively.
3971      * </p>
3972      */
3973     public final class WakeLock {
3974         @UnsupportedAppUsage
3975         private int mFlags;
3976         @UnsupportedAppUsage
3977         private String mTag;
3978         private int mTagHash;
3979         private final String mPackageName;
3980         private final IBinder mToken;
3981         private int mInternalCount;
3982         private int mExternalCount;
3983         private boolean mRefCounted = true;
3984         private boolean mHeld;
3985         private WorkSource mWorkSource;
3986         private String mHistoryTag;
3987         private final int mDisplayId;
3988         private WakeLockStateListener mListener;
3989         private IWakeLockCallback mCallback;
3990 
3991         private final Runnable mReleaser = () -> release(RELEASE_FLAG_TIMEOUT);
3992 
WakeLock(int flags, String tag, String packageName, int displayId)3993         WakeLock(int flags, String tag, String packageName, int displayId) {
3994             mFlags = flags;
3995             mTag = tag;
3996             mTagHash = mTag.hashCode();
3997             mPackageName = packageName;
3998             mToken = new Binder();
3999             mDisplayId = displayId;
4000         }
4001 
4002         @Override
finalize()4003         protected void finalize() throws Throwable {
4004             synchronized (mToken) {
4005                 if (mHeld) {
4006                     Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
4007                     Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_POWER,
4008                             "WakeLocks", mTagHash);
4009                     try {
4010                         mService.releaseWakeLock(mToken, 0);
4011                     } catch (RemoteException e) {
4012                         throw e.rethrowFromSystemServer();
4013                     }
4014                 }
4015             }
4016         }
4017 
4018         /**
4019          * Sets whether this WakeLock is reference counted.
4020          * <p>
4021          * Wake locks are reference counted by default.  If a wake lock is
4022          * reference counted, then each call to {@link #acquire()} must be
4023          * balanced by an equal number of calls to {@link #release()}.  If a wake
4024          * lock is not reference counted, then one call to {@link #release()} is
4025          * sufficient to undo the effect of all previous calls to {@link #acquire()}.
4026          * </p>
4027          *
4028          * @param value True to make the wake lock reference counted, false to
4029          * make the wake lock non-reference counted.
4030          */
setReferenceCounted(boolean value)4031         public void setReferenceCounted(boolean value) {
4032             synchronized (mToken) {
4033                 mRefCounted = value;
4034             }
4035         }
4036 
4037         /**
4038          * Acquires the wake lock.
4039          * <p>
4040          * Ensures that the device is on at the level requested when
4041          * the wake lock was created.
4042          * </p>
4043          */
acquire()4044         public void acquire() {
4045             synchronized (mToken) {
4046                 acquireLocked();
4047             }
4048         }
4049 
4050         /**
4051          * Acquires the wake lock with a timeout.
4052          * <p>
4053          * Ensures that the device is on at the level requested when
4054          * the wake lock was created.  The lock will be released after the given timeout
4055          * expires.
4056          * </p>
4057          *
4058          * @param timeout The timeout after which to release the wake lock, in milliseconds.
4059          */
acquire(long timeout)4060         public void acquire(long timeout) {
4061             synchronized (mToken) {
4062                 acquireLocked();
4063                 mHandler.postDelayed(mReleaser, timeout);
4064             }
4065         }
4066 
acquireLocked()4067         private void acquireLocked() {
4068             mInternalCount++;
4069             mExternalCount++;
4070             if (!mRefCounted || mInternalCount == 1) {
4071                 // Do this even if the wake lock is already thought to be held (mHeld == true)
4072                 // because non-reference counted wake locks are not always properly released.
4073                 // For example, the keyguard's wake lock might be forcibly released by the
4074                 // power manager without the keyguard knowing.  A subsequent call to acquire
4075                 // should immediately acquire the wake lock once again despite never having
4076                 // been explicitly released by the keyguard.
4077                 mHandler.removeCallbacks(mReleaser);
4078                 Trace.asyncTraceForTrackBegin(Trace.TRACE_TAG_POWER,
4079                         "WakeLocks", mTag, mTagHash);
4080                 try {
4081                     mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
4082                             mHistoryTag, mDisplayId, mCallback);
4083                 } catch (RemoteException e) {
4084                     throw e.rethrowFromSystemServer();
4085                 }
4086                 mHeld = true;
4087             }
4088         }
4089 
4090         /**
4091          * Releases the wake lock.
4092          * <p>
4093          * This method releases your claim to the CPU or screen being on.
4094          * The screen may turn off shortly after you release the wake lock, or it may
4095          * not if there are other wake locks still held.
4096          * </p>
4097          */
release()4098         public void release() {
4099             release(0);
4100         }
4101 
4102         /**
4103          * Releases the wake lock with flags to modify the release behavior.
4104          * <p>
4105          * This method releases your claim to the CPU or screen being on.
4106          * The screen may turn off shortly after you release the wake lock, or it may
4107          * not if there are other wake locks still held.
4108          * </p>
4109          *
4110          * @param flags Combination of flag values to modify the release behavior.
4111          * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
4112          * Passing 0 is equivalent to calling {@link #release()}.
4113          */
release(int flags)4114         public void release(int flags) {
4115             synchronized (mToken) {
4116                 if (mInternalCount > 0) {
4117                     // internal count must only be decreased if it is > 0 or state of
4118                     // the WakeLock object is broken.
4119                     mInternalCount--;
4120                 }
4121                 if ((flags & RELEASE_FLAG_TIMEOUT) == 0) {
4122                     mExternalCount--;
4123                 }
4124                 if (!mRefCounted || mInternalCount == 0) {
4125                     mHandler.removeCallbacks(mReleaser);
4126                     if (mHeld) {
4127                         Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_POWER,
4128                                 "WakeLocks", mTagHash);
4129                         try {
4130                             mService.releaseWakeLock(mToken, flags);
4131                         } catch (RemoteException e) {
4132                             throw e.rethrowFromSystemServer();
4133                         }
4134                         mHeld = false;
4135                     }
4136                 }
4137                 if (mRefCounted && mExternalCount < 0) {
4138                     throw new RuntimeException("WakeLock under-locked " + mTag);
4139                 }
4140             }
4141         }
4142 
4143         /**
4144          * Returns true if the wake lock has been acquired but not yet released.
4145          *
4146          * @return True if the wake lock is held.
4147          */
isHeld()4148         public boolean isHeld() {
4149             synchronized (mToken) {
4150                 return mHeld;
4151             }
4152         }
4153 
4154         /**
4155          * Sets the work source associated with the wake lock.
4156          * <p>
4157          * The work source is used to determine on behalf of which application
4158          * the wake lock is being held.  This is useful in the case where a
4159          * service is performing work on behalf of an application so that the
4160          * cost of that work can be accounted to the application.
4161          * </p>
4162          *
4163          * <p>
4164          * Make sure to follow the tag naming convention when using WorkSource
4165          * to make it easier for app developers to understand wake locks
4166          * attributed to them. See {@link PowerManager#newWakeLock(int, String)}
4167          * documentation.
4168          * </p>
4169          *
4170          * @param ws The work source, or null if none.
4171          */
setWorkSource(WorkSource ws)4172         public void setWorkSource(WorkSource ws) {
4173             synchronized (mToken) {
4174                 if (ws != null && ws.isEmpty()) {
4175                     ws = null;
4176                 }
4177 
4178                 final boolean changed;
4179                 if (ws == null) {
4180                     changed = mWorkSource != null;
4181                     mWorkSource = null;
4182                 } else if (mWorkSource == null) {
4183                     changed = true;
4184                     mWorkSource = new WorkSource(ws);
4185                 } else {
4186                     changed = !mWorkSource.equals(ws);
4187                     if (changed) {
4188                         mWorkSource.set(ws);
4189                     }
4190                 }
4191 
4192                 if (changed && mHeld) {
4193                     try {
4194                         mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
4195                     } catch (RemoteException e) {
4196                         throw e.rethrowFromSystemServer();
4197                     }
4198                 }
4199             }
4200         }
4201 
4202         /** @hide */
setTag(String tag)4203         public void setTag(String tag) {
4204             mTag = tag;
4205             mTagHash = mTag.hashCode();
4206         }
4207 
4208         /** @hide */
getTag()4209         public String getTag() {
4210             return mTag;
4211         }
4212 
4213         /** @hide */
setHistoryTag(String tag)4214         public void setHistoryTag(String tag) {
4215             mHistoryTag = tag;
4216         }
4217 
4218         /** @hide */
setUnimportantForLogging(boolean state)4219         public void setUnimportantForLogging(boolean state) {
4220             if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
4221             else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
4222         }
4223 
4224         /** @hide */
updateUids(int[] uids)4225         public void updateUids(int[] uids) {
4226             synchronized (mToken) {
4227                 try {
4228                     mService.updateWakeLockUids(mToken, uids);
4229                 } catch (RemoteException e) {
4230                     throw e.rethrowFromSystemServer();
4231                 }
4232             }
4233         }
4234 
4235         @Override
toString()4236         public String toString() {
4237             synchronized (mToken) {
4238                 return "WakeLock{"
4239                     + Integer.toHexString(System.identityHashCode(this))
4240                     + " held=" + mHeld + ", refCount=" + mInternalCount + "}";
4241             }
4242         }
4243 
4244         /** @hide */
dumpDebug(ProtoOutputStream proto, long fieldId)4245         public void dumpDebug(ProtoOutputStream proto, long fieldId) {
4246             synchronized (mToken) {
4247                 final long token = proto.start(fieldId);
4248                 proto.write(PowerManagerProto.WakeLock.TAG, mTag);
4249                 proto.write(PowerManagerProto.WakeLock.PACKAGE_NAME, mPackageName);
4250                 proto.write(PowerManagerProto.WakeLock.HELD, mHeld);
4251                 proto.write(PowerManagerProto.WakeLock.INTERNAL_COUNT, mInternalCount);
4252                 if (mWorkSource != null) {
4253                     mWorkSource.dumpDebug(proto, PowerManagerProto.WakeLock.WORK_SOURCE);
4254                 }
4255                 proto.end(token);
4256             }
4257         }
4258 
4259         /**
4260          * Wraps a Runnable such that this method immediately acquires the wake lock and then
4261          * once the Runnable is done the wake lock is released.
4262          *
4263          * <p>Example:
4264          *
4265          * <pre>
4266          * mHandler.post(mWakeLock.wrap(() -> {
4267          *     // do things on handler, lock is held while we're waiting for this
4268          *     // to get scheduled and until the runnable is done executing.
4269          * });
4270          * </pre>
4271          *
4272          * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
4273          *    leak the wakelock!
4274          *
4275          * @hide
4276          */
4277         @SuppressLint("WakelockTimeout")
wrap(Runnable r)4278         public Runnable wrap(Runnable r) {
4279             acquire();
4280             return () -> {
4281                 try {
4282                     r.run();
4283                 } finally {
4284                     release();
4285                 }
4286             };
4287         }
4288 
4289         /**
4290          * Set the listener to get notified when the wakelock is enabled/disabled.
4291          *
4292          * @param executor {@link Executor} to handle listener callback.
4293          * @param listener listener to be added, set the listener to null to cancel a listener.
4294          */
setStateListener(@onNull @allbackExecutor Executor executor, @Nullable WakeLockStateListener listener)4295         public void setStateListener(@NonNull @CallbackExecutor Executor executor,
4296                 @Nullable WakeLockStateListener listener) {
4297             Preconditions.checkNotNull(executor, "executor cannot be null");
4298             synchronized (mToken) {
4299                 if (listener != mListener) {
4300                     mListener = listener;
4301                     if (listener != null) {
4302                         mCallback = new IWakeLockCallback.Stub() {
4303                             public void onStateChanged(boolean enabled) {
4304                                 final long token = Binder.clearCallingIdentity();
4305                                 try {
4306                                     executor.execute(() -> {
4307                                         listener.onStateChanged(enabled);
4308                                     });
4309                                 } finally {
4310                                     Binder.restoreCallingIdentity(token);
4311                                 }
4312                             }
4313                         };
4314                     } else {
4315                         mCallback = null;
4316                     }
4317                     if (mHeld) {
4318                         try {
4319                             mService.updateWakeLockCallback(mToken, mCallback);
4320                         } catch (RemoteException e) {
4321                             throw e.rethrowFromSystemServer();
4322                         }
4323                     }
4324                 }
4325             }
4326         }
4327     }
4328 
4329     /**
4330      * @hide
4331      */
4332     public static void invalidatePowerSaveModeCaches() {
4333         PropertyInvalidatedCache.invalidateCache(MODULE_SYSTEM, CACHE_KEY_IS_POWER_SAVE_MODE_API);
4334     }
4335 
4336     /**
4337      * @hide
4338      */
4339     public static void invalidateIsInteractiveCaches() {
4340         PropertyInvalidatedCache.invalidateCache(MODULE_SYSTEM, CACHE_KEY_IS_INTERACTIVE_API);
4341     }
4342 }
4343