blob: f18b4db6dc51dc532a9ef4bd41292515945b5ddf [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
Salvador Martinez812ea752018-10-19 13:03:20 -070019import android.Manifest.permission;
Wei Wang59476652018-11-29 16:02:48 -080020import android.annotation.CallbackExecutor;
Salvador Martineza6f7b252017-04-10 10:46:15 -070021import android.annotation.IntDef;
Wei Wang59476652018-11-29 16:02:48 -080022import android.annotation.NonNull;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060023import android.annotation.RequiresPermission;
Dianne Hackborneb94fa72014-06-03 17:48:12 -070024import android.annotation.SdkConstant;
Jeff Brown0a571122014-08-21 21:50:43 -070025import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060026import android.annotation.SystemService;
Dan Gittik26b030d2018-04-16 18:50:10 +010027import android.annotation.TestApi;
Andrei Onea24ec3212019-03-15 17:35:05 +000028import android.annotation.UnsupportedAppUsage;
Jeff Brown96307042012-07-27 15:51:34 -070029import android.content.Context;
Oleg Kibirev2385b5e2018-11-13 10:43:07 -080030import android.service.dreams.Sandman;
Wei Wang59476652018-11-29 16:02:48 -080031import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.util.Log;
Yi Jin148d7f42017-11-28 14:23:56 -080033import android.util.proto.ProtoOutputStream;
Julius D'souzab22da802017-06-09 10:27:14 -070034
Wei Wang59476652018-11-29 16:02:48 -080035import com.android.internal.util.Preconditions;
36
Salvador Martineza6f7b252017-04-10 10:46:15 -070037import java.lang.annotation.Retention;
38import java.lang.annotation.RetentionPolicy;
Wei Wang59476652018-11-29 16:02:48 -080039import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041/**
Jeff Brown1244cda2012-06-19 16:44:46 -070042 * This class gives you control of the power state of the device.
43 *
44 * <p>
45 * <b>Device battery life will be significantly affected by the use of this API.</b>
46 * Do not acquire {@link WakeLock}s unless you really need them, use the minimum levels
47 * possible, and be sure to release them as soon as possible.
48 * </p><p>
Jeff Brown1244cda2012-06-19 16:44:46 -070049 * The primary API you'll use is {@link #newWakeLock(int, String) newWakeLock()}.
50 * This will create a {@link PowerManager.WakeLock} object. You can then use methods
51 * on the wake lock object to control the power state of the device.
52 * </p><p>
53 * In practice it's quite simple:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 * {@samplecode
55 * PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
56 * PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
57 * wl.acquire();
58 * ..screen will stay on during this section..
59 * wl.release();
60 * }
Jeff Brown1244cda2012-06-19 16:44:46 -070061 * </p><p>
Jeff Brown96307042012-07-27 15:51:34 -070062 * The following wake lock levels are defined, with varying effects on system power.
63 * <i>These levels are mutually exclusive - you may only specify one of them.</i>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070065 * <table>
Santos Cordon3107d292016-09-20 15:50:35 -070066 * <tr><th>Flag Value</th>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <th>CPU</th> <th>Screen</th> <th>Keyboard</th></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070069 * <tr><td>{@link #PARTIAL_WAKE_LOCK}</td>
Santos Cordon3107d292016-09-20 15:50:35 -070070 * <td>On*</td> <td>Off</td> <td>Off</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * </tr>
Santos Cordon3107d292016-09-20 15:50:35 -070072 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070073 * <tr><td>{@link #SCREEN_DIM_WAKE_LOCK}</td>
Santos Cordon3107d292016-09-20 15:50:35 -070074 * <td>On</td> <td>Dim</td> <td>Off</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 * </tr>
76 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070077 * <tr><td>{@link #SCREEN_BRIGHT_WAKE_LOCK}</td>
Santos Cordon3107d292016-09-20 15:50:35 -070078 * <td>On</td> <td>Bright</td> <td>Off</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 * </tr>
Santos Cordon3107d292016-09-20 15:50:35 -070080 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070081 * <tr><td>{@link #FULL_WAKE_LOCK}</td>
Santos Cordon3107d292016-09-20 15:50:35 -070082 * <td>On</td> <td>Bright</td> <td>Bright</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * </tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * </table>
Jeff Brown1244cda2012-06-19 16:44:46 -070085 * </p><p>
86 * *<i>If you hold a partial wake lock, the CPU will continue to run, regardless of any
87 * display timeouts or the state of the screen and even after the user presses the power button.
88 * In all other wake locks, the CPU will run, but the user can still put the device to sleep
89 * using the power button.</i>
90 * </p><p>
91 * In addition, you can add two more flags, which affect behavior of the screen only.
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070092 * <i>These flags have no effect when combined with a {@link #PARTIAL_WAKE_LOCK}.</i></p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070094 * <table>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 * <tr><th>Flag Value</th> <th>Description</th></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -070097 * <tr><td>{@link #ACQUIRE_CAUSES_WAKEUP}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 * <td>Normal wake locks don't actually turn on the illumination. Instead, they cause
99 * the illumination to remain on once it turns on (e.g. from user activity). This flag
100 * will force the screen and/or keyboard to turn on immediately, when the WakeLock is
101 * acquired. A typical use would be for notifications which are important for the user to
Santos Cordon3107d292016-09-20 15:50:35 -0700102 * see immediately.</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 * </tr>
Santos Cordon3107d292016-09-20 15:50:35 -0700104 *
Dirk Dougherty7b9a2882012-10-28 12:07:08 -0700105 * <tr><td>{@link #ON_AFTER_RELEASE}</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * <td>If this flag is set, the user activity timer will be reset when the WakeLock is
Santos Cordon3107d292016-09-20 15:50:35 -0700107 * released, causing the illumination to remain on a bit longer. This can be used to
108 * reduce flicker if you are cycling between wake lock conditions.</td>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 * </tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 * </table>
Dirk Dougherty7b9a2882012-10-28 12:07:08 -0700111 * <p>
Kenny Rootd710fb52011-03-15 17:39:45 -0700112 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
Neil Fuller71fbb812015-11-30 09:51:33 +0000113 * permission in an {@code <uses-permission>} element of the application's manifest.
Jeff Brown1244cda2012-06-19 16:44:46 -0700114 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600116@SystemService(Context.POWER_SERVICE)
Jeff Brown1244cda2012-06-19 16:44:46 -0700117public final class PowerManager {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "PowerManager";
Jeff Brown1244cda2012-06-19 16:44:46 -0700119
Jeff Brown155fc702012-07-27 12:12:15 -0700120 /* NOTE: Wake lock levels were previously defined as a bit field, except that only a few
121 * combinations were actually supported so the bit field was removed. This explains
122 * why the numbering scheme is so odd. If adding a new wake lock level, any unused
Bookatz1a1b0462018-01-12 11:47:03 -0800123 * value (in frameworks/base/core/proto/android/os/enums.proto) can be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
126 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700127 * Wake lock level: Ensures that the CPU is running; the screen and keyboard
128 * backlight will be allowed to go off.
Jeff Brown155fc702012-07-27 12:12:15 -0700129 * <p>
130 * If the user presses the power button, then the screen will be turned off
131 * but the CPU will be kept on until all partial wake locks have been released.
Jeff Brown1244cda2012-06-19 16:44:46 -0700132 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 */
Bookatz1a1b0462018-01-12 11:47:03 -0800134 public static final int PARTIAL_WAKE_LOCK = OsProtoEnums.PARTIAL_WAKE_LOCK; // 0x00000001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 /**
Jeff Brown155fc702012-07-27 12:12:15 -0700137 * Wake lock level: Ensures that the screen is on (but may be dimmed);
Jeff Brown1244cda2012-06-19 16:44:46 -0700138 * the keyboard backlight will be allowed to go off.
Jeff Brown155fc702012-07-27 12:12:15 -0700139 * <p>
140 * If the user presses the power button, then the {@link #SCREEN_DIM_WAKE_LOCK} will be
141 * implicitly released by the system, causing both the screen and the CPU to be turned off.
142 * Contrast with {@link #PARTIAL_WAKE_LOCK}.
143 * </p>
Jeff Brown1244cda2012-06-19 16:44:46 -0700144 *
Dianne Hackborn9567a662011-04-19 18:44:03 -0700145 * @deprecated Most applications should use
146 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
147 * of this type of wake lock, as it will be correctly managed by the platform
148 * as the user moves between applications and doesn't require a special permission.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 */
Dianne Hackborn9567a662011-04-19 18:44:03 -0700150 @Deprecated
Bookatz1a1b0462018-01-12 11:47:03 -0800151 public static final int SCREEN_DIM_WAKE_LOCK = OsProtoEnums.SCREEN_DIM_WAKE_LOCK; // 0x00000006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
153 /**
Jeff Brown155fc702012-07-27 12:12:15 -0700154 * Wake lock level: Ensures that the screen is on at full brightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 * the keyboard backlight will be allowed to go off.
Jeff Brown155fc702012-07-27 12:12:15 -0700156 * <p>
157 * If the user presses the power button, then the {@link #SCREEN_BRIGHT_WAKE_LOCK} will be
158 * implicitly released by the system, causing both the screen and the CPU to be turned off.
159 * Contrast with {@link #PARTIAL_WAKE_LOCK}.
160 * </p>
161 *
162 * @deprecated Most applications should use
163 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
164 * of this type of wake lock, as it will be correctly managed by the platform
165 * as the user moves between applications and doesn't require a special permission.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 */
Jeff Brown155fc702012-07-27 12:12:15 -0700167 @Deprecated
Bookatz1a1b0462018-01-12 11:47:03 -0800168 public static final int SCREEN_BRIGHT_WAKE_LOCK =
169 OsProtoEnums.SCREEN_BRIGHT_WAKE_LOCK; // 0x0000000a
Jeff Brown155fc702012-07-27 12:12:15 -0700170
171 /**
172 * Wake lock level: Ensures that the screen and keyboard backlight are on at
173 * full brightness.
174 * <p>
175 * If the user presses the power button, then the {@link #FULL_WAKE_LOCK} will be
176 * implicitly released by the system, causing both the screen and the CPU to be turned off.
177 * Contrast with {@link #PARTIAL_WAKE_LOCK}.
178 * </p>
179 *
180 * @deprecated Most applications should use
181 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead
182 * of this type of wake lock, as it will be correctly managed by the platform
183 * as the user moves between applications and doesn't require a special permission.
184 */
185 @Deprecated
Bookatz1a1b0462018-01-12 11:47:03 -0800186 public static final int FULL_WAKE_LOCK = OsProtoEnums.FULL_WAKE_LOCK; // 0x0000001a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700189 * Wake lock level: Turns the screen off when the proximity sensor activates.
190 * <p>
Jeff Brown93cbbb22012-10-04 13:18:36 -0700191 * If the proximity sensor detects that an object is nearby, the screen turns off
192 * immediately. Shortly after the object moves away, the screen turns on again.
193 * </p><p>
194 * A proximity wake lock does not prevent the device from falling asleep
195 * unlike {@link #FULL_WAKE_LOCK}, {@link #SCREEN_BRIGHT_WAKE_LOCK} and
196 * {@link #SCREEN_DIM_WAKE_LOCK}. If there is no user activity and no other
197 * wake locks are held, then the device will fall asleep (and lock) as usual.
198 * However, the device will not fall asleep while the screen has been turned off
199 * by the proximity sensor because it effectively counts as ongoing user activity.
200 * </p><p>
Jeff Brown96307042012-07-27 15:51:34 -0700201 * Since not all devices have proximity sensors, use {@link #isWakeLockLevelSupported}
Jeff Brown1244cda2012-06-19 16:44:46 -0700202 * to determine whether this wake lock level is supported.
Craig Mautner6edb6db2012-11-20 18:21:12 -0800203 * </p><p>
204 * Cannot be used with {@link #ACQUIRE_CAUSES_WAKEUP}.
Jeff Brown1244cda2012-06-19 16:44:46 -0700205 * </p>
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700206 */
Bookatz1a1b0462018-01-12 11:47:03 -0800207 public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK =
208 OsProtoEnums.PROXIMITY_SCREEN_OFF_WAKE_LOCK; // 0x00000020
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700209
210 /**
Jeff Brown26875502014-01-30 21:47:47 -0800211 * Wake lock level: Put the screen in a low power state and allow the CPU to suspend
212 * if no other wake locks are held.
213 * <p>
214 * This is used by the dream manager to implement doze mode. It currently
215 * has no effect unless the power manager is in the dozing state.
Jeff Brown72671fb2014-08-21 21:41:09 -0700216 * </p><p>
217 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
Jeff Brown26875502014-01-30 21:47:47 -0800218 * </p>
219 *
220 * {@hide}
221 */
Bookatz1a1b0462018-01-12 11:47:03 -0800222 public static final int DOZE_WAKE_LOCK = OsProtoEnums.DOZE_WAKE_LOCK; // 0x00000040
Jeff Brown26875502014-01-30 21:47:47 -0800223
224 /**
Jeff Brownc2932a12014-11-20 18:04:05 -0800225 * Wake lock level: Keep the device awake enough to allow drawing to occur.
226 * <p>
227 * This is used by the window manager to allow applications to draw while the
228 * system is dozing. It currently has no effect unless the power manager is in
229 * the dozing state.
230 * </p><p>
231 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
232 * </p>
233 *
234 * {@hide}
235 */
Bookatz1a1b0462018-01-12 11:47:03 -0800236 public static final int DRAW_WAKE_LOCK = OsProtoEnums.DRAW_WAKE_LOCK; // 0x00000080
Jeff Brownc2932a12014-11-20 18:04:05 -0800237
238 /**
Jeff Brown155fc702012-07-27 12:12:15 -0700239 * Mask for the wake lock level component of a combined wake lock level and flags integer.
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500240 *
Jeff Brown155fc702012-07-27 12:12:15 -0700241 * @hide
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500242 */
Jeff Brown155fc702012-07-27 12:12:15 -0700243 public static final int WAKE_LOCK_LEVEL_MASK = 0x0000ffff;
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500244
245 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700246 * Wake lock flag: Turn the screen on when the wake lock is acquired.
247 * <p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 * Normally wake locks don't actually wake the device, they just cause
Jeff Brown1244cda2012-06-19 16:44:46 -0700249 * the screen to remain on once it's already on. Think of the video player
250 * application as the normal behavior. Notifications that pop up and want
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 * the device to be on are the exception; use this flag to be like them.
Jeff Brown1244cda2012-06-19 16:44:46 -0700252 * </p><p>
253 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
254 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 */
Jeff Brown155fc702012-07-27 12:12:15 -0700256 public static final int ACQUIRE_CAUSES_WAKEUP = 0x10000000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257
258 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700259 * Wake lock flag: When this wake lock is released, poke the user activity timer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 * so the screen stays on for a little longer.
261 * <p>
Jeff Brown1244cda2012-06-19 16:44:46 -0700262 * Will not turn the screen on if it is not already on.
263 * See {@link #ACQUIRE_CAUSES_WAKEUP} if you want that.
264 * </p><p>
265 * Cannot be used with {@link #PARTIAL_WAKE_LOCK}.
266 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 */
Jeff Brown155fc702012-07-27 12:12:15 -0700268 public static final int ON_AFTER_RELEASE = 0x20000000;
269
270 /**
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800271 * Wake lock flag: This wake lock is not important for logging events. If a later
272 * wake lock is acquired that is important, it will be considered the one to log.
273 * @hide
274 */
275 public static final int UNIMPORTANT_FOR_LOGGING = 0x40000000;
276
277 /**
Jeff Browna71f03c2014-08-21 18:01:51 -0700278 * Flag for {@link WakeLock#release WakeLock.release(int)}: Defer releasing a
279 * {@link #PROXIMITY_SCREEN_OFF_WAKE_LOCK} wake lock until the proximity sensor
280 * indicates that an object is not in close proximity.
Jeff Brown155fc702012-07-27 12:12:15 -0700281 */
Jeff Sharkey291c32a2017-07-05 12:34:04 -0600282 public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1 << 0;
283
284 /**
285 * Flag for {@link WakeLock#release(int)} when called due to timeout.
286 * @hide
287 */
288 public static final int RELEASE_FLAG_TIMEOUT = 1 << 16;
Jeff Brown7304c342012-05-11 18:42:42 -0700289
290 /**
Jeff Brown7304c342012-05-11 18:42:42 -0700291 * Brightness value for fully on.
292 * @hide
293 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000294 @UnsupportedAppUsage
Jeff Brown7304c342012-05-11 18:42:42 -0700295 public static final int BRIGHTNESS_ON = 255;
296
297 /**
Jeff Brown7304c342012-05-11 18:42:42 -0700298 * Brightness value for fully off.
299 * @hide
300 */
301 public static final int BRIGHTNESS_OFF = 0;
302
Jeff Brown970d4132014-07-19 11:33:47 -0700303 /**
304 * Brightness value for default policy handling by the system.
305 * @hide
306 */
307 public static final int BRIGHTNESS_DEFAULT = -1;
308
Jeff Brownb696de52012-07-27 15:38:50 -0700309 // Note: Be sure to update android.os.BatteryStats and PowerManager.h
310 // if adding or modifying user activity event constants.
311
312 /**
313 * User activity event type: Unspecified event type.
314 * @hide
315 */
Jeff Brown0a571122014-08-21 21:50:43 -0700316 @SystemApi
Jeff Brownb696de52012-07-27 15:38:50 -0700317 public static final int USER_ACTIVITY_EVENT_OTHER = 0;
318
319 /**
320 * User activity event type: Button or key pressed or released.
321 * @hide
322 */
Jeff Brown0a571122014-08-21 21:50:43 -0700323 @SystemApi
Jeff Brownb696de52012-07-27 15:38:50 -0700324 public static final int USER_ACTIVITY_EVENT_BUTTON = 1;
325
326 /**
327 * User activity event type: Touch down, move or up.
328 * @hide
329 */
Jeff Brown0a571122014-08-21 21:50:43 -0700330 @SystemApi
Jeff Brownb696de52012-07-27 15:38:50 -0700331 public static final int USER_ACTIVITY_EVENT_TOUCH = 2;
332
Jeff Brown96307042012-07-27 15:51:34 -0700333 /**
Phil Weaverda80d672016-03-15 16:25:46 -0700334 * User activity event type: Accessibility taking action on behalf of user.
335 * @hide
336 */
337 @SystemApi
338 public static final int USER_ACTIVITY_EVENT_ACCESSIBILITY = 3;
339
340 /**
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800341 * User activity event type: {@link android.service.attention.AttentionService} taking action
342 * on behalf of user.
343 * @hide
344 */
345 public static final int USER_ACTIVITY_EVENT_ATTENTION = 4;
346
347 /**
Jeff Brown0a571122014-08-21 21:50:43 -0700348 * User activity flag: If already dimmed, extend the dim timeout
349 * but do not brighten. This flag is useful for keeping the screen on
350 * a little longer without causing a visible change such as when
351 * the power key is pressed.
Jeff Brown96307042012-07-27 15:51:34 -0700352 * @hide
353 */
Jeff Brown0a571122014-08-21 21:50:43 -0700354 @SystemApi
Jeff Brown96307042012-07-27 15:51:34 -0700355 public static final int USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS = 1 << 0;
356
357 /**
Jeff Brown0a571122014-08-21 21:50:43 -0700358 * User activity flag: Note the user activity as usual but do not
359 * reset the user activity timeout. This flag is useful for applying
360 * user activity power hints when interacting with the device indirectly
361 * on a secondary screen while allowing the primary screen to go to sleep.
362 * @hide
363 */
364 @SystemApi
365 public static final int USER_ACTIVITY_FLAG_INDIRECT = 1 << 1;
366
367 /**
Santos Cordon12f92eb2019-02-01 21:28:47 +0000368 * @hide
369 */
370 public static final int GO_TO_SLEEP_REASON_MIN = 0;
371
372 /**
Jeff Brownc12035c2014-08-13 18:52:25 -0700373 * Go to sleep reason code: Going to sleep due by application request.
Jeff Brown96307042012-07-27 15:51:34 -0700374 * @hide
375 */
Santos Cordon12f92eb2019-02-01 21:28:47 +0000376 public static final int GO_TO_SLEEP_REASON_APPLICATION = GO_TO_SLEEP_REASON_MIN;
Jeff Brown96307042012-07-27 15:51:34 -0700377
378 /**
379 * Go to sleep reason code: Going to sleep due by request of the
380 * device administration policy.
381 * @hide
382 */
383 public static final int GO_TO_SLEEP_REASON_DEVICE_ADMIN = 1;
384
385 /**
386 * Go to sleep reason code: Going to sleep due to a screen timeout.
387 * @hide
388 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000389 @UnsupportedAppUsage
Jeff Brown96307042012-07-27 15:51:34 -0700390 public static final int GO_TO_SLEEP_REASON_TIMEOUT = 2;
391
Doug Zongker3b0218b2014-01-14 12:29:06 -0800392 /**
Jeff Brownc12035c2014-08-13 18:52:25 -0700393 * Go to sleep reason code: Going to sleep due to the lid switch being closed.
394 * @hide
395 */
396 public static final int GO_TO_SLEEP_REASON_LID_SWITCH = 3;
397
398 /**
399 * Go to sleep reason code: Going to sleep due to the power button being pressed.
400 * @hide
401 */
402 public static final int GO_TO_SLEEP_REASON_POWER_BUTTON = 4;
403
404 /**
405 * Go to sleep reason code: Going to sleep due to HDMI.
406 * @hide
407 */
408 public static final int GO_TO_SLEEP_REASON_HDMI = 5;
409
410 /**
Filip Gruszczynski9779e122015-03-13 17:39:31 -0700411 * Go to sleep reason code: Going to sleep due to the sleep button being pressed.
412 * @hide
413 */
414 public static final int GO_TO_SLEEP_REASON_SLEEP_BUTTON = 6;
415
416 /**
Eugene Suslaf9a651d2017-10-11 12:06:27 -0700417 * Go to sleep reason code: Going to sleep by request of an accessibility service
418 * @hide
419 */
420 public static final int GO_TO_SLEEP_REASON_ACCESSIBILITY = 7;
421
422 /**
Santos Cordon12f92eb2019-02-01 21:28:47 +0000423 * Go to sleep reason code: Going to sleep due to force-suspend.
424 * @hide
425 */
426 public static final int GO_TO_SLEEP_REASON_FORCE_SUSPEND = 8;
427
428 /**
Robert Horvath5560f382019-07-10 10:46:38 +0200429 * Go to sleep reason code: Going to sleep due to user inattentiveness.
Santos Cordon12f92eb2019-02-01 21:28:47 +0000430 * @hide
431 */
Robert Horvath5560f382019-07-10 10:46:38 +0200432 public static final int GO_TO_SLEEP_REASON_INATTENTIVE = 9;
433
434 /**
435 * @hide
436 */
437 public static final int GO_TO_SLEEP_REASON_MAX = GO_TO_SLEEP_REASON_INATTENTIVE;
Santos Cordon12f92eb2019-02-01 21:28:47 +0000438
439 /**
Calin Tatarua3805722018-08-09 16:41:28 +0200440 * @hide
441 */
442 public static String sleepReasonToString(int sleepReason) {
443 switch (sleepReason) {
444 case GO_TO_SLEEP_REASON_APPLICATION: return "application";
445 case GO_TO_SLEEP_REASON_DEVICE_ADMIN: return "device_admin";
446 case GO_TO_SLEEP_REASON_TIMEOUT: return "timeout";
447 case GO_TO_SLEEP_REASON_LID_SWITCH: return "lid_switch";
448 case GO_TO_SLEEP_REASON_POWER_BUTTON: return "power_button";
449 case GO_TO_SLEEP_REASON_HDMI: return "hdmi";
450 case GO_TO_SLEEP_REASON_SLEEP_BUTTON: return "sleep_button";
451 case GO_TO_SLEEP_REASON_ACCESSIBILITY: return "accessibility";
Santos Cordon12f92eb2019-02-01 21:28:47 +0000452 case GO_TO_SLEEP_REASON_FORCE_SUSPEND: return "force_suspend";
Robert Horvath5560f382019-07-10 10:46:38 +0200453 case GO_TO_SLEEP_REASON_INATTENTIVE: return "inattentive";
Calin Tatarua3805722018-08-09 16:41:28 +0200454 default: return Integer.toString(sleepReason);
455 }
456 }
457
458 /**
Jeff Brown72671fb2014-08-21 21:41:09 -0700459 * Go to sleep flag: Skip dozing state and directly go to full sleep.
460 * @hide
461 */
462 public static final int GO_TO_SLEEP_FLAG_NO_DOZE = 1 << 0;
463
464 /**
Michael Wrighte3001042019-02-05 00:13:14 +0000465 * @hide
466 */
467 @IntDef(prefix = { "WAKE_REASON_" }, value = {
468 WAKE_REASON_UNKNOWN,
469 WAKE_REASON_POWER_BUTTON,
470 WAKE_REASON_APPLICATION,
471 WAKE_REASON_PLUGGED_IN,
472 WAKE_REASON_GESTURE,
473 WAKE_REASON_CAMERA_LAUNCH,
474 WAKE_REASON_WAKE_KEY,
475 WAKE_REASON_WAKE_MOTION,
476 WAKE_REASON_HDMI,
477 })
478 @Retention(RetentionPolicy.SOURCE)
479 public @interface WakeReason{}
480
481 /**
482 * Wake up reason code: Waking for an unknown reason.
483 * @hide
484 */
485 public static final int WAKE_REASON_UNKNOWN = 0;
486
487 /**
488 * Wake up reason code: Waking up due to power button press.
489 * @hide
490 */
491 public static final int WAKE_REASON_POWER_BUTTON = 1;
492
493 /**
494 * Wake up reason code: Waking up because an application requested it.
495 * @hide
496 */
497 public static final int WAKE_REASON_APPLICATION = 2;
498
499 /**
500 * Wake up reason code: Waking up due to being plugged in or docked on a wireless charger.
501 * @hide
502 */
503 public static final int WAKE_REASON_PLUGGED_IN = 3;
504
505 /**
506 * Wake up reason code: Waking up due to a user performed gesture (e.g. douple tapping on the
507 * screen).
508 * @hide
509 */
510 public static final int WAKE_REASON_GESTURE = 4;
511
512 /**
513 * Wake up reason code: Waking up due to the camera being launched.
514 * @hide
515 */
516 public static final int WAKE_REASON_CAMERA_LAUNCH = 5;
517
518 /**
519 * Wake up reason code: Waking up because a wake key other than power was pressed.
520 * @hide
521 */
522 public static final int WAKE_REASON_WAKE_KEY = 6;
523
524 /**
525 * Wake up reason code: Waking up because a wake motion was performed.
526 *
527 * For example, a trackball that was set to wake the device up was spun.
528 * @hide
529 */
530 public static final int WAKE_REASON_WAKE_MOTION = 7;
531
532 /**
533 * Wake up reason code: Waking due to HDMI.
534 * @hide
535 */
536 public static final int WAKE_REASON_HDMI = 8;
537
538 /**
539 * Wake up reason code: Waking due to the lid being opened.
540 * @hide
541 */
542 public static final int WAKE_REASON_LID = 9;
543
544 /**
545 * Convert the wake reason to a string for debugging purposes.
546 * @hide
547 */
548 public static String wakeReasonToString(@WakeReason int wakeReason) {
549 switch (wakeReason) {
550 case WAKE_REASON_UNKNOWN: return "WAKE_REASON_UNKNOWN";
551 case WAKE_REASON_POWER_BUTTON: return "WAKE_REASON_POWER_BUTTON";
552 case WAKE_REASON_APPLICATION: return "WAKE_REASON_APPLICATION";
553 case WAKE_REASON_PLUGGED_IN: return "WAKE_REASON_PLUGGED_IN";
554 case WAKE_REASON_GESTURE: return "WAKE_REASON_GESTURE";
555 case WAKE_REASON_CAMERA_LAUNCH: return "WAKE_REASON_CAMERA_LAUNCH";
556 case WAKE_REASON_WAKE_KEY: return "WAKE_REASON_WAKE_KEY";
557 case WAKE_REASON_WAKE_MOTION: return "WAKE_REASON_WAKE_MOTION";
558 case WAKE_REASON_HDMI: return "WAKE_REASON_HDMI";
559 case WAKE_REASON_LID: return "WAKE_REASON_LID";
560 default: return Integer.toString(wakeReason);
561 }
562 }
563
564 /**
Santos Cordon623526b2019-04-09 17:02:38 +0100565 * @hide
566 */
567 public static class WakeData {
568 public WakeData(long wakeTime, @WakeReason int wakeReason) {
569 this.wakeTime = wakeTime;
570 this.wakeReason = wakeReason;
571 }
572 public long wakeTime;
573 public @WakeReason int wakeReason;
574 }
575
576 /**
Tao Baoe8a403d2015-12-31 07:44:55 -0800577 * The value to pass as the 'reason' argument to reboot() to reboot into
578 * recovery mode for tasks other than applying system updates, such as
579 * doing factory resets.
Doug Zongker3b0218b2014-01-14 12:29:06 -0800580 * <p>
581 * Requires the {@link android.Manifest.permission#RECOVERY}
582 * permission (in addition to
583 * {@link android.Manifest.permission#REBOOT}).
584 * </p>
Doug Zongker183415e2014-08-12 10:18:40 -0700585 * @hide
Doug Zongker3b0218b2014-01-14 12:29:06 -0800586 */
587 public static final String REBOOT_RECOVERY = "recovery";
Yusuke Sato705ffd12015-07-21 15:52:11 -0700588
589 /**
Tao Baoe8a403d2015-12-31 07:44:55 -0800590 * The value to pass as the 'reason' argument to reboot() to reboot into
591 * recovery mode for applying system updates.
592 * <p>
593 * Requires the {@link android.Manifest.permission#RECOVERY}
594 * permission (in addition to
595 * {@link android.Manifest.permission#REBOOT}).
596 * </p>
597 * @hide
598 */
599 public static final String REBOOT_RECOVERY_UPDATE = "recovery-update";
600
601 /**
Mahaver Chopra1ce53bc2015-12-14 13:35:14 +0000602 * The value to pass as the 'reason' argument to reboot() when device owner requests a reboot on
603 * the device.
604 * @hide
605 */
606 public static final String REBOOT_REQUESTED_BY_DEVICE_OWNER = "deviceowner";
607
608 /**
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700609 * The 'reason' value used when rebooting in safe mode
610 * @hide
611 */
612 public static final String REBOOT_SAFE_MODE = "safemode";
613
614 /**
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800615 * The 'reason' value used when rebooting the device without turning on the screen.
616 * @hide
617 */
618 public static final String REBOOT_QUIESCENT = "quiescent";
619
620 /**
Yusuke Sato705ffd12015-07-21 15:52:11 -0700621 * The value to pass as the 'reason' argument to android_reboot().
622 * @hide
623 */
624 public static final String SHUTDOWN_USER_REQUESTED = "userrequested";
625
Salvador Martineza6f7b252017-04-10 10:46:15 -0700626 /**
Sudheer Shanka292637f2017-09-25 10:36:23 -0700627 * The value to pass as the 'reason' argument to android_reboot() when battery temperature
628 * is too high.
629 * @hide
630 */
631 public static final String SHUTDOWN_BATTERY_THERMAL_STATE = "thermal,battery";
632
633 /**
Wei Wangbad7c202018-11-01 11:57:39 -0700634 * The value to pass as the 'reason' argument to android_reboot() when device temperature
635 * is too high.
636 * @hide
637 */
638 public static final String SHUTDOWN_THERMAL_STATE = "thermal";
639
640 /**
Sudheer Shanka292637f2017-09-25 10:36:23 -0700641 * The value to pass as the 'reason' argument to android_reboot() when device is running
642 * critically low on battery.
643 * @hide
644 */
645 public static final String SHUTDOWN_LOW_BATTERY = "battery";
646
647 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -0700648 * @hide
649 */
650 @Retention(RetentionPolicy.SOURCE)
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700651 @IntDef(prefix = { "SHUTDOWN_REASON_" }, value = {
Salvador Martineza6f7b252017-04-10 10:46:15 -0700652 SHUTDOWN_REASON_UNKNOWN,
653 SHUTDOWN_REASON_SHUTDOWN,
654 SHUTDOWN_REASON_REBOOT,
655 SHUTDOWN_REASON_USER_REQUESTED,
Sudheer Shanka292637f2017-09-25 10:36:23 -0700656 SHUTDOWN_REASON_THERMAL_SHUTDOWN,
657 SHUTDOWN_REASON_LOW_BATTERY,
658 SHUTDOWN_REASON_BATTERY_THERMAL
Salvador Martineza6f7b252017-04-10 10:46:15 -0700659 })
660 public @interface ShutdownReason {}
661
662 /**
663 * constant for shutdown reason being unknown.
664 * @hide
665 */
666 public static final int SHUTDOWN_REASON_UNKNOWN = 0;
667
668 /**
669 * constant for shutdown reason being normal shutdown.
670 * @hide
671 */
672 public static final int SHUTDOWN_REASON_SHUTDOWN = 1;
673
674 /**
675 * constant for shutdown reason being reboot.
676 * @hide
677 */
678 public static final int SHUTDOWN_REASON_REBOOT = 2;
679
680 /**
681 * constant for shutdown reason being user requested.
682 * @hide
683 */
684 public static final int SHUTDOWN_REASON_USER_REQUESTED = 3;
685
686 /**
687 * constant for shutdown reason being overheating.
688 * @hide
689 */
690 public static final int SHUTDOWN_REASON_THERMAL_SHUTDOWN = 4;
691
Sudheer Shanka292637f2017-09-25 10:36:23 -0700692 /**
693 * constant for shutdown reason being low battery.
694 * @hide
695 */
696 public static final int SHUTDOWN_REASON_LOW_BATTERY = 5;
697
698 /**
699 * constant for shutdown reason being critical battery thermal state.
700 * @hide
701 */
702 public static final int SHUTDOWN_REASON_BATTERY_THERMAL = 6;
703
Makoto Onuki2eccd022017-11-01 13:44:23 -0700704 /**
705 * @hide
706 */
707 @Retention(RetentionPolicy.SOURCE)
Kweku Adams731a1032019-02-04 14:05:41 -0800708 @IntDef({ServiceType.LOCATION,
Makoto Onuki2eccd022017-11-01 13:44:23 -0700709 ServiceType.VIBRATION,
710 ServiceType.ANIMATION,
711 ServiceType.FULL_BACKUP,
712 ServiceType.KEYVALUE_BACKUP,
713 ServiceType.NETWORK_FIREWALL,
714 ServiceType.SCREEN_BRIGHTNESS,
715 ServiceType.SOUND,
716 ServiceType.BATTERY_STATS,
Makoto Onukiaae89532017-11-08 14:32:03 -0800717 ServiceType.DATA_SAVER,
Makoto Onuki9be01402017-11-10 13:22:26 -0800718 ServiceType.FORCE_ALL_APPS_STANDBY,
Kweku Adams27c65cc2019-02-28 15:32:31 -0800719 ServiceType.FORCE_BACKGROUND_CHECK,
Makoto Onukiaae89532017-11-08 14:32:03 -0800720 ServiceType.OPTIONAL_SENSORS,
Lucas Dupin92a62e52018-01-30 17:22:20 -0800721 ServiceType.AOD,
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700722 ServiceType.QUICK_DOZE,
Kweku Adams27c65cc2019-02-28 15:32:31 -0800723 ServiceType.NIGHT_MODE,
Makoto Onukiaae89532017-11-08 14:32:03 -0800724 })
Makoto Onuki2eccd022017-11-01 13:44:23 -0700725 public @interface ServiceType {
726 int NULL = 0;
Kweku Adams731a1032019-02-04 14:05:41 -0800727 int LOCATION = 1;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700728 int VIBRATION = 2;
729 int ANIMATION = 3;
730 int FULL_BACKUP = 4;
731 int KEYVALUE_BACKUP = 5;
732 int NETWORK_FIREWALL = 6;
733 int SCREEN_BRIGHTNESS = 7;
734 int SOUND = 8;
735 int BATTERY_STATS = 9;
736 int DATA_SAVER = 10;
Lucas Dupin92a62e52018-01-30 17:22:20 -0800737 int AOD = 14;
Makoto Onukiaae89532017-11-08 14:32:03 -0800738
739 /**
Makoto Onuki9be01402017-11-10 13:22:26 -0800740 * Whether to enable force-app-standby on all apps or not.
Makoto Onukiaae89532017-11-08 14:32:03 -0800741 */
Makoto Onuki9be01402017-11-10 13:22:26 -0800742 int FORCE_ALL_APPS_STANDBY = 11;
Makoto Onukiaae89532017-11-08 14:32:03 -0800743
744 /**
Makoto Onukie7ec72a2017-11-22 11:16:30 -0800745 * Whether to enable background check on all apps or not.
746 */
747 int FORCE_BACKGROUND_CHECK = 12;
748
749 /**
Makoto Onukiaae89532017-11-08 14:32:03 -0800750 * Whether to disable non-essential sensors. (e.g. edge sensors.)
751 */
752 int OPTIONAL_SENSORS = 13;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700753
754 /**
755 * Whether to go into Deep Doze as soon as the screen turns off or not.
756 */
757 int QUICK_DOZE = 15;
Kweku Adams4db6a3c2019-02-04 16:06:13 -0800758
759 /**
760 * Whether to enable night mode when battery saver is enabled.
761 */
762 int NIGHT_MODE = 16;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700763 }
764
Makoto Onuki57f0f552017-12-11 12:22:18 -0800765 /**
766 * Either the location providers shouldn't be affected by battery saver,
767 * or battery saver is off.
768 */
769 public static final int LOCATION_MODE_NO_CHANGE = 0;
770
771 /**
772 * In this mode, the GPS based location provider should be disabled when battery saver is on and
773 * the device is non-interactive.
774 */
775 public static final int LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF = 1;
776
777 /**
778 * All location providers should be disabled when battery saver is on and
779 * the device is non-interactive.
780 */
781 public static final int LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF = 2;
782
783 /**
784 * In this mode, all the location providers will be kept available, but location fixes
785 * should only be provided to foreground apps.
786 */
787 public static final int LOCATION_MODE_FOREGROUND_ONLY = 3;
788
Kweku Adams4fb074e2019-02-01 16:03:27 -0800789 /**
790 * In this mode, location will not be turned off, but LocationManager will throttle all
791 * requests to providers when the device is non-interactive.
792 */
793 public static final int LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF = 4;
794
Kweku Adamsc1d844a2019-03-28 16:05:00 -0700795 /** @hide */
796 public static final int MIN_LOCATION_MODE = LOCATION_MODE_NO_CHANGE;
797 /** @hide */
798 public static final int MAX_LOCATION_MODE = LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF;
Kweku Adams9f488e22019-01-14 16:25:08 -0800799
Makoto Onuki57f0f552017-12-11 12:22:18 -0800800 /**
801 * @hide
802 */
803 @Retention(RetentionPolicy.SOURCE)
804 @IntDef(prefix = {"LOCATION_MODE_"}, value = {
805 LOCATION_MODE_NO_CHANGE,
806 LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF,
807 LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF,
808 LOCATION_MODE_FOREGROUND_ONLY,
Kweku Adams4fb074e2019-02-01 16:03:27 -0800809 LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF,
Makoto Onuki57f0f552017-12-11 12:22:18 -0800810 })
811 public @interface LocationPowerSaveMode {}
812
Kweku Adams4fb074e2019-02-01 16:03:27 -0800813 /** @hide */
814 public static String locationPowerSaveModeToString(@LocationPowerSaveMode int mode) {
815 switch (mode) {
816 case LOCATION_MODE_NO_CHANGE:
817 return "NO_CHANGE";
818 case LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF:
819 return "GPS_DISABLED_WHEN_SCREEN_OFF";
820 case LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF:
821 return "ALL_DISABLED_WHEN_SCREEN_OFF";
822 case LOCATION_MODE_FOREGROUND_ONLY:
823 return "FOREGROUND_ONLY";
824 case LOCATION_MODE_THROTTLE_REQUESTS_WHEN_SCREEN_OFF:
825 return "THROTTLE_REQUESTS_WHEN_SCREEN_OFF";
826 default:
827 return Integer.toString(mode);
828 }
829 }
830
Jeff Brown96307042012-07-27 15:51:34 -0700831 final Context mContext;
Andrei Onea24ec3212019-03-15 17:35:05 +0000832 @UnsupportedAppUsage
Jeff Brown1244cda2012-06-19 16:44:46 -0700833 final IPowerManager mService;
Artur Satayev70507ed2019-07-29 13:18:27 +0100834 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
Jeff Brown1244cda2012-06-19 16:44:46 -0700835 final Handler mHandler;
836
Makoto Onuki152742f2019-10-31 17:22:26 -0700837 /** We lazily initialize it.*/
838 private DeviceIdleManager mDeviceIdleManager;
839
Wei Wang59476652018-11-29 16:02:48 -0800840 IThermalService mThermalService;
Wei Wang7a49ff62019-03-04 21:13:32 -0800841 private final ArrayMap<OnThermalStatusChangedListener, IThermalStatusListener>
842 mListenerMap = new ArrayMap<>();
Wei Wang59476652018-11-29 16:02:48 -0800843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700845 * {@hide}
846 */
Jeff Brown96307042012-07-27 15:51:34 -0700847 public PowerManager(Context context, IPowerManager service, Handler handler) {
848 mContext = context;
Jeff Brown1244cda2012-06-19 16:44:46 -0700849 mService = service;
850 mHandler = handler;
851 }
852
Makoto Onuki152742f2019-10-31 17:22:26 -0700853 private DeviceIdleManager getDeviceIdleManager() {
854 if (mDeviceIdleManager == null) {
855 // No need for synchronization; getSystemService() will return the same object anyway.
856 mDeviceIdleManager = mContext.getSystemService(DeviceIdleManager.class);
857 }
858 return mDeviceIdleManager;
859 }
860
Jeff Brown1244cda2012-06-19 16:44:46 -0700861 /**
Jeff Brown96307042012-07-27 15:51:34 -0700862 * Gets the minimum supported screen brightness setting.
863 * The screen may be allowed to become dimmer than this value but
864 * this is the minimum value that can be set by the user.
865 * @hide
866 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000867 @UnsupportedAppUsage
Jeff Brown96307042012-07-27 15:51:34 -0700868 public int getMinimumScreenBrightnessSetting() {
869 return mContext.getResources().getInteger(
Jeff Brownf9bba132012-08-21 22:04:02 -0700870 com.android.internal.R.integer.config_screenBrightnessSettingMinimum);
Jeff Brown96307042012-07-27 15:51:34 -0700871 }
872
873 /**
874 * Gets the maximum supported screen brightness setting.
875 * The screen may be allowed to become dimmer than this value but
876 * this is the maximum value that can be set by the user.
877 * @hide
878 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000879 @UnsupportedAppUsage
Jeff Brown96307042012-07-27 15:51:34 -0700880 public int getMaximumScreenBrightnessSetting() {
Jeff Brownf9bba132012-08-21 22:04:02 -0700881 return mContext.getResources().getInteger(
882 com.android.internal.R.integer.config_screenBrightnessSettingMaximum);
Jeff Brown96307042012-07-27 15:51:34 -0700883 }
884
885 /**
886 * Gets the default screen brightness setting.
887 * @hide
888 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000889 @UnsupportedAppUsage
Jeff Brown96307042012-07-27 15:51:34 -0700890 public int getDefaultScreenBrightnessSetting() {
Jeff Brownf9bba132012-08-21 22:04:02 -0700891 return mContext.getResources().getInteger(
892 com.android.internal.R.integer.config_screenBrightnessSettingDefault);
Jeff Brown96307042012-07-27 15:51:34 -0700893 }
894
895 /**
Santos Cordon3107d292016-09-20 15:50:35 -0700896 * Gets the minimum supported screen brightness setting for VR Mode.
897 * @hide
898 */
899 public int getMinimumScreenBrightnessForVrSetting() {
900 return mContext.getResources().getInteger(
901 com.android.internal.R.integer.config_screenBrightnessForVrSettingMinimum);
902 }
903
904 /**
905 * Gets the maximum supported screen brightness setting for VR Mode.
906 * The screen may be allowed to become dimmer than this value but
907 * this is the maximum value that can be set by the user.
908 * @hide
909 */
910 public int getMaximumScreenBrightnessForVrSetting() {
911 return mContext.getResources().getInteger(
912 com.android.internal.R.integer.config_screenBrightnessForVrSettingMaximum);
913 }
914
915 /**
916 * Gets the default screen brightness for VR setting.
917 * @hide
918 */
919 public int getDefaultScreenBrightnessForVrSetting() {
920 return mContext.getResources().getInteger(
921 com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
922 }
923
924 /**
Jeff Brown1244cda2012-06-19 16:44:46 -0700925 * Creates a new wake lock with the specified level and flags.
Kenny Rootd710fb52011-03-15 17:39:45 -0700926 * <p>
Jeff Brown1244cda2012-06-19 16:44:46 -0700927 * The {@code levelAndFlags} parameter specifies a wake lock level and optional flags
928 * combined using the logical OR operator.
929 * </p><p>
930 * The wake lock levels are: {@link #PARTIAL_WAKE_LOCK},
931 * {@link #FULL_WAKE_LOCK}, {@link #SCREEN_DIM_WAKE_LOCK}
932 * and {@link #SCREEN_BRIGHT_WAKE_LOCK}. Exactly one wake lock level must be
933 * specified as part of the {@code levelAndFlags} parameter.
934 * </p><p>
935 * The wake lock flags are: {@link #ACQUIRE_CAUSES_WAKEUP}
936 * and {@link #ON_AFTER_RELEASE}. Multiple flags can be combined as part of the
937 * {@code levelAndFlags} parameters.
938 * </p><p>
939 * Call {@link WakeLock#acquire() acquire()} on the object to acquire the
940 * wake lock, and {@link WakeLock#release release()} when you are done.
941 * </p><p>
942 * {@samplecode
943 * PowerManager pm = (PowerManager)mContext.getSystemService(
944 * Context.POWER_SERVICE);
945 * PowerManager.WakeLock wl = pm.newWakeLock(
946 * PowerManager.SCREEN_DIM_WAKE_LOCK
947 * | PowerManager.ON_AFTER_RELEASE,
948 * TAG);
949 * wl.acquire();
950 * // ... do work...
951 * wl.release();
952 * }
953 * </p><p>
954 * Although a wake lock can be created without special permissions,
955 * the {@link android.Manifest.permission#WAKE_LOCK} permission is
956 * required to actually acquire or release the wake lock that is returned.
957 * </p><p class="note">
958 * If using this to keep the screen on, you should strongly consider using
959 * {@link android.view.WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON} instead.
960 * This window flag will be correctly managed by the platform
961 * as the user moves between applications and doesn't require a special permission.
962 * </p>
963 *
Olivier Gaillard24a0c132017-11-22 15:07:31 +0000964 * <p>
965 * Recommended naming conventions for tags to make debugging easier:
966 * <ul>
967 * <li>use a unique prefix delimited by a colon for your app/library (e.g.
968 * gmail:mytag) to make it easier to understand where the wake locks comes
969 * from. This namespace will also avoid collision for tags inside your app
970 * coming from different libraries which will make debugging easier.
971 * <li>use constants (e.g. do not include timestamps in the tag) to make it
972 * easier for tools to aggregate similar wake locks. When collecting
973 * debugging data, the platform only monitors a finite number of tags,
974 * using constants will help tools to provide better debugging data.
975 * <li>avoid using Class#getName() or similar method since this class name
976 * can be transformed by java optimizer and obfuscator tools.
977 * <li>avoid wrapping the tag or a prefix to avoid collision with wake lock
978 * tags from the platform (e.g. *alarm*).
979 * <li>never include personnally identifiable information for privacy
980 * reasons.
981 * </ul>
982 * </p>
983 *
Jeff Brown1244cda2012-06-19 16:44:46 -0700984 * @param levelAndFlags Combination of wake lock level and flag values defining
985 * the requested behavior of the WakeLock.
986 * @param tag Your class name (or other tag) for debugging purposes.
987 *
988 * @see WakeLock#acquire()
989 * @see WakeLock#release()
990 * @see #PARTIAL_WAKE_LOCK
991 * @see #FULL_WAKE_LOCK
992 * @see #SCREEN_DIM_WAKE_LOCK
993 * @see #SCREEN_BRIGHT_WAKE_LOCK
Jeff Browna71f03c2014-08-21 18:01:51 -0700994 * @see #PROXIMITY_SCREEN_OFF_WAKE_LOCK
Jeff Brown1244cda2012-06-19 16:44:46 -0700995 * @see #ACQUIRE_CAUSES_WAKEUP
996 * @see #ON_AFTER_RELEASE
997 */
998 public WakeLock newWakeLock(int levelAndFlags, String tag) {
Jeff Brown155fc702012-07-27 12:12:15 -0700999 validateWakeLockParameters(levelAndFlags, tag);
Dianne Hackborn95d78532013-09-11 09:51:14 -07001000 return new WakeLock(levelAndFlags, tag, mContext.getOpPackageName());
Jeff Brown155fc702012-07-27 12:12:15 -07001001 }
1002
1003 /** @hide */
Andrei Onea24ec3212019-03-15 17:35:05 +00001004 @UnsupportedAppUsage
Jeff Brown155fc702012-07-27 12:12:15 -07001005 public static void validateWakeLockParameters(int levelAndFlags, String tag) {
1006 switch (levelAndFlags & WAKE_LOCK_LEVEL_MASK) {
1007 case PARTIAL_WAKE_LOCK:
1008 case SCREEN_DIM_WAKE_LOCK:
1009 case SCREEN_BRIGHT_WAKE_LOCK:
1010 case FULL_WAKE_LOCK:
1011 case PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001012 case DOZE_WAKE_LOCK:
Jeff Brownc2932a12014-11-20 18:04:05 -08001013 case DRAW_WAKE_LOCK:
Jeff Brown155fc702012-07-27 12:12:15 -07001014 break;
1015 default:
1016 throw new IllegalArgumentException("Must specify a valid wake lock level.");
Jeff Brown1244cda2012-06-19 16:44:46 -07001017 }
1018 if (tag == null) {
1019 throw new IllegalArgumentException("The tag must not be null.");
1020 }
Jeff Brown1244cda2012-06-19 16:44:46 -07001021 }
1022
1023 /**
1024 * Notifies the power manager that user activity happened.
1025 * <p>
Jeff Brown96307042012-07-27 15:51:34 -07001026 * Resets the auto-off timer and brightens the screen if the device
1027 * is not asleep. This is what happens normally when a key or the touch
1028 * screen is pressed or when some other user activity occurs.
1029 * This method does not wake up the device if it has been put to sleep.
Jeff Brown1244cda2012-06-19 16:44:46 -07001030 * </p><p>
1031 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1032 * </p>
1033 *
1034 * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
Jeff Brown62c82e42012-09-26 01:30:41 -07001035 * time base. This timestamp is used to correctly order the user activity request with
Jeff Brown1244cda2012-06-19 16:44:46 -07001036 * other power management functions. It should be set
1037 * to the timestamp of the input event that caused the user activity.
1038 * @param noChangeLights If true, does not cause the keyboard backlight to turn on
1039 * because of this event. This is set when the power key is pressed.
1040 * We want the device to stay on while the button is down, but we're about
1041 * to turn off the screen so we don't want the keyboard backlight to turn on again.
1042 * Otherwise the lights flash on and then off and it looks weird.
Jeff Brown96307042012-07-27 15:51:34 -07001043 *
1044 * @see #wakeUp
1045 * @see #goToSleep
Jeff Brown7d827512014-08-21 21:56:02 -07001046 *
1047 * @removed Requires signature or system permission.
1048 * @deprecated Use {@link #userActivity(long, int, int)}.
Jeff Brown1244cda2012-06-19 16:44:46 -07001049 */
Jeff Brown7d827512014-08-21 21:56:02 -07001050 @Deprecated
Jeff Brown1244cda2012-06-19 16:44:46 -07001051 public void userActivity(long when, boolean noChangeLights) {
Jeff Brown0a571122014-08-21 21:50:43 -07001052 userActivity(when, USER_ACTIVITY_EVENT_OTHER,
1053 noChangeLights ? USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS : 0);
1054 }
1055
1056 /**
1057 * Notifies the power manager that user activity happened.
1058 * <p>
1059 * Resets the auto-off timer and brightens the screen if the device
1060 * is not asleep. This is what happens normally when a key or the touch
1061 * screen is pressed or when some other user activity occurs.
1062 * This method does not wake up the device if it has been put to sleep.
1063 * </p><p>
1064 * Requires the {@link android.Manifest.permission#DEVICE_POWER} or
1065 * {@link android.Manifest.permission#USER_ACTIVITY} permission.
1066 * </p>
1067 *
1068 * @param when The time of the user activity, in the {@link SystemClock#uptimeMillis()}
1069 * time base. This timestamp is used to correctly order the user activity request with
1070 * other power management functions. It should be set
1071 * to the timestamp of the input event that caused the user activity.
1072 * @param event The user activity event.
1073 * @param flags Optional user activity flags.
1074 *
1075 * @see #wakeUp
1076 * @see #goToSleep
1077 *
1078 * @hide Requires signature or system permission.
1079 */
1080 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06001081 @RequiresPermission(anyOf = {
1082 android.Manifest.permission.DEVICE_POWER,
1083 android.Manifest.permission.USER_ACTIVITY
1084 })
Jeff Brown0a571122014-08-21 21:50:43 -07001085 public void userActivity(long when, int event, int flags) {
Jeff Brown1244cda2012-06-19 16:44:46 -07001086 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001087 mService.userActivity(when, event, flags);
Jeff Brown1244cda2012-06-19 16:44:46 -07001088 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001089 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07001090 }
1091 }
1092
1093 /**
1094 * Forces the device to go to sleep.
1095 * <p>
Jeff Brown96307042012-07-27 15:51:34 -07001096 * Overrides all the wake locks that are held.
1097 * This is what happens when the power key is pressed to turn off the screen.
Jeff Brown1244cda2012-06-19 16:44:46 -07001098 * </p><p>
1099 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1100 * </p>
1101 *
1102 * @param time The time when the request to go to sleep was issued, in the
1103 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
Jeff Brown62c82e42012-09-26 01:30:41 -07001104 * order the go to sleep request with other power management functions. It should be set
Jeff Brown1244cda2012-06-19 16:44:46 -07001105 * to the timestamp of the input event that caused the request to go to sleep.
Jeff Brown96307042012-07-27 15:51:34 -07001106 *
1107 * @see #userActivity
1108 * @see #wakeUp
Jeff Brown7d827512014-08-21 21:56:02 -07001109 *
1110 * @removed Requires signature permission.
Jeff Brown1244cda2012-06-19 16:44:46 -07001111 */
1112 public void goToSleep(long time) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001113 goToSleep(time, GO_TO_SLEEP_REASON_APPLICATION, 0);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001114 }
1115
1116 /**
Jeff Brown7d827512014-08-21 21:56:02 -07001117 * Forces the device to go to sleep.
1118 * <p>
1119 * Overrides all the wake locks that are held.
1120 * This is what happens when the power key is pressed to turn off the screen.
1121 * </p><p>
1122 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1123 * </p>
1124 *
1125 * @param time The time when the request to go to sleep was issued, in the
1126 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1127 * order the go to sleep request with other power management functions. It should be set
1128 * to the timestamp of the input event that caused the request to go to sleep.
1129 * @param reason The reason the device is going to sleep.
1130 * @param flags Optional flags to apply when going to sleep.
1131 *
1132 * @see #userActivity
1133 * @see #wakeUp
1134 *
1135 * @hide Requires signature permission.
Jeff Brown6d8fd272014-05-20 21:24:38 -07001136 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001137 @UnsupportedAppUsage
Jeff Brown6d8fd272014-05-20 21:24:38 -07001138 public void goToSleep(long time, int reason, int flags) {
Jeff Brown1244cda2012-06-19 16:44:46 -07001139 try {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001140 mService.goToSleep(time, reason, flags);
Jeff Brown96307042012-07-27 15:51:34 -07001141 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001142 throw e.rethrowFromSystemServer();
Jeff Brown96307042012-07-27 15:51:34 -07001143 }
1144 }
1145
1146 /**
1147 * Forces the device to wake up from sleep.
1148 * <p>
1149 * If the device is currently asleep, wakes it up, otherwise does nothing.
1150 * This is what happens when the power key is pressed to turn on the screen.
1151 * </p><p>
1152 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1153 * </p>
1154 *
1155 * @param time The time when the request to wake up was issued, in the
1156 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
Jeff Brown62c82e42012-09-26 01:30:41 -07001157 * order the wake up request with other power management functions. It should be set
Jeff Brown96307042012-07-27 15:51:34 -07001158 * to the timestamp of the input event that caused the request to wake up.
1159 *
1160 * @see #userActivity
1161 * @see #goToSleep
Jeff Brown7d827512014-08-21 21:56:02 -07001162 *
Michael Wrighte3001042019-02-05 00:13:14 +00001163 * @deprecated Use {@link #wakeUp(long, int, String)} instead.
Jeff Brown7d827512014-08-21 21:56:02 -07001164 * @removed Requires signature permission.
Jeff Brown96307042012-07-27 15:51:34 -07001165 */
Michael Wrighte3001042019-02-05 00:13:14 +00001166 @Deprecated
Jeff Brown96307042012-07-27 15:51:34 -07001167 public void wakeUp(long time) {
Michael Wrighte3001042019-02-05 00:13:14 +00001168 wakeUp(time, WAKE_REASON_UNKNOWN, "wakeUp");
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001169 }
1170
1171 /**
Michael Wrighte3001042019-02-05 00:13:14 +00001172 * Forces the device to wake up from sleep.
1173 * <p>
1174 * If the device is currently asleep, wakes it up, otherwise does nothing.
1175 * This is what happens when the power key is pressed to turn on the screen.
1176 * </p><p>
1177 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1178 * </p>
1179 *
1180 * @param time The time when the request to wake up was issued, in the
1181 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1182 * order the wake up request with other power management functions. It should be set
1183 * to the timestamp of the input event that caused the request to wake up.
1184 *
1185 * @param details A free form string to explain the specific details behind the wake up for
1186 * debugging purposes.
1187 *
1188 * @see #userActivity
1189 * @see #goToSleep
1190 *
1191 * @deprecated Use {@link #wakeUp(long, int, String)} instead.
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001192 * @hide
1193 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001194 @UnsupportedAppUsage
Michael Wrighte3001042019-02-05 00:13:14 +00001195 @Deprecated
1196 public void wakeUp(long time, String details) {
1197 wakeUp(time, WAKE_REASON_UNKNOWN, details);
1198 }
1199
1200 /**
1201 * Forces the device to wake up from sleep.
1202 * <p>
1203 * If the device is currently asleep, wakes it up, otherwise does nothing.
1204 * This is what happens when the power key is pressed to turn on the screen.
1205 * </p><p>
1206 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1207 * </p>
1208 *
1209 * @param time The time when the request to wake up was issued, in the
1210 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1211 * order the wake up request with other power management functions. It should be set
1212 * to the timestamp of the input event that caused the request to wake up.
1213 *
1214 * @param reason The reason for the wake up.
1215 *
1216 * @param details A free form string to explain the specific details behind the wake up for
1217 * debugging purposes.
1218 *
1219 * @see #userActivity
1220 * @see #goToSleep
1221 * @hide
1222 */
1223 public void wakeUp(long time, @WakeReason int reason, String details) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001224 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001225 mService.wakeUp(time, reason, details, mContext.getOpPackageName());
Jeff Brown1244cda2012-06-19 16:44:46 -07001226 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001227 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07001228 }
1229 }
1230
1231 /**
Jeff Brown62c82e42012-09-26 01:30:41 -07001232 * Forces the device to start napping.
1233 * <p>
1234 * If the device is currently awake, starts dreaming, otherwise does nothing.
1235 * When the dream ends or if the dream cannot be started, the device will
1236 * either wake up or go to sleep depending on whether there has been recent
1237 * user activity.
1238 * </p><p>
1239 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1240 * </p>
1241 *
1242 * @param time The time when the request to nap was issued, in the
1243 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1244 * order the nap request with other power management functions. It should be set
1245 * to the timestamp of the input event that caused the request to nap.
1246 *
1247 * @see #wakeUp
1248 * @see #goToSleep
1249 *
Jeff Brown7d827512014-08-21 21:56:02 -07001250 * @hide Requires signature permission.
Jeff Brown62c82e42012-09-26 01:30:41 -07001251 */
1252 public void nap(long time) {
1253 try {
1254 mService.nap(time);
1255 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001256 throw e.rethrowFromSystemServer();
Jeff Brown62c82e42012-09-26 01:30:41 -07001257 }
1258 }
1259
1260 /**
Oleg Kibirev2385b5e2018-11-13 10:43:07 -08001261 * Requests the device to start dreaming.
1262 * <p>
1263 * If dream can not be started, for example if another {@link PowerManager} transition is in
1264 * progress, does nothing. Unlike {@link #nap(long)}, this does not put device to sleep when
1265 * dream ends.
1266 * </p><p>
Oleg Kibirevc9752eb2018-11-27 13:26:11 -08001267 * Requires the {@link android.Manifest.permission#READ_DREAM_STATE} and
1268 * {@link android.Manifest.permission#WRITE_DREAM_STATE} permissions.
Oleg Kibirev2385b5e2018-11-13 10:43:07 -08001269 * </p>
1270 *
1271 * @param time The time when the request to nap was issued, in the
1272 * {@link SystemClock#uptimeMillis()} time base. This timestamp may be used to correctly
1273 * order the dream request with other power management functions. It should be set
1274 * to the timestamp of the input event that caused the request to dream.
1275 *
1276 * @hide
1277 */
1278 @SystemApi
Oleg Kibirevc9752eb2018-11-27 13:26:11 -08001279 @RequiresPermission(allOf = {
1280 android.Manifest.permission.READ_DREAM_STATE,
1281 android.Manifest.permission.WRITE_DREAM_STATE })
Oleg Kibirev2385b5e2018-11-13 10:43:07 -08001282 public void dream(long time) {
1283 Sandman.startDreamByUserRequest(mContext);
1284 }
1285
1286 /**
Jeff Browne333e672014-10-28 13:48:55 -07001287 * Boosts the brightness of the screen to maximum for a predetermined
1288 * period of time. This is used to make the screen more readable in bright
1289 * daylight for a short duration.
1290 * <p>
1291 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1292 * </p>
1293 *
1294 * @param time The time when the request to boost was issued, in the
1295 * {@link SystemClock#uptimeMillis()} time base. This timestamp is used to correctly
1296 * order the boost request with other power management functions. It should be set
1297 * to the timestamp of the input event that caused the request to boost.
1298 *
1299 * @hide Requires signature permission.
1300 */
1301 public void boostScreenBrightness(long time) {
1302 try {
1303 mService.boostScreenBrightness(time);
1304 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001305 throw e.rethrowFromSystemServer();
Jeff Browne333e672014-10-28 13:48:55 -07001306 }
1307 }
1308
Jeff Brown1244cda2012-06-19 16:44:46 -07001309 /**
Jeff Brown96307042012-07-27 15:51:34 -07001310 * Returns true if the specified wake lock level is supported.
Jeff Brown1244cda2012-06-19 16:44:46 -07001311 *
Jeff Brown96307042012-07-27 15:51:34 -07001312 * @param level The wake lock level to check.
1313 * @return True if the specified wake lock level is supported.
Jeff Brown1244cda2012-06-19 16:44:46 -07001314 */
Jeff Brown96307042012-07-27 15:51:34 -07001315 public boolean isWakeLockLevelSupported(int level) {
Jeff Brown1244cda2012-06-19 16:44:46 -07001316 try {
Jeff Brown96307042012-07-27 15:51:34 -07001317 return mService.isWakeLockLevelSupported(level);
Jeff Brown1244cda2012-06-19 16:44:46 -07001318 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001319 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07001320 }
1321 }
1322
1323 /**
Jeff Brown037c33e2014-04-09 00:31:55 -07001324 * Returns true if the device is in an interactive state.
Jeff Brown1244cda2012-06-19 16:44:46 -07001325 * <p>
Jeff Brown037c33e2014-04-09 00:31:55 -07001326 * For historical reasons, the name of this method refers to the power state of
1327 * the screen but it actually describes the overall interactive state of
1328 * the device. This method has been replaced by {@link #isInteractive}.
Jeff Brown1244cda2012-06-19 16:44:46 -07001329 * </p><p>
Jeff Brown037c33e2014-04-09 00:31:55 -07001330 * The value returned by this method only indicates whether the device is
1331 * in an interactive state which may have nothing to do with the screen being
1332 * on or off. To determine the actual state of the screen,
1333 * use {@link android.view.Display#getState}.
Jeff Brown1244cda2012-06-19 16:44:46 -07001334 * </p>
1335 *
Jeff Brown037c33e2014-04-09 00:31:55 -07001336 * @return True if the device is in an interactive state.
1337 *
1338 * @deprecated Use {@link #isInteractive} instead.
Jeff Brown1244cda2012-06-19 16:44:46 -07001339 */
Jeff Brown037c33e2014-04-09 00:31:55 -07001340 @Deprecated
Jeff Brown1244cda2012-06-19 16:44:46 -07001341 public boolean isScreenOn() {
Jeff Brown037c33e2014-04-09 00:31:55 -07001342 return isInteractive();
1343 }
1344
1345 /**
1346 * Returns true if the device is in an interactive state.
1347 * <p>
1348 * When this method returns true, the device is awake and ready to interact
1349 * with the user (although this is not a guarantee that the user is actively
1350 * interacting with the device just this moment). The main screen is usually
1351 * turned on while in this state. Certain features, such as the proximity
1352 * sensor, may temporarily turn off the screen while still leaving the device in an
1353 * interactive state. Note in particular that the device is still considered
1354 * to be interactive while dreaming (since dreams can be interactive) but not
1355 * when it is dozing or asleep.
1356 * </p><p>
1357 * When this method returns false, the device is dozing or asleep and must
1358 * be awoken before it will become ready to interact with the user again. The
1359 * main screen is usually turned off while in this state. Certain features,
1360 * such as "ambient mode" may cause the main screen to remain on (albeit in a
1361 * low power state) to display system-provided content while the device dozes.
1362 * </p><p>
1363 * The system will send a {@link android.content.Intent#ACTION_SCREEN_ON screen on}
1364 * or {@link android.content.Intent#ACTION_SCREEN_OFF screen off} broadcast
1365 * whenever the interactive state of the device changes. For historical reasons,
1366 * the names of these broadcasts refer to the power state of the screen
1367 * but they are actually sent in response to changes in the overall interactive
1368 * state of the device, as described by this method.
1369 * </p><p>
1370 * Services may use the non-interactive state as a hint to conserve power
1371 * since the user is not present.
1372 * </p>
1373 *
1374 * @return True if the device is in an interactive state.
1375 *
1376 * @see android.content.Intent#ACTION_SCREEN_ON
1377 * @see android.content.Intent#ACTION_SCREEN_OFF
1378 */
1379 public boolean isInteractive() {
Jeff Brown1244cda2012-06-19 16:44:46 -07001380 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001381 return mService.isInteractive();
Jeff Brown1244cda2012-06-19 16:44:46 -07001382 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001383 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07001384 }
1385 }
1386
1387 /**
1388 * Reboot the device. Will not return if the reboot is successful.
1389 * <p>
1390 * Requires the {@link android.Manifest.permission#REBOOT} permission.
1391 * </p>
1392 *
1393 * @param reason code to pass to the kernel (e.g., "recovery") to
1394 * request special boot modes, or null.
1395 */
1396 public void reboot(String reason) {
1397 try {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001398 mService.reboot(false, reason, true);
Jeff Brown1244cda2012-06-19 16:44:46 -07001399 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001400 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07001401 }
1402 }
1403
1404 /**
Tony Mantlerb8009fd2016-03-14 15:55:35 -07001405 * Reboot the device. Will not return if the reboot is successful.
1406 * <p>
1407 * Requires the {@link android.Manifest.permission#REBOOT} permission.
1408 * </p>
1409 * @hide
1410 */
1411 public void rebootSafeMode() {
1412 try {
1413 mService.rebootSafeMode(false, true);
1414 } catch (RemoteException e) {
1415 throw e.rethrowFromSystemServer();
1416 }
1417 }
1418
1419 /**
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001420 * Returns true if the device is currently in power save mode. When in this mode,
1421 * applications should reduce their functionality in order to conserve battery as
1422 * much as possible. You can monitor for changes to this state with
1423 * {@link #ACTION_POWER_SAVE_MODE_CHANGED}.
1424 *
1425 * @return Returns true if currently in low power mode, else false.
1426 */
1427 public boolean isPowerSaveMode() {
1428 try {
1429 return mService.isPowerSaveMode();
1430 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001431 throw e.rethrowFromSystemServer();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001432 }
1433 }
1434
1435 /**
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001436 * Set the current power save mode.
1437 *
1438 * @return True if the set was allowed.
1439 *
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001440 * @hide
Salvador Martineza80bbab2018-09-24 10:36:11 -07001441 * @see #isPowerSaveMode()
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001442 */
Salvador Martineza80bbab2018-09-24 10:36:11 -07001443 @SystemApi
1444 @TestApi
1445 @RequiresPermission(anyOf = {
1446 android.Manifest.permission.DEVICE_POWER,
1447 android.Manifest.permission.POWER_SAVER
1448 })
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07001449 public boolean setPowerSaveModeEnabled(boolean mode) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001450 try {
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07001451 return mService.setPowerSaveModeEnabled(mode);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001452 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001453 throw e.rethrowFromSystemServer();
John Spurlock8d4e6cb2014-09-14 11:10:22 -04001454 }
1455 }
1456
1457 /**
Salvador Martinez812ea752018-10-19 13:03:20 -07001458 * Updates the current state of dynamic power savings and disable threshold. This is
1459 * a signal to the system which an app can update to serve as an indicator that
1460 * the user will be in a battery critical situation before being able to plug in.
1461 * Only apps with the {@link android.Manifest.permission#POWER_SAVER} permission may do this.
1462 * This is a device global state, not a per user setting.
1463 *
1464 * <p>When enabled, the system may enact various measures for reducing power consumption in
1465 * order to help ensure that the user will make it to their next charging point. The most
1466 * visible of these will be the automatic enabling of battery saver if the user has set
1467 * their battery saver mode to "automatic". Note
1468 * that this is NOT simply an on/off switch for features, but rather a hint for the
1469 * system to consider enacting these power saving features, some of which have additional
1470 * logic around when to activate based on this signal.
1471 *
1472 * <p>The provided threshold is the percentage the system should consider itself safe at given
1473 * the current state of the device. The value is an integer representing a battery level.
1474 *
1475 * <p>The threshold is meant to set an explicit stopping point for dynamic power savings
1476 * functionality so that the dynamic power savings itself remains a signal rather than becoming
1477 * an on/off switch for a subset of features.
1478 * @hide
1479 *
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001480 * @param powerSaveHint A signal indicating to the system if it believes the
Salvador Martinez812ea752018-10-19 13:03:20 -07001481 * dynamic power savings behaviors should be activated.
1482 * @param disableThreshold When the suggesting app believes it would be safe to disable dynamic
1483 * power savings behaviors.
1484 * @return True if the update was allowed and succeeded.
1485 *
1486 * @hide
1487 */
1488 @SystemApi
1489 @TestApi
1490 @RequiresPermission(permission.POWER_SAVER)
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001491 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
Salvador Martinez812ea752018-10-19 13:03:20 -07001492 try {
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001493 return mService.setDynamicPowerSaveHint(powerSaveHint, disableThreshold);
Salvador Martinez812ea752018-10-19 13:03:20 -07001494 } catch (RemoteException e) {
1495 throw e.rethrowFromSystemServer();
1496 }
1497 }
1498
1499 /**
Kweku Adams9f488e22019-01-14 16:25:08 -08001500 * Sets the policy for adaptive power save.
1501 *
1502 * @return true if there was an effectual change. If full battery saver is enabled or the
1503 * adaptive policy is not enabled, then this will return false.
1504 *
1505 * @hide
1506 */
1507 @SystemApi
1508 @RequiresPermission(anyOf = {
1509 android.Manifest.permission.DEVICE_POWER,
1510 android.Manifest.permission.POWER_SAVER
1511 })
1512 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
1513 try {
1514 return mService.setAdaptivePowerSavePolicy(config);
1515 } catch (RemoteException e) {
1516 throw e.rethrowFromSystemServer();
1517 }
1518 }
1519
1520 /**
1521 * Enables or disables adaptive power save.
1522 *
1523 * @return true if there was an effectual change. If full battery saver is enabled, then this
1524 * will return false.
1525 *
1526 * @hide
1527 */
1528 @SystemApi
1529 @RequiresPermission(anyOf = {
1530 android.Manifest.permission.DEVICE_POWER,
1531 android.Manifest.permission.POWER_SAVER
1532 })
1533 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
1534 try {
1535 return mService.setAdaptivePowerSaveEnabled(enabled);
1536 } catch (RemoteException e) {
1537 throw e.rethrowFromSystemServer();
1538 }
1539 }
1540
1541 /**
Salvador Martinez812ea752018-10-19 13:03:20 -07001542 * Indicates automatic battery saver toggling by the system will be based on percentage.
1543 *
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001544 * @see PowerManager#getPowerSaveModeTrigger()
Salvador Martinez812ea752018-10-19 13:03:20 -07001545 *
1546 * @hide
1547 */
1548 @SystemApi
1549 @TestApi
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001550 public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0;
Salvador Martinez812ea752018-10-19 13:03:20 -07001551
1552 /**
1553 * Indicates automatic battery saver toggling by the system will be based on the state
1554 * of the dynamic power savings signal.
1555 *
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001556 * @see PowerManager#setDynamicPowerSaveHint(boolean, int)
1557 * @see PowerManager#getPowerSaveModeTrigger()
Salvador Martinez812ea752018-10-19 13:03:20 -07001558 *
1559 * @hide
1560 */
1561 @SystemApi
1562 @TestApi
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001563 public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1;
Salvador Martinez812ea752018-10-19 13:03:20 -07001564
1565 /** @hide */
1566 @Retention(RetentionPolicy.SOURCE)
1567 @IntDef(value = {
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001568 POWER_SAVE_MODE_TRIGGER_PERCENTAGE,
1569 POWER_SAVE_MODE_TRIGGER_DYNAMIC
Salvador Martinez812ea752018-10-19 13:03:20 -07001570
1571 })
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001572 public @interface AutoPowerSaveModeTriggers {}
Salvador Martinez812ea752018-10-19 13:03:20 -07001573
1574
1575 /**
1576 * Returns the current battery saver control mode. Values it may return are defined in
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001577 * AutoPowerSaveModeTriggers. Note that this is a global device state, not a per user setting.
Salvador Martinez812ea752018-10-19 13:03:20 -07001578 *
1579 * @return The current value power saver mode for the system.
1580 *
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001581 * @see AutoPowerSaveModeTriggers
1582 * @see PowerManager#getPowerSaveModeTrigger()
Salvador Martinez812ea752018-10-19 13:03:20 -07001583 * @hide
1584 */
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001585 @AutoPowerSaveModeTriggers
Salvador Martinez812ea752018-10-19 13:03:20 -07001586 @SystemApi
1587 @TestApi
1588 @RequiresPermission(android.Manifest.permission.POWER_SAVER)
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001589 public int getPowerSaveModeTrigger() {
Salvador Martinez812ea752018-10-19 13:03:20 -07001590 try {
Salvador Martinezb85a9f82019-03-20 16:21:27 -07001591 return mService.getPowerSaveModeTrigger();
Salvador Martinez812ea752018-10-19 13:03:20 -07001592 } catch (RemoteException e) {
1593 throw e.rethrowFromSystemServer();
1594 }
1595 }
1596
1597 /**
jackqdyulei455e90a2017-02-09 15:29:16 -08001598 * Get data about the battery saver mode for a specific service
Makoto Onuki2eccd022017-11-01 13:44:23 -07001599 * @param serviceType unique key for the service, one of {@link ServiceType}
jackqdyulei455e90a2017-02-09 15:29:16 -08001600 * @return Battery saver state data.
1601 *
1602 * @hide
Kweku Adams7fb72a42019-01-08 16:08:49 -08001603 * @see com.android.server.power.batterysaver.BatterySaverPolicy
jackqdyulei455e90a2017-02-09 15:29:16 -08001604 * @see PowerSaveState
1605 */
Makoto Onuki2eccd022017-11-01 13:44:23 -07001606 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
jackqdyulei455e90a2017-02-09 15:29:16 -08001607 try {
1608 return mService.getPowerSaveState(serviceType);
1609 } catch (RemoteException e) {
1610 throw e.rethrowFromSystemServer();
1611 }
1612 }
1613
1614 /**
Makoto Onuki57f0f552017-12-11 12:22:18 -08001615 * Returns how location features should behave when battery saver is on. When battery saver
1616 * is off, this will always return {@link #LOCATION_MODE_NO_CHANGE}.
1617 *
1618 * <p>This API is normally only useful for components that provide location features.
1619 *
1620 * @see #isPowerSaveMode()
1621 * @see #ACTION_POWER_SAVE_MODE_CHANGED
1622 */
1623 @LocationPowerSaveMode
1624 public int getLocationPowerSaveMode() {
Kweku Adams731a1032019-02-04 14:05:41 -08001625 final PowerSaveState powerSaveState = getPowerSaveState(ServiceType.LOCATION);
Kweku Adams5e0052b2019-02-22 15:17:52 -08001626 if (!powerSaveState.batterySaverEnabled) {
Makoto Onuki57f0f552017-12-11 12:22:18 -08001627 return LOCATION_MODE_NO_CHANGE;
1628 }
Kweku Adams731a1032019-02-04 14:05:41 -08001629 return powerSaveState.locationMode;
Makoto Onuki57f0f552017-12-11 12:22:18 -08001630 }
1631
1632 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001633 * Returns true if the device is currently in idle mode. This happens when a device
1634 * has been sitting unused and unmoving for a sufficiently long period of time, so that
1635 * it decides to go into a lower power-use state. This may involve things like turning
1636 * off network access to apps. You can monitor for changes to this state with
1637 * {@link #ACTION_DEVICE_IDLE_MODE_CHANGED}.
1638 *
Dianne Hackbornece0f4f2015-06-11 13:29:01 -07001639 * @return Returns true if currently in active device idle mode, else false. This is
1640 * when idle mode restrictions are being actively applied; it will return false if the
1641 * device is in a long-term idle mode but currently running a maintenance window where
1642 * restrictions have been lifted.
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001643 */
1644 public boolean isDeviceIdleMode() {
1645 try {
1646 return mService.isDeviceIdleMode();
1647 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001648 throw e.rethrowFromSystemServer();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001649 }
1650 }
1651
1652 /**
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001653 * Returns true if the device is currently in light idle mode. This happens when a device
1654 * has had its screen off for a short time, switching it into a batching mode where we
1655 * execute jobs, syncs, networking on a batching schedule. You can monitor for changes to
1656 * this state with {@link #ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED}.
1657 *
1658 * @return Returns true if currently in active light device idle mode, else false. This is
1659 * when light idle mode restrictions are being actively applied; it will return false if the
1660 * device is in a long-term idle mode but currently running a maintenance window where
1661 * restrictions have been lifted.
1662 * @hide
1663 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001664 @UnsupportedAppUsage
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001665 public boolean isLightDeviceIdleMode() {
1666 try {
1667 return mService.isLightDeviceIdleMode();
1668 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001669 throw e.rethrowFromSystemServer();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001670 }
1671 }
1672
1673 /**
Dianne Hackborn1958e5e2015-06-12 18:11:41 -07001674 * Return whether the given application package name is on the device's power whitelist.
1675 * Apps can be placed on the whitelist through the settings UI invoked by
1676 * {@link android.provider.Settings#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}.
1677 */
1678 public boolean isIgnoringBatteryOptimizations(String packageName) {
Makoto Onuki152742f2019-10-31 17:22:26 -07001679 return getDeviceIdleManager().isApplicationWhitelisted(packageName);
Dianne Hackborn1958e5e2015-06-12 18:11:41 -07001680 }
1681
1682 /**
Filip Gruszczynskid05af862015-02-04 09:48:47 -08001683 * Turn off the device.
1684 *
1685 * @param confirm If true, shows a shutdown confirmation dialog.
Yusuke Sato705ffd12015-07-21 15:52:11 -07001686 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Filip Gruszczynskid05af862015-02-04 09:48:47 -08001687 * @param wait If true, this call waits for the shutdown to complete and does not return.
1688 *
1689 * @hide
1690 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07001691 public void shutdown(boolean confirm, String reason, boolean wait) {
Filip Gruszczynskid05af862015-02-04 09:48:47 -08001692 try {
Yusuke Sato705ffd12015-07-21 15:52:11 -07001693 mService.shutdown(confirm, reason, wait);
Filip Gruszczynskid05af862015-02-04 09:48:47 -08001694 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001695 throw e.rethrowFromSystemServer();
Filip Gruszczynskid05af862015-02-04 09:48:47 -08001696 }
1697 }
1698
1699 /**
Ruchi Kandoic45908d2016-05-16 10:23:15 -07001700 * This function checks if the device has implemented Sustained Performance
1701 * Mode. This needs to be checked only once and is constant for a particular
1702 * device/release.
1703 *
1704 * Sustained Performance Mode is intended to provide a consistent level of
1705 * performance for prolonged amount of time.
1706 *
1707 * Applications should check if the device supports this mode, before using
1708 * {@link android.view.Window#setSustainedPerformanceMode}.
1709 *
1710 * @return Returns True if the device supports it, false otherwise.
1711 *
1712 * @see android.view.Window#setSustainedPerformanceMode
Ruchi Kandoib4aa2e92016-03-30 12:07:31 -07001713 */
1714 public boolean isSustainedPerformanceModeSupported() {
1715 return mContext.getResources().getBoolean(
1716 com.android.internal.R.bool.config_sustainedPerformanceModeSupported);
1717 }
1718
1719 /**
Wei Wang59476652018-11-29 16:02:48 -08001720 * Thermal status code: Not under throttling.
1721 */
1722 public static final int THERMAL_STATUS_NONE = Temperature.THROTTLING_NONE;
1723
1724 /**
1725 * Thermal status code: Light throttling where UX is not impacted.
1726 */
1727 public static final int THERMAL_STATUS_LIGHT = Temperature.THROTTLING_LIGHT;
1728
1729 /**
1730 * Thermal status code: Moderate throttling where UX is not largely impacted.
1731 */
1732 public static final int THERMAL_STATUS_MODERATE = Temperature.THROTTLING_MODERATE;
1733
1734 /**
1735 * Thermal status code: Severe throttling where UX is largely impacted.
1736 */
1737 public static final int THERMAL_STATUS_SEVERE = Temperature.THROTTLING_SEVERE;
1738
1739 /**
1740 * Thermal status code: Platform has done everything to reduce power.
1741 */
1742 public static final int THERMAL_STATUS_CRITICAL = Temperature.THROTTLING_CRITICAL;
1743
1744 /**
1745 * Thermal status code: Key components in platform are shutting down due to thermal condition.
1746 * Device functionalities will be limited.
1747 */
1748 public static final int THERMAL_STATUS_EMERGENCY = Temperature.THROTTLING_EMERGENCY;
1749
1750 /**
1751 * Thermal status code: Need shutdown immediately.
1752 */
1753 public static final int THERMAL_STATUS_SHUTDOWN = Temperature.THROTTLING_SHUTDOWN;
1754
1755 /** @hide */
1756 @IntDef(prefix = { "THERMAL_STATUS_" }, value = {
1757 THERMAL_STATUS_NONE,
1758 THERMAL_STATUS_LIGHT,
1759 THERMAL_STATUS_MODERATE,
1760 THERMAL_STATUS_SEVERE,
1761 THERMAL_STATUS_CRITICAL,
1762 THERMAL_STATUS_EMERGENCY,
1763 THERMAL_STATUS_SHUTDOWN,
1764 })
1765 @Retention(RetentionPolicy.SOURCE)
1766 public @interface ThermalStatus {}
1767
1768 /**
1769 * This function returns the current thermal status of the device.
1770 *
1771 * @return thermal status as int, {@link #THERMAL_STATUS_NONE} if device in not under
1772 * thermal throttling.
1773 */
1774 public @ThermalStatus int getCurrentThermalStatus() {
1775 synchronized (this) {
1776 if (mThermalService == null) {
1777 mThermalService = IThermalService.Stub.asInterface(
1778 ServiceManager.getService(Context.THERMAL_SERVICE));
1779 }
1780 try {
1781 return mThermalService.getCurrentThermalStatus();
1782 } catch (RemoteException e) {
1783 throw e.rethrowFromSystemServer();
1784 }
1785 }
1786
1787 }
1788
1789 /**
Wei Wang7a49ff62019-03-04 21:13:32 -08001790 * Listener passed to
1791 * {@link PowerManager#addThermalStatusListener} and
1792 * {@link PowerManager#removeThermalStatusListener}
1793 * to notify caller of thermal status has changed.
Wei Wang59476652018-11-29 16:02:48 -08001794 */
Wei Wang7a49ff62019-03-04 21:13:32 -08001795 public interface OnThermalStatusChangedListener {
Wei Wang59476652018-11-29 16:02:48 -08001796
1797 /**
1798 * Called when overall thermal throttling status changed.
1799 * @param status defined in {@link android.os.Temperature}.
1800 */
Wei Wang7a49ff62019-03-04 21:13:32 -08001801 void onThermalStatusChanged(@ThermalStatus int status);
Wei Wang59476652018-11-29 16:02:48 -08001802 }
1803
Wei Wang7a49ff62019-03-04 21:13:32 -08001804
Wei Wang59476652018-11-29 16:02:48 -08001805 /**
Wei Wang7a49ff62019-03-04 21:13:32 -08001806 * This function adds a listener for thermal status change, listen call back will be
1807 * enqueued tasks on the main thread
Wei Wang59476652018-11-29 16:02:48 -08001808 *
Wei Wang7a49ff62019-03-04 21:13:32 -08001809 * @param listener listener to be added,
Wei Wang59476652018-11-29 16:02:48 -08001810 */
Wei Wang7a49ff62019-03-04 21:13:32 -08001811 public void addThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
1812 Preconditions.checkNotNull(listener, "listener cannot be null");
Wei Wang59476652018-11-29 16:02:48 -08001813 synchronized (this) {
1814 if (mThermalService == null) {
1815 mThermalService = IThermalService.Stub.asInterface(
1816 ServiceManager.getService(Context.THERMAL_SERVICE));
1817 }
Wei Wang7a49ff62019-03-04 21:13:32 -08001818 this.addThermalStatusListener(mContext.getMainExecutor(), listener);
1819 }
1820 }
1821
1822 /**
1823 * This function adds a listener for thermal status change.
1824 *
1825 * @param executor {@link Executor} to handle listener callback.
1826 * @param listener listener to be added.
1827 */
1828 public void addThermalStatusListener(@NonNull @CallbackExecutor Executor executor,
1829 @NonNull OnThermalStatusChangedListener listener) {
1830 Preconditions.checkNotNull(listener, "listener cannot be null");
1831 Preconditions.checkNotNull(executor, "executor cannot be null");
1832 synchronized (this) {
1833 if (mThermalService == null) {
1834 mThermalService = IThermalService.Stub.asInterface(
1835 ServiceManager.getService(Context.THERMAL_SERVICE));
1836 }
1837 Preconditions.checkArgument(!mListenerMap.containsKey(listener),
1838 "Listener already registered: " + listener);
1839 IThermalStatusListener internalListener = new IThermalStatusListener.Stub() {
1840 @Override
1841 public void onStatusChange(int status) {
1842 final long token = Binder.clearCallingIdentity();
1843 try {
Wei Wang59476652018-11-29 16:02:48 -08001844 executor.execute(() -> {
Wei Wang7a49ff62019-03-04 21:13:32 -08001845 listener.onThermalStatusChanged(status);
Wei Wang59476652018-11-29 16:02:48 -08001846 });
Wei Wang7a49ff62019-03-04 21:13:32 -08001847 } finally {
1848 Binder.restoreCallingIdentity(token);
Wei Wang59476652018-11-29 16:02:48 -08001849 }
Wei Wang7a49ff62019-03-04 21:13:32 -08001850 }
1851 };
1852 try {
1853 if (mThermalService.registerThermalStatusListener(internalListener)) {
1854 mListenerMap.put(listener, internalListener);
Wei Wang59476652018-11-29 16:02:48 -08001855 } else {
Wei Wang7a49ff62019-03-04 21:13:32 -08001856 throw new RuntimeException("Listener failed to set");
Wei Wang59476652018-11-29 16:02:48 -08001857 }
1858 } catch (RemoteException e) {
1859 throw e.rethrowFromSystemServer();
1860 }
1861 }
1862 }
1863
1864 /**
Wei Wang7a49ff62019-03-04 21:13:32 -08001865 * This function removes a listener for thermal status change
Wei Wang59476652018-11-29 16:02:48 -08001866 *
Wei Wang7a49ff62019-03-04 21:13:32 -08001867 * @param listener listener to be removed
Wei Wang59476652018-11-29 16:02:48 -08001868 */
Wei Wang7a49ff62019-03-04 21:13:32 -08001869 public void removeThermalStatusListener(@NonNull OnThermalStatusChangedListener listener) {
1870 Preconditions.checkNotNull(listener, "listener cannot be null");
Wei Wang59476652018-11-29 16:02:48 -08001871 synchronized (this) {
1872 if (mThermalService == null) {
1873 mThermalService = IThermalService.Stub.asInterface(
1874 ServiceManager.getService(Context.THERMAL_SERVICE));
1875 }
Wei Wang7a49ff62019-03-04 21:13:32 -08001876 IThermalStatusListener internalListener = mListenerMap.get(listener);
1877 Preconditions.checkArgument(internalListener != null, "Listener was not added");
Wei Wang59476652018-11-29 16:02:48 -08001878 try {
Wei Wang7a49ff62019-03-04 21:13:32 -08001879 if (mThermalService.unregisterThermalStatusListener(internalListener)) {
1880 mListenerMap.remove(listener);
Wei Wang59476652018-11-29 16:02:48 -08001881 } else {
Wei Wang7a49ff62019-03-04 21:13:32 -08001882 throw new RuntimeException("Listener failed to remove");
Wei Wang59476652018-11-29 16:02:48 -08001883 }
1884 } catch (RemoteException e) {
1885 throw e.rethrowFromSystemServer();
1886 }
1887 }
1888 }
1889
1890 /**
Lucas Dupin16cfe452018-02-08 13:14:50 -08001891 * If true, the doze component is not started until after the screen has been
1892 * turned off and the screen off animation has been performed.
1893 * @hide
1894 */
1895 public void setDozeAfterScreenOff(boolean dozeAfterScreenOf) {
1896 try {
1897 mService.setDozeAfterScreenOff(dozeAfterScreenOf);
1898 } catch (RemoteException e) {
1899 throw e.rethrowFromSystemServer();
1900 }
1901 }
1902
1903 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07001904 * Returns the reason the phone was last shutdown. Calling app must have the
1905 * {@link android.Manifest.permission#DEVICE_POWER} permission to request this information.
1906 * @return Reason for shutdown as an int, {@link #SHUTDOWN_REASON_UNKNOWN} if the file could
1907 * not be accessed.
1908 * @hide
1909 */
1910 @ShutdownReason
1911 public int getLastShutdownReason() {
1912 try {
1913 return mService.getLastShutdownReason();
1914 } catch (RemoteException e) {
1915 throw e.rethrowFromSystemServer();
1916 }
1917 }
1918
1919 /**
Calin Tatarua3805722018-08-09 16:41:28 +02001920 * Returns the reason the device last went to sleep (i.e. the last value of
1921 * the second argument of {@link #goToSleep(long, int, int) goToSleep}).
1922 *
1923 * @return One of the {@code GO_TO_SLEEP_REASON_*} constants.
1924 *
1925 * @hide
1926 */
1927 public int getLastSleepReason() {
1928 try {
1929 return mService.getLastSleepReason();
1930 } catch (RemoteException e) {
1931 throw e.rethrowFromSystemServer();
1932 }
1933 }
1934
1935 /**
Santos Cordon12f92eb2019-02-01 21:28:47 +00001936 * Forces the device to go to suspend, even if there are currently wakelocks being held.
1937 * <b>Caution</b>
1938 * This is a very dangerous command as it puts the device to sleep immediately. Apps and parts
1939 * of the system will not be notified and will not have an opportunity to save state prior to
1940 * the device going to suspend.
1941 * This method should only be used in very rare circumstances where the device is intended
1942 * to appear as completely off to the user and they have a well understood, reliable way of
1943 * re-enabling it.
1944 * </p><p>
1945 * Requires the {@link android.Manifest.permission#DEVICE_POWER} permission.
1946 * </p>
1947 *
1948 * @return true on success, false otherwise.
1949 * @hide
1950 */
1951 @SystemApi
1952 @RequiresPermission(android.Manifest.permission.DEVICE_POWER)
1953 public boolean forceSuspend() {
1954 try {
1955 return mService.forceSuspend();
1956 } catch (RemoteException e) {
1957 throw e.rethrowFromSystemServer();
1958 }
1959 }
1960
1961 /**
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001962 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1963 * This broadcast is only sent to registered receivers.
1964 */
1965 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1966 public static final String ACTION_POWER_SAVE_MODE_CHANGED
1967 = "android.os.action.POWER_SAVE_MODE_CHANGED";
1968
1969 /**
Jason Monkafae4bd2015-12-15 14:20:06 -05001970 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} changes.
1971 * @hide
1972 */
1973 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1974 public static final String ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL
1975 = "android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL";
1976
1977 /**
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001978 * Intent that is broadcast when the state of {@link #isDeviceIdleMode()} changes.
1979 * This broadcast is only sent to registered receivers.
1980 */
1981 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1982 public static final String ACTION_DEVICE_IDLE_MODE_CHANGED
1983 = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
1984
1985 /**
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001986 * Intent that is broadcast when the state of {@link #isLightDeviceIdleMode()} changes.
1987 * This broadcast is only sent to registered receivers.
1988 * @hide
1989 */
Andrei Onea24ec3212019-03-15 17:35:05 +00001990 @UnsupportedAppUsage
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001991 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
1992 public static final String ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED
1993 = "android.os.action.LIGHT_DEVICE_IDLE_MODE_CHANGED";
1994
1995 /**
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001996 * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
1997 * This broadcast is only sent to registered receivers.
1998 */
1999 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
2000 public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
2001 = "android.os.action.POWER_SAVE_WHITELIST_CHANGED";
2002
2003 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002004 * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed.
2005 * This broadcast is only sent to registered receivers.
2006 */
2007 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
2008 public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED
2009 = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED";
2010
2011 /**
John Spurlock1bb480a2014-08-02 17:12:43 -04002012 * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change.
2013 * This broadcast is only sent to registered receivers.
2014 *
2015 * @hide
2016 */
Andrei Onea24ec3212019-03-15 17:35:05 +00002017 @UnsupportedAppUsage
John Spurlock1bb480a2014-08-02 17:12:43 -04002018 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
2019 public static final String ACTION_POWER_SAVE_MODE_CHANGING
2020 = "android.os.action.POWER_SAVE_MODE_CHANGING";
2021
2022 /** @hide */
Andrei Onea24ec3212019-03-15 17:35:05 +00002023 @UnsupportedAppUsage
John Spurlock1bb480a2014-08-02 17:12:43 -04002024 public static final String EXTRA_POWER_SAVE_MODE = "mode";
2025
2026 /**
Denny cy Leec5a7c292019-01-01 17:37:55 +08002027 * Constant for PreIdleTimeout normal mode (default mode, not short nor extend timeout) .
2028 * @hide
2029 */
2030 public static final int PRE_IDLE_TIMEOUT_MODE_NORMAL = 0;
2031
2032 /**
2033 * Constant for PreIdleTimeout long mode (extend timeout to keep in inactive mode
2034 * longer).
2035 * @hide
2036 */
2037 public static final int PRE_IDLE_TIMEOUT_MODE_LONG = 1;
2038
2039 /**
2040 * Constant for PreIdleTimeout short mode (short timeout to go to doze mode quickly)
2041 * @hide
2042 */
2043 public static final int PRE_IDLE_TIMEOUT_MODE_SHORT = 2;
2044
2045 /**
Jeff Brown1244cda2012-06-19 16:44:46 -07002046 * A wake lock is a mechanism to indicate that your application needs
2047 * to have the device stay on.
Kenny Rootd710fb52011-03-15 17:39:45 -07002048 * <p>
2049 * Any application using a WakeLock must request the {@code android.permission.WAKE_LOCK}
Neil Fuller71fbb812015-11-30 09:51:33 +00002050 * permission in an {@code <uses-permission>} element of the application's manifest.
Jeff Brown1244cda2012-06-19 16:44:46 -07002051 * Obtain a wake lock by calling {@link PowerManager#newWakeLock(int, String)}.
2052 * </p><p>
2053 * Call {@link #acquire()} to acquire the wake lock and force the device to stay
2054 * on at the level that was requested when the wake lock was created.
2055 * </p><p>
2056 * Call {@link #release()} when you are done and don't need the lock anymore.
2057 * It is very important to do this as soon as possible to avoid running down the
2058 * device's battery excessively.
2059 * </p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 */
Jeff Brown1244cda2012-06-19 16:44:46 -07002061 public final class WakeLock {
Andrei Onea24ec3212019-03-15 17:35:05 +00002062 @UnsupportedAppUsage
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002063 private int mFlags;
Andrei Onea24ec3212019-03-15 17:35:05 +00002064 @UnsupportedAppUsage
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002065 private String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002066 private final String mPackageName;
Jeff Brown1244cda2012-06-19 16:44:46 -07002067 private final IBinder mToken;
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002068 private int mInternalCount;
2069 private int mExternalCount;
Jeff Brown1244cda2012-06-19 16:44:46 -07002070 private boolean mRefCounted = true;
2071 private boolean mHeld;
2072 private WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002073 private String mHistoryTag;
Jeff Brown3edf5272014-08-14 19:25:14 -07002074 private final String mTraceName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075
Jeff Brown1244cda2012-06-19 16:44:46 -07002076 private final Runnable mReleaser = new Runnable() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 public void run() {
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002078 release(RELEASE_FLAG_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081
Dianne Hackborn713df152013-05-17 11:27:57 -07002082 WakeLock(int flags, String tag, String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 mFlags = flags;
2084 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002085 mPackageName = packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 mToken = new Binder();
Jeff Brown3edf5272014-08-14 19:25:14 -07002087 mTraceName = "WakeLock (" + mTag + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 @Override
Jeff Brown1244cda2012-06-19 16:44:46 -07002091 protected void finalize() throws Throwable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 synchronized (mToken) {
2093 if (mHeld) {
Dan Egnor60d87622009-12-16 16:32:58 -08002094 Log.wtf(TAG, "WakeLock finalized while still held: " + mTag);
Jeff Brown3edf5272014-08-14 19:25:14 -07002095 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 try {
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002097 mService.releaseWakeLock(mToken, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002099 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102 }
2103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104
Jeff Brown1244cda2012-06-19 16:44:46 -07002105 /**
2106 * Sets whether this WakeLock is reference counted.
2107 * <p>
2108 * Wake locks are reference counted by default. If a wake lock is
2109 * reference counted, then each call to {@link #acquire()} must be
2110 * balanced by an equal number of calls to {@link #release()}. If a wake
2111 * lock is not reference counted, then one call to {@link #release()} is
2112 * sufficient to undo the effect of all previous calls to {@link #acquire()}.
2113 * </p>
2114 *
2115 * @param value True to make the wake lock reference counted, false to
2116 * make the wake lock non-reference counted.
2117 */
2118 public void setReferenceCounted(boolean value) {
2119 synchronized (mToken) {
2120 mRefCounted = value;
2121 }
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04002122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123
Jeff Brown1244cda2012-06-19 16:44:46 -07002124 /**
2125 * Acquires the wake lock.
2126 * <p>
2127 * Ensures that the device is on at the level requested when
2128 * the wake lock was created.
2129 * </p>
2130 */
2131 public void acquire() {
2132 synchronized (mToken) {
2133 acquireLocked();
2134 }
2135 }
2136
2137 /**
2138 * Acquires the wake lock with a timeout.
2139 * <p>
2140 * Ensures that the device is on at the level requested when
2141 * the wake lock was created. The lock will be released after the given timeout
2142 * expires.
2143 * </p>
2144 *
2145 * @param timeout The timeout after which to release the wake lock, in milliseconds.
2146 */
2147 public void acquire(long timeout) {
2148 synchronized (mToken) {
2149 acquireLocked();
2150 mHandler.postDelayed(mReleaser, timeout);
2151 }
2152 }
2153
2154 private void acquireLocked() {
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002155 mInternalCount++;
2156 mExternalCount++;
2157 if (!mRefCounted || mInternalCount == 1) {
Jeff Brownff1baef2012-07-19 15:01:17 -07002158 // Do this even if the wake lock is already thought to be held (mHeld == true)
2159 // because non-reference counted wake locks are not always properly released.
2160 // For example, the keyguard's wake lock might be forcibly released by the
2161 // power manager without the keyguard knowing. A subsequent call to acquire
2162 // should immediately acquire the wake lock once again despite never having
2163 // been explicitly released by the keyguard.
Jeff Brown1244cda2012-06-19 16:44:46 -07002164 mHandler.removeCallbacks(mReleaser);
Jeff Brown3edf5272014-08-14 19:25:14 -07002165 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brownff1baef2012-07-19 15:01:17 -07002166 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002167 mService.acquireWakeLock(mToken, mFlags, mTag, mPackageName, mWorkSource,
2168 mHistoryTag);
Jeff Brownff1baef2012-07-19 15:01:17 -07002169 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002170 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07002171 }
Jeff Brownff1baef2012-07-19 15:01:17 -07002172 mHeld = true;
Jeff Brown1244cda2012-06-19 16:44:46 -07002173 }
2174 }
2175
2176 /**
2177 * Releases the wake lock.
2178 * <p>
2179 * This method releases your claim to the CPU or screen being on.
2180 * The screen may turn off shortly after you release the wake lock, or it may
2181 * not if there are other wake locks still held.
2182 * </p>
2183 */
2184 public void release() {
2185 release(0);
2186 }
2187
2188 /**
2189 * Releases the wake lock with flags to modify the release behavior.
2190 * <p>
2191 * This method releases your claim to the CPU or screen being on.
2192 * The screen may turn off shortly after you release the wake lock, or it may
2193 * not if there are other wake locks still held.
2194 * </p>
2195 *
2196 * @param flags Combination of flag values to modify the release behavior.
Michael Wright1208e272014-09-08 19:57:50 -07002197 * Currently only {@link #RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY} is supported.
2198 * Passing 0 is equivalent to calling {@link #release()}.
Jeff Brown1244cda2012-06-19 16:44:46 -07002199 */
2200 public void release(int flags) {
2201 synchronized (mToken) {
Henrik Baard8d475ca2017-08-09 14:45:05 +02002202 if (mInternalCount > 0) {
2203 // internal count must only be decreased if it is > 0 or state of
2204 // the WakeLock object is broken.
2205 mInternalCount--;
2206 }
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002207 if ((flags & RELEASE_FLAG_TIMEOUT) == 0) {
2208 mExternalCount--;
2209 }
2210 if (!mRefCounted || mInternalCount == 0) {
Jeff Brown1244cda2012-06-19 16:44:46 -07002211 mHandler.removeCallbacks(mReleaser);
2212 if (mHeld) {
Jeff Brown3edf5272014-08-14 19:25:14 -07002213 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown1244cda2012-06-19 16:44:46 -07002214 try {
2215 mService.releaseWakeLock(mToken, flags);
2216 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002217 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07002218 }
2219 mHeld = false;
2220 }
2221 }
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002222 if (mRefCounted && mExternalCount < 0) {
Jeff Brown1244cda2012-06-19 16:44:46 -07002223 throw new RuntimeException("WakeLock under-locked " + mTag);
2224 }
2225 }
2226 }
2227
2228 /**
2229 * Returns true if the wake lock has been acquired but not yet released.
2230 *
2231 * @return True if the wake lock is held.
2232 */
2233 public boolean isHeld() {
2234 synchronized (mToken) {
2235 return mHeld;
2236 }
2237 }
2238
2239 /**
2240 * Sets the work source associated with the wake lock.
2241 * <p>
2242 * The work source is used to determine on behalf of which application
2243 * the wake lock is being held. This is useful in the case where a
2244 * service is performing work on behalf of an application so that the
2245 * cost of that work can be accounted to the application.
2246 * </p>
2247 *
Olivier Gaillard24a0c132017-11-22 15:07:31 +00002248 * <p>
2249 * Make sure to follow the tag naming convention when using WorkSource
2250 * to make it easier for app developers to understand wake locks
2251 * attributed to them. See {@link PowerManager#newWakeLock(int, String)}
2252 * documentation.
2253 * </p>
2254 *
Jeff Brown1244cda2012-06-19 16:44:46 -07002255 * @param ws The work source, or null if none.
2256 */
2257 public void setWorkSource(WorkSource ws) {
2258 synchronized (mToken) {
Narayan Kamath81822022017-12-08 11:56:01 +00002259 if (ws != null && ws.isEmpty()) {
Jeff Brown1244cda2012-06-19 16:44:46 -07002260 ws = null;
2261 }
2262
2263 final boolean changed;
2264 if (ws == null) {
2265 changed = mWorkSource != null;
2266 mWorkSource = null;
2267 } else if (mWorkSource == null) {
2268 changed = true;
2269 mWorkSource = new WorkSource(ws);
2270 } else {
Narayan Kamath81822022017-12-08 11:56:01 +00002271 changed = !mWorkSource.equals(ws);
Jeff Brown1244cda2012-06-19 16:44:46 -07002272 if (changed) {
2273 mWorkSource.set(ws);
2274 }
2275 }
2276
2277 if (changed && mHeld) {
2278 try {
Dianne Hackborn4590e522014-03-24 13:36:46 -07002279 mService.updateWakeLockWorkSource(mToken, mWorkSource, mHistoryTag);
Jeff Brown1244cda2012-06-19 16:44:46 -07002280 } catch (RemoteException e) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07002281 throw e.rethrowFromSystemServer();
Jeff Brown1244cda2012-06-19 16:44:46 -07002282 }
2283 }
2284 }
2285 }
2286
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002287 /** @hide */
2288 public void setTag(String tag) {
2289 mTag = tag;
2290 }
2291
2292 /** @hide */
Christopher Tate4b17e982016-09-26 12:59:10 -07002293 public String getTag() {
2294 return mTag;
2295 }
2296
2297 /** @hide */
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002298 public void setHistoryTag(String tag) {
2299 mHistoryTag = tag;
2300 }
2301
2302 /** @hide */
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002303 public void setUnimportantForLogging(boolean state) {
2304 if (state) mFlags |= UNIMPORTANT_FOR_LOGGING;
2305 else mFlags &= ~UNIMPORTANT_FOR_LOGGING;
2306 }
2307
Jeff Brown1244cda2012-06-19 16:44:46 -07002308 @Override
2309 public String toString() {
2310 synchronized (mToken) {
2311 return "WakeLock{"
2312 + Integer.toHexString(System.identityHashCode(this))
Jeff Sharkey291c32a2017-07-05 12:34:04 -06002313 + " held=" + mHeld + ", refCount=" + mInternalCount + "}";
Jeff Brown1244cda2012-06-19 16:44:46 -07002314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
Adrian Roos7445c0b2016-09-06 16:45:46 -07002316
Yi Jin148d7f42017-11-28 14:23:56 -08002317 /** @hide */
2318 public void writeToProto(ProtoOutputStream proto, long fieldId) {
2319 synchronized (mToken) {
2320 final long token = proto.start(fieldId);
Yi Jin163967f2018-03-15 13:49:44 -07002321 proto.write(PowerManagerProto.WakeLock.TAG, mTag);
2322 proto.write(PowerManagerProto.WakeLock.PACKAGE_NAME, mPackageName);
2323 proto.write(PowerManagerProto.WakeLock.HELD, mHeld);
2324 proto.write(PowerManagerProto.WakeLock.INTERNAL_COUNT, mInternalCount);
Yi Jin148d7f42017-11-28 14:23:56 -08002325 if (mWorkSource != null) {
Yi Jin163967f2018-03-15 13:49:44 -07002326 mWorkSource.writeToProto(proto, PowerManagerProto.WakeLock.WORK_SOURCE);
Yi Jin148d7f42017-11-28 14:23:56 -08002327 }
2328 proto.end(token);
2329 }
2330 }
2331
Adrian Roos7445c0b2016-09-06 16:45:46 -07002332 /**
2333 * Wraps a Runnable such that this method immediately acquires the wake lock and then
2334 * once the Runnable is done the wake lock is released.
2335 *
2336 * <p>Example:
2337 *
2338 * <pre>
2339 * mHandler.post(mWakeLock.wrap(() -> {
2340 * // do things on handler, lock is held while we're waiting for this
2341 * // to get scheduled and until the runnable is done executing.
2342 * });
2343 * </pre>
2344 *
2345 * <p>Note: you must make sure that the Runnable eventually gets executed, otherwise you'll
2346 * leak the wakelock!
2347 *
2348 * @hide
2349 */
2350 public Runnable wrap(Runnable r) {
2351 acquire();
2352 return () -> {
2353 try {
2354 r.run();
2355 } finally {
2356 release();
2357 }
2358 };
2359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361}