blob: 85fa5188be393a37f0c333943d8cd172c865e907 [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
Jeff Brown4f8ecd82012-06-18 18:29:13 -070017package com.android.server.power;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Jeff Brown96307042012-07-27 15:51:34 -070019import android.Manifest;
Tony Mantlerb8009fd2016-03-14 15:55:35 -070020import android.annotation.IntDef;
Jason Monkafae4bd2015-12-15 14:20:06 -050021import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070028import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080029import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080030import android.hardware.SensorManager;
31import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080032import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070033import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Jeff Brown96307042012-07-27 15:51:34 -070034import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070035import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070036import android.os.BatteryManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Binder;
38import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.IBinder;
40import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070041import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080042import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.PowerManager;
Jeff Brown6f357d32014-01-15 20:40:55 -080044import android.os.PowerManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Process;
46import android.os.RemoteException;
47import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070048import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070049import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070050import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070051import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.provider.Settings;
Jason Monk5dbd4aa2016-02-07 13:13:39 -050053import android.provider.Settings.Secure;
Daichi Hirono82ab9802016-03-02 13:23:29 +090054import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080055import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070056import android.service.vr.IVrManager;
57import android.service.vr.IVrStateCallbacks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.util.EventLog;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070059import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Jason Monkafae4bd2015-12-15 14:20:06 -050061import android.util.SparseIntArray;
Jeff Brown96307042012-07-27 15:51:34 -070062import android.util.TimeUtils;
Jeff Brown037c33e2014-04-09 00:31:55 -070063import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.WindowManagerPolicy;
Daichi Hirono82ab9802016-03-02 13:23:29 +090065
Jason Monkafae4bd2015-12-15 14:20:06 -050066import com.android.internal.app.IAppOpsService;
67import com.android.internal.app.IBatteryStats;
68import com.android.internal.os.BackgroundThread;
Jeff Sharkey3dee8d62016-03-02 13:07:56 -070069import com.android.internal.util.ArrayUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050070import com.android.server.EventLogTags;
71import com.android.server.ServiceThread;
72import com.android.server.SystemService;
73import com.android.server.Watchdog;
74import com.android.server.am.BatteryStatsService;
75import com.android.server.lights.Light;
76import com.android.server.lights.LightsManager;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070077import com.android.server.vr.VrManagerService;
Jason Monkafae4bd2015-12-15 14:20:06 -050078import libcore.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80import java.io.FileDescriptor;
81import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -070082import java.lang.annotation.Retention;
83import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -070085import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Michael Wrighta4d22d72015-09-16 23:19:26 +010087import static android.os.PowerManagerInternal.POWER_HINT_INTERACTION;
Jeff Brownfbe96702014-11-19 18:30:58 -080088import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
89import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
Jeff Brownfbe96702014-11-19 18:30:58 -080090import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
Jason Monkafae4bd2015-12-15 14:20:06 -050091import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
Jeff Brownfbe96702014-11-19 18:30:58 -080092
Jeff Brown96307042012-07-27 15:51:34 -070093/**
94 * The power manager service is responsible for coordinating power management
95 * functions on the device.
96 */
Jeff Brown2175e9c2014-09-12 16:11:07 -070097public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -070098 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Jeff Brown88c997a2012-06-22 13:57:45 -0700101 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700102 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700103
Jeff Brown96307042012-07-27 15:51:34 -0700104 // Message: Sent when a user activity timeout occurs to update the power state.
105 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800106 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700107 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700108 // Message: Sent when the screen brightness boost expires.
109 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700110 // Message: Polling to look for long held wake locks.
111 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Jeff Brown7304c342012-05-11 18:42:42 -0700112
Jeff Brown96307042012-07-27 15:51:34 -0700113 // Dirty bit: mWakeLocks changed
114 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
115 // Dirty bit: mWakefulness changed
116 private static final int DIRTY_WAKEFULNESS = 1 << 1;
117 // Dirty bit: user activity was poked or may have timed out
118 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
119 // Dirty bit: actual display power state was updated asynchronously
120 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
121 // Dirty bit: mBootCompleted changed
122 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
123 // Dirty bit: settings changed
124 private static final int DIRTY_SETTINGS = 1 << 5;
125 // Dirty bit: mIsPowered changed
126 private static final int DIRTY_IS_POWERED = 1 << 6;
127 // Dirty bit: mStayOn changed
128 private static final int DIRTY_STAY_ON = 1 << 7;
129 // Dirty bit: battery state changed
130 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700131 // Dirty bit: proximity state changed
132 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700133 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700134 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700135 // Dirty bit: brightness boost changed
136 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Santos Cordond6a56602016-09-20 15:50:35 -0700137 // Dirty bit: VR Mode enabled changed
138 private static final int DIRTY_VR_MODE_CHANGED = 1 << 12;
Jeff Brown7304c342012-05-11 18:42:42 -0700139
Jeff Brown96307042012-07-27 15:51:34 -0700140 // Summarizes the state of all active wakelocks.
141 private static final int WAKE_LOCK_CPU = 1 << 0;
142 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
143 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
144 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
145 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700146 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800147 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800148 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Jeff Brown96307042012-07-27 15:51:34 -0700150 // Summarizes the user activity state.
151 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
152 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700153 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Jeff Brown27736f52014-05-20 17:17:10 -0700155 // Default timeout in milliseconds. This is only used until the settings
156 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700157 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700158 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700159
Jeff Browne333e672014-10-28 13:48:55 -0700160 // Screen brightness boost timeout.
161 // Hardcoded for now until we decide what the right policy should be.
162 // This should perhaps be a setting.
163 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
164
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700165 // How long a partial wake lock must be held until we consider it a long wake lock.
166 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
167
Jeff Brown0a571122014-08-21 21:50:43 -0700168 // Power hints defined in hardware/libhardware/include/hardware/power.h.
Jeff Brown0a571122014-08-21 21:50:43 -0700169 private static final int POWER_HINT_LOW_POWER = 5;
Ruchi Kandoi03a04282016-03-14 17:09:17 -0700170 private static final int POWER_HINT_VR_MODE = 7;
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700171
Jason Monk27bbb2d2015-03-31 16:46:39 -0400172 // Power features defined in hardware/libhardware/include/hardware/power.h.
173 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
174
175 // Default setting for double tap to wake.
176 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
177
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700178 /** Constants for {@link #shutdownOrRebootInternal} */
179 @Retention(RetentionPolicy.SOURCE)
180 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
181 public @interface HaltMode {}
182 private static final int HALT_MODE_SHUTDOWN = 0;
183 private static final int HALT_MODE_REBOOT = 1;
184 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
185
Jeff Brownb880d882014-02-10 19:47:07 -0800186 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700187 private final ServiceThread mHandlerThread;
188 private final PowerManagerHandler mHandler;
189
Adam Lesinski182f73f2013-12-05 16:48:06 -0800190 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700191 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800192 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700193 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700194 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700195 private WindowManagerPolicy mPolicy;
196 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800197 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700198 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800199 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800200 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700201
Jeff Brown96307042012-07-27 15:51:34 -0700202 private final Object mLock = new Object();
203
204 // A bitfield that indicates what parts of the power state have
205 // changed and need to be recalculated.
206 private int mDirty;
207
208 // Indicates whether the device is awake or asleep or somewhere in between.
209 // This is distinct from the screen power state, which is managed separately.
210 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800211 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700212
Jeff Brown26875502014-01-30 21:47:47 -0800213 // True if the sandman has just been summoned for the first time since entering the
214 // dreaming or dozing state. Indicates whether a new dream should begin.
215 private boolean mSandmanSummoned;
216
Jeff Brown96307042012-07-27 15:51:34 -0700217 // True if MSG_SANDMAN has been scheduled.
218 private boolean mSandmanScheduled;
219
220 // Table of all suspend blockers.
221 // There should only be a few of these.
222 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
223
224 // Table of all wake locks acquired by applications.
225 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
226
227 // A bitfield that summarizes the state of all active wakelocks.
228 private int mWakeLockSummary;
229
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700230 // Have we scheduled a message to check for long wake locks? This is when we will check.
231 private long mNotifyLongScheduled;
232
233 // Last time we checked for long wake locks.
234 private long mNotifyLongDispatched;
235
236 // The time we decided to do next long check.
237 private long mNotifyLongNextCheck;
238
Jeff Brown96307042012-07-27 15:51:34 -0700239 // If true, instructs the display controller to wait for the proximity sensor to
240 // go negative before turning the screen on.
241 private boolean mRequestWaitForNegativeProximity;
242
243 // Timestamp of the last time the device was awoken or put to sleep.
244 private long mLastWakeTime;
245 private long mLastSleepTime;
246
Jeff Brown96307042012-07-27 15:51:34 -0700247 // Timestamp of the last call to user activity.
248 private long mLastUserActivityTime;
249 private long mLastUserActivityTimeNoChangeLights;
250
Jeff Brown0a571122014-08-21 21:50:43 -0700251 // Timestamp of last interactive power hint.
252 private long mLastInteractivePowerHintTime;
253
Jeff Browne333e672014-10-28 13:48:55 -0700254 // Timestamp of the last screen brightness boost.
255 private long mLastScreenBrightnessBoostTime;
256 private boolean mScreenBrightnessBoostInProgress;
257
Jeff Brown96307042012-07-27 15:51:34 -0700258 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700259 private int mUserActivitySummary;
260
261 // The desired display power state. The actual state may lag behind the
262 // requested because it is updated asynchronously by the display power controller.
263 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
264
Jeff Brown96307042012-07-27 15:51:34 -0700265 // True if the display power state has been fully applied, which means the display
266 // is actually on or actually off or whatever was requested.
267 private boolean mDisplayReady;
268
Jeff Brown27f7a862012-12-12 15:43:31 -0800269 // The suspend blocker used to keep the CPU alive when an application has acquired
270 // a wake lock.
271 private final SuspendBlocker mWakeLockSuspendBlocker;
272
273 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700274 private boolean mHoldingWakeLockSuspendBlocker;
275
Jeff Brown27f7a862012-12-12 15:43:31 -0800276 // The suspend blocker used to keep the CPU alive when the display is on, the
277 // display is getting ready or there is user activity (in which case the display
278 // must be on).
279 private final SuspendBlocker mDisplaySuspendBlocker;
280
281 // True if the display suspend blocker has been acquired.
282 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700283
284 // True if systemReady() has been called.
285 private boolean mSystemReady;
286
287 // True if boot completed occurred. We keep the screen on until this happens.
288 private boolean mBootCompleted;
289
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700290 // Runnables that should be triggered on boot completed
291 private Runnable[] mBootCompletedRunnables;
292
Jeff Brown26875502014-01-30 21:47:47 -0800293 // True if auto-suspend mode is enabled.
294 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700295 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800296
297 // True if interactive mode is enabled.
298 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700299 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800300
Jeff Brown96307042012-07-27 15:51:34 -0700301 // True if the device is plugged into a power source.
302 private boolean mIsPowered;
303
Jeff Brownf3fb8952012-10-02 20:57:05 -0700304 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
305 private int mPlugType;
306
Jeff Brown016ff142012-10-15 16:47:22 -0700307 // The current battery level percentage.
308 private int mBatteryLevel;
309
310 // The battery level percentage at the time the dream started.
311 // This is used to terminate a dream and go to sleep if the battery is
312 // draining faster than it is charging and the user activity timeout has expired.
313 private int mBatteryLevelWhenDreamStarted;
314
Jeff Brownec6aa592012-10-17 20:30:25 -0700315 // The current dock state.
316 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
317
Jeff Brown26875502014-01-30 21:47:47 -0800318 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700319 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800320
321 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700322 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800323
Jeff Brown96307042012-07-27 15:51:34 -0700324 // True if the device should wake up when plugged or unplugged.
325 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
326
Bryce Lee584a4452014-10-21 15:55:55 -0700327 // True if the device should wake up when plugged or unplugged in theater mode.
328 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
329
Jeff Brownec083212013-09-11 20:45:25 -0700330 // True if the device should suspend when the screen is off due to proximity.
331 private boolean mSuspendWhenScreenOffDueToProximityConfig;
332
Jeff Brown96307042012-07-27 15:51:34 -0700333 // True if dreams are supported on this device.
334 private boolean mDreamsSupportedConfig;
335
John Spurlocked108f32012-10-18 16:49:24 -0400336 // Default value for dreams enabled
337 private boolean mDreamsEnabledByDefaultConfig;
338
339 // Default value for dreams activate-on-sleep
340 private boolean mDreamsActivatedOnSleepByDefaultConfig;
341
342 // Default value for dreams activate-on-dock
343 private boolean mDreamsActivatedOnDockByDefaultConfig;
344
Jeff Brown26875502014-01-30 21:47:47 -0800345 // True if dreams can run while not plugged in.
346 private boolean mDreamsEnabledOnBatteryConfig;
347
348 // Minimum battery level to allow dreaming when powered.
349 // Use -1 to disable this safety feature.
350 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
351
352 // Minimum battery level to allow dreaming when not powered.
353 // Use -1 to disable this safety feature.
354 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
355
356 // If the battery level drops by this percentage and the user activity timeout
357 // has expired, then assume the device is receiving insufficient current to charge
358 // effectively and terminate the dream. Use -1 to disable this safety feature.
359 private int mDreamsBatteryLevelDrainCutoffConfig;
360
Jeff Brown96307042012-07-27 15:51:34 -0700361 // True if dreams are enabled by the user.
362 private boolean mDreamsEnabledSetting;
363
John Spurlock1a868b72012-08-22 09:56:51 -0400364 // True if dreams should be activated on sleep.
365 private boolean mDreamsActivateOnSleepSetting;
366
Jeff Brownec6aa592012-10-17 20:30:25 -0700367 // True if dreams should be activated on dock.
368 private boolean mDreamsActivateOnDockSetting;
369
Jeff Brown2175e9c2014-09-12 16:11:07 -0700370 // True if doze should not be started until after the screen off transition.
371 private boolean mDozeAfterScreenOffConfig;
372
Jeff Brown27736f52014-05-20 17:17:10 -0700373 // The minimum screen off timeout, in milliseconds.
374 private int mMinimumScreenOffTimeoutConfig;
375
376 // The screen dim duration, in milliseconds.
377 // This is subtracted from the end of the screen off timeout so the
378 // minimum screen off timeout should be longer than this.
379 private int mMaximumScreenDimDurationConfig;
380
381 // The maximum screen dim time expressed as a ratio relative to the screen
382 // off timeout. If the screen off timeout is very short then we want the
383 // dim timeout to also be quite short so that most of the time is spent on.
384 // Otherwise the user won't get much screen on time before dimming occurs.
385 private float mMaximumScreenDimRatioConfig;
386
Jason Monk27bbb2d2015-03-31 16:46:39 -0400387 // Whether device supports double tap to wake.
388 private boolean mSupportsDoubleTapWakeConfig;
389
Jeff Brown96307042012-07-27 15:51:34 -0700390 // The screen off timeout setting value in milliseconds.
391 private int mScreenOffTimeoutSetting;
392
Jeff Brown05af6ad2014-09-30 20:54:30 -0700393 // The sleep timeout setting value in milliseconds.
394 private int mSleepTimeoutSetting;
395
Jeff Brown96307042012-07-27 15:51:34 -0700396 // The maximum allowable screen off timeout according to the device
397 // administration policy. Overrides other settings.
398 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
399
400 // The stay on while plugged in setting.
401 // A bitfield of battery conditions under which to make the screen stay on.
402 private int mStayOnWhilePluggedInSetting;
403
404 // True if the device should stay on.
405 private boolean mStayOn;
406
Jeff Brown93cbbb22012-10-04 13:18:36 -0700407 // True if the proximity sensor reads a positive result.
408 private boolean mProximityPositive;
409
Jeff Brown96307042012-07-27 15:51:34 -0700410 // Screen brightness setting limits.
411 private int mScreenBrightnessSettingMinimum;
412 private int mScreenBrightnessSettingMaximum;
413 private int mScreenBrightnessSettingDefault;
Santos Cordond6a56602016-09-20 15:50:35 -0700414 private int mScreenBrightnessForVrSettingDefault;
Jeff Brown96307042012-07-27 15:51:34 -0700415
416 // The screen brightness setting, from 0 to 255.
417 // Use -1 if no value has been set.
418 private int mScreenBrightnessSetting;
419
Santos Cordond6a56602016-09-20 15:50:35 -0700420 // The screen brightness setting, from 0 to 255, to be used while in VR Mode.
421 private int mScreenBrightnessForVrSetting;
422
Jeff Brown330560f2012-08-21 22:10:57 -0700423 // The screen auto-brightness adjustment setting, from -1 to 1.
424 // Use 0 if there is no adjustment.
425 private float mScreenAutoBrightnessAdjustmentSetting;
426
Jeff Brown96307042012-07-27 15:51:34 -0700427 // The screen brightness mode.
428 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
429 private int mScreenBrightnessModeSetting;
430
431 // The screen brightness setting override from the window manager
432 // to allow the current foreground activity to override the brightness.
433 // Use -1 to disable.
434 private int mScreenBrightnessOverrideFromWindowManager = -1;
435
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700436 // The window manager has determined the user to be inactive via other means.
437 // Set this to false to disable.
438 private boolean mUserInactiveOverrideFromWindowManager;
439
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700440 // The next possible user activity timeout after being explicitly told the user is inactive.
441 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
442 private long mOverriddenTimeout = -1;
443
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700444 // The user activity timeout override from the window manager
445 // to allow the current foreground activity to override the user activity timeout.
446 // Use -1 to disable.
447 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
448
Jeff Brown96307042012-07-27 15:51:34 -0700449 // The screen brightness setting override from the settings application
450 // to temporarily adjust the brightness until next updated,
451 // Use -1 to disable.
452 private int mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453
Jeff Brown330560f2012-08-21 22:10:57 -0700454 // The screen brightness adjustment setting override from the settings
455 // application to temporarily adjust the auto-brightness adjustment factor
456 // until next updated, in the range -1..1.
457 // Use NaN to disable.
458 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
459
Jeff Brown970d4132014-07-19 11:33:47 -0700460 // The screen state to use while dozing.
461 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
462
463 // The screen brightness to use while dozing.
464 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
465
Jeff Brown9ba8d782012-10-01 16:38:23 -0700466 // Time when we last logged a warning about calling userActivity() without permission.
467 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
468
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700469 // If true, the device is in low power mode.
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700470 private boolean mLowPowerModeEnabled;
471
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700472 // Current state of the low power mode setting.
473 private boolean mLowPowerModeSetting;
474
Dianne Hackborn14272302014-06-10 23:13:02 -0700475 // Current state of whether the settings are allowing auto low power mode.
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400476 private boolean mAutoLowPowerModeConfigured;
Dianne Hackborn14272302014-06-10 23:13:02 -0700477
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400478 // The user turned off low power mode below the trigger level
John Spurlock1bb480a2014-08-02 17:12:43 -0400479 private boolean mAutoLowPowerModeSnoozing;
480
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700481 // True if the battery level is currently considered low.
482 private boolean mBatteryLevelLow;
483
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700484 // True if we are currently in device idle mode.
485 private boolean mDeviceIdleMode;
486
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700487 // True if we are currently in light device idle mode.
488 private boolean mLightDeviceIdleMode;
489
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700490 // Set of app ids that we will always respect the wake locks for.
491 int[] mDeviceIdleWhitelist = new int[0];
492
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700493 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
494 int[] mDeviceIdleTempWhitelist = new int[0];
495
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700496 private final SparseIntArray mUidState = new SparseIntArray();
497
Bryce Lee584a4452014-10-21 15:55:55 -0700498 // True if theater mode is enabled
499 private boolean mTheaterModeEnabled;
500
Jason Monk27bbb2d2015-03-31 16:46:39 -0400501 // True if double tap to wake is enabled
502 private boolean mDoubleTapWakeEnabled;
503
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700504 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners
505 = new ArrayList<PowerManagerInternal.LowPowerModeListener>();
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700506
Jason Monk5dbd4aa2016-02-07 13:13:39 -0500507 // True if brightness should be affected by twilight.
508 private boolean mBrightnessUseTwilight;
509
Santos Cordond6a56602016-09-20 15:50:35 -0700510 // True if we are currently in VR Mode.
511 private boolean mIsVrModeEnabled;
512
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700513 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514
Jeff Brown96307042012-07-27 15:51:34 -0700515 private static native void nativeAcquireSuspendBlocker(String name);
516 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700517 private static native void nativeSetInteractive(boolean enable);
518 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700519 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400520 private static native void nativeSetFeature(int featureId, int data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521
Jeff Brownb880d882014-02-10 19:47:07 -0800522 public PowerManagerService(Context context) {
523 super(context);
524 mContext = context;
Jeff Brown2c43c332014-06-12 22:38:59 -0700525 mHandlerThread = new ServiceThread(TAG,
526 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
527 mHandlerThread.start();
528 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
529
Jeff Brown96307042012-07-27 15:51:34 -0700530 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800531 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
532 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
533 mDisplaySuspendBlocker.acquire();
534 mHoldingDisplaySuspendBlocker = true;
Jeff Brown037c33e2014-04-09 00:31:55 -0700535 mHalAutoSuspendModeEnabled = false;
536 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800537
Jeff Brown96307042012-07-27 15:51:34 -0700538 mWakefulness = WAKEFULNESS_AWAKE;
Jeff Brown7304c342012-05-11 18:42:42 -0700539
Jeff Brown037c33e2014-04-09 00:31:55 -0700540 nativeInit();
541 nativeSetAutoSuspend(false);
542 nativeSetInteractive(true);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400543 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
Jeff Brown6f357d32014-01-15 20:40:55 -0800547 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800548 public void onStart() {
549 publishBinderService(Context.POWER_SERVICE, new BinderService());
550 publishLocalService(PowerManagerInternal.class, new LocalService());
Jeff Brown9e316a12012-10-08 19:17:06 -0700551
552 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800553 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700554 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800555
Jeff Brown6d2a9492014-08-07 19:06:49 -0700556 @Override
557 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700558 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600559 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
560 incrementBootCount();
561
562 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700563 final long now = SystemClock.uptimeMillis();
564 mBootCompleted = true;
565 mDirty |= DIRTY_BOOT_COMPLETED;
566 userActivityNoUpdateLocked(
567 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
568 updatePowerStateLocked();
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700569
570 if (!ArrayUtils.isEmpty(mBootCompletedRunnables)) {
571 Slog.d(TAG, "Posting " + mBootCompletedRunnables.length + " delayed runnables");
572 for (Runnable r : mBootCompletedRunnables) {
573 BackgroundThread.getHandler().post(r);
574 }
575 }
576 mBootCompletedRunnables = null;
Craig Mautner6e2f3952014-09-09 14:26:41 -0700577 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700578 }
579 }
580
Jeff Brown21392762014-06-13 19:00:36 -0700581 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700582 synchronized (mLock) {
583 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700584 mAppOps = appOps;
585 mDreamManager = getLocalService(DreamManagerInternal.class);
586 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
587 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700588 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
Adam Lesinski182f73f2013-12-05 16:48:06 -0800590 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700591 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
592 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
593 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
Santos Cordond6a56602016-09-20 15:50:35 -0700594 mScreenBrightnessForVrSettingDefault = pm.getDefaultScreenBrightnessForVrSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700596 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800597
Jeff Brownc38c9be2012-10-04 13:16:19 -0700598 // The notifier runs on the system server's main looper so as not to interfere
599 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700600 mBatteryStats = BatteryStatsService.getService();
Jeff Brownc38c9be2012-10-04 13:16:19 -0700601 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700602 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brown3ee549c2014-09-22 20:14:39 -0700603 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700604
Jeff Brown3b971592013-01-09 18:46:37 -0800605 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700606 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
607 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700608 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700609
610 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800611 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400612
Jeff Brown131206b2014-04-08 17:27:14 -0700613 // Initialize display power management.
614 mDisplayManagerInternal.initPowerManagement(
615 mDisplayPowerCallbacks, mHandler, sensorManager);
616
Jeff Brown96307042012-07-27 15:51:34 -0700617 // Register for broadcasts from other components of the system.
618 IntentFilter filter = new IntentFilter();
619 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700620 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Jeff Brownd4935962012-09-25 13:27:20 -0700621 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700622
Jeff Brown96307042012-07-27 15:51:34 -0700623 filter = new IntentFilter();
Dianne Hackbornbe87e2f2012-09-28 16:31:34 -0700624 filter.addAction(Intent.ACTION_DREAMING_STARTED);
625 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
Jeff Brownd4935962012-09-25 13:27:20 -0700626 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
627
628 filter = new IntentFilter();
629 filter.addAction(Intent.ACTION_USER_SWITCHED);
630 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
John Spurlockf4f6b4c2012-08-25 12:08:03 -0400631
Jeff Brownec6aa592012-10-17 20:30:25 -0700632 filter = new IntentFilter();
633 filter.addAction(Intent.ACTION_DOCK_EVENT);
634 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
635
Jeff Brown96307042012-07-27 15:51:34 -0700636 // Register for settings changes.
637 final ContentResolver resolver = mContext.getContentResolver();
638 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700639 Settings.Secure.SCREENSAVER_ENABLED),
640 false, mSettingsObserver, UserHandle.USER_ALL);
John Spurlock1a868b72012-08-22 09:56:51 -0400641 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700642 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
643 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brownec6aa592012-10-17 20:30:25 -0700644 resolver.registerContentObserver(Settings.Secure.getUriFor(
645 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
646 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700647 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700648 Settings.System.SCREEN_OFF_TIMEOUT),
649 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700650 resolver.registerContentObserver(Settings.Secure.getUriFor(
651 Settings.Secure.SLEEP_TIMEOUT),
652 false, mSettingsObserver, UserHandle.USER_ALL);
Christopher Tatead735322012-09-07 14:19:43 -0700653 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700654 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
655 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700656 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700657 Settings.System.SCREEN_BRIGHTNESS),
658 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700659 resolver.registerContentObserver(Settings.System.getUriFor(
Santos Cordond6a56602016-09-20 15:50:35 -0700660 Settings.System.SCREEN_BRIGHTNESS_FOR_VR),
661 false, mSettingsObserver, UserHandle.USER_ALL);
662 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700663 Settings.System.SCREEN_BRIGHTNESS_MODE),
664 false, mSettingsObserver, UserHandle.USER_ALL);
Adrian Roos6dee6052014-05-14 19:44:18 +0200665 resolver.registerContentObserver(Settings.System.getUriFor(
666 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
667 false, mSettingsObserver, UserHandle.USER_ALL);
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700668 resolver.registerContentObserver(Settings.Global.getUriFor(
669 Settings.Global.LOW_POWER_MODE),
670 false, mSettingsObserver, UserHandle.USER_ALL);
Dianne Hackborn14272302014-06-10 23:13:02 -0700671 resolver.registerContentObserver(Settings.Global.getUriFor(
672 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
673 false, mSettingsObserver, UserHandle.USER_ALL);
Bryce Lee584a4452014-10-21 15:55:55 -0700674 resolver.registerContentObserver(Settings.Global.getUriFor(
675 Settings.Global.THEATER_MODE_ON),
676 false, mSettingsObserver, UserHandle.USER_ALL);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400677 resolver.registerContentObserver(Settings.Secure.getUriFor(
678 Settings.Secure.DOUBLE_TAP_TO_WAKE),
679 false, mSettingsObserver, UserHandle.USER_ALL);
Jason Monk5dbd4aa2016-02-07 13:13:39 -0500680 resolver.registerContentObserver(Settings.Secure.getUriFor(
681 Secure.BRIGHTNESS_USE_TWILIGHT),
682 false, mSettingsObserver, UserHandle.USER_ALL);
Ruben Brunkc7be3be2016-04-01 17:07:51 -0700683 IVrManager vrManager =
684 (IVrManager) getBinderService(VrManagerService.VR_MANAGER_BINDER_SERVICE);
Wei Liuef89d212016-09-19 15:10:33 -0700685 if (vrManager != null) {
686 try {
687 vrManager.registerListener(mVrStateCallbacks);
688 } catch (RemoteException e) {
689 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
690 }
Ruben Brunkc7be3be2016-04-01 17:07:51 -0700691 }
Jeff Brown96307042012-07-27 15:51:34 -0700692 // Go.
693 readConfigurationLocked();
694 updateSettingsLocked();
695 mDirty |= DIRTY_BATTERY_STATE;
696 updatePowerStateLocked();
697 }
698 }
699
700 private void readConfigurationLocked() {
701 final Resources resources = mContext.getResources();
702
Jeff Brown037c33e2014-04-09 00:31:55 -0700703 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800704 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700705 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800706 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700707 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700708 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700709 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
710 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700711 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
712 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700713 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400714 com.android.internal.R.bool.config_dreamsSupported);
715 mDreamsEnabledByDefaultConfig = resources.getBoolean(
716 com.android.internal.R.bool.config_dreamsEnabledByDefault);
717 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
718 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
719 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
720 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800721 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
722 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
723 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
724 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
725 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
726 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
727 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
728 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Jeff Brown2175e9c2014-09-12 16:11:07 -0700729 mDozeAfterScreenOffConfig = resources.getBoolean(
730 com.android.internal.R.bool.config_dozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -0700731 mMinimumScreenOffTimeoutConfig = resources.getInteger(
732 com.android.internal.R.integer.config_minimumScreenOffTimeout);
733 mMaximumScreenDimDurationConfig = resources.getInteger(
734 com.android.internal.R.integer.config_maximumScreenDimDuration);
735 mMaximumScreenDimRatioConfig = resources.getFraction(
736 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400737 mSupportsDoubleTapWakeConfig = resources.getBoolean(
738 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 }
740
Jeff Brown96307042012-07-27 15:51:34 -0700741 private void updateSettingsLocked() {
742 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700743
Jeff Brownd4935962012-09-25 13:27:20 -0700744 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400745 Settings.Secure.SCREENSAVER_ENABLED,
746 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700747 UserHandle.USER_CURRENT) != 0);
748 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400749 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
750 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700751 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700752 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400753 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
754 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700755 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700756 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
757 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
758 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700759 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
760 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
761 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700762 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700763 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -0700764 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
765 Settings.Global.THEATER_MODE_ON, 0) == 1;
Jeff Brown7304c342012-05-11 18:42:42 -0700766
Jason Monk27bbb2d2015-03-31 16:46:39 -0400767 if (mSupportsDoubleTapWakeConfig) {
768 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
769 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
770 UserHandle.USER_CURRENT) != 0;
771 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
772 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
773 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
774 }
775 }
776
Santos Cordond6a56602016-09-20 15:50:35 -0700777 final int oldScreenBrightnessSetting = getCurrentBrightnessSettingLocked();
778
779 mScreenBrightnessForVrSetting = Settings.System.getIntForUser(resolver,
780 Settings.System.SCREEN_BRIGHTNESS_FOR_VR, mScreenBrightnessForVrSettingDefault,
781 UserHandle.USER_CURRENT);
782
Jeff Brownd4935962012-09-25 13:27:20 -0700783 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
784 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
785 UserHandle.USER_CURRENT);
Santos Cordond6a56602016-09-20 15:50:35 -0700786
787 if (oldScreenBrightnessSetting != getCurrentBrightnessSettingLocked()) {
Jeff Brown96307042012-07-27 15:51:34 -0700788 mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
Jeff Brown96307042012-07-27 15:51:34 -0700790
Jeff Brown330560f2012-08-21 22:10:57 -0700791 final float oldScreenAutoBrightnessAdjustmentSetting =
792 mScreenAutoBrightnessAdjustmentSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700793 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
794 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
795 UserHandle.USER_CURRENT);
Jeff Brown330560f2012-08-21 22:10:57 -0700796 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
Jeff Brown5d03a532012-08-22 13:22:02 -0700797 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
Jeff Brown330560f2012-08-21 22:10:57 -0700798 }
799
Jeff Brownd4935962012-09-25 13:27:20 -0700800 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700801 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700802 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700803
Jason Monk5dbd4aa2016-02-07 13:13:39 -0500804 mBrightnessUseTwilight = Settings.Secure.getIntForUser(resolver,
805 Secure.BRIGHTNESS_USE_TWILIGHT, 0, UserHandle.USER_CURRENT) != 0;
806
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700807 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver,
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700808 Settings.Global.LOW_POWER_MODE, 0) != 0;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400809 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver,
John Spurlock1bb480a2014-08-02 17:12:43 -0400810 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0;
Dianne Hackborn14272302014-06-10 23:13:02 -0700811 if (lowPowerModeEnabled != mLowPowerModeSetting
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400812 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700813 mLowPowerModeSetting = lowPowerModeEnabled;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400814 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured;
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700815 updateLowPowerModeLocked();
816 }
817
818 mDirty |= DIRTY_SETTINGS;
819 }
820
Santos Cordond6a56602016-09-20 15:50:35 -0700821 private int getCurrentBrightnessSettingLocked() {
822 return mIsVrModeEnabled ? mScreenBrightnessForVrSetting : mScreenBrightnessSetting;
823 }
824
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700825 private void postAfterBootCompleted(Runnable r) {
826 if (mBootCompleted) {
827 BackgroundThread.getHandler().post(r);
828 } else {
829 Slog.d(TAG, "Delaying runnable until system is booted");
830 mBootCompletedRunnables = ArrayUtils.appendElement(Runnable.class,
831 mBootCompletedRunnables, r);
832 }
833 }
834
Daichi Hirono82ab9802016-03-02 13:23:29 +0900835 private void updateLowPowerModeLocked() {
Michael Wright2763c2b2016-08-11 15:45:49 +0100836 if ((mIsPowered || !mBatteryLevelLow && !mBootCompleted) && mLowPowerModeSetting) {
John Spurlock1bb480a2014-08-02 17:12:43 -0400837 if (DEBUG_SPEW) {
Michael Wright2763c2b2016-08-11 15:45:49 +0100838 Slog.d(TAG, "updateLowPowerModeLocked: powered or booting with sufficient battery,"
839 + " turning setting off");
John Spurlock1bb480a2014-08-02 17:12:43 -0400840 }
841 // Turn setting off if powered
842 Settings.Global.putInt(mContext.getContentResolver(),
843 Settings.Global.LOW_POWER_MODE, 0);
844 mLowPowerModeSetting = false;
John Spurlock1bb480a2014-08-02 17:12:43 -0400845 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400846 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured
847 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow;
848 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled;
849
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700850 if (mLowPowerModeEnabled != lowPowerModeEnabled) {
851 mLowPowerModeEnabled = lowPowerModeEnabled;
Jeff Brown0a571122014-08-21 21:50:43 -0700852 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0);
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700853 postAfterBootCompleted(new Runnable() {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700854 @Override
855 public void run() {
John Spurlock1bb480a2014-08-02 17:12:43 -0400856 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)
857 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled)
858 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
859 mContext.sendBroadcast(intent);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700860 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners;
861 synchronized (mLock) {
862 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>(
863 mLowPowerModeListeners);
864 }
865 for (int i=0; i<listeners.size(); i++) {
866 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled);
867 }
John Spurlock1bb480a2014-08-02 17:12:43 -0400868 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700869 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
870 mContext.sendBroadcast(intent);
Jason Monkafae4bd2015-12-15 14:20:06 -0500871 // Send internal version that requires signature permission.
872 mContext.sendBroadcastAsUser(new Intent(
873 PowerManager.ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL), UserHandle.ALL,
874 Manifest.permission.DEVICE_POWER);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700875 }
876 });
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
Jeff Brown96307042012-07-27 15:51:34 -0700880 private void handleSettingsChangedLocked() {
881 updateSettingsLocked();
882 updatePowerStateLocked();
883 }
884
Dianne Hackborn713df152013-05-17 11:27:57 -0700885 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800886 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700887 synchronized (mLock) {
888 if (DEBUG_SPEW) {
889 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
890 + ", flags=0x" + Integer.toHexString(flags)
891 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893
Jeff Brown96307042012-07-27 15:51:34 -0700894 WakeLock wakeLock;
895 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700896 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -0700897 if (index >= 0) {
898 wakeLock = mWakeLocks.get(index);
899 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
900 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800901 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
902 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800903 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700905 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 } else {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800907 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700908 try {
909 lock.linkToDeath(wakeLock, 0);
910 } catch (RemoteException ex) {
911 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Jeff Brown96307042012-07-27 15:51:34 -0700913 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700914 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700915 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
Jeff Brownc12035c2014-08-13 18:52:25 -0700918 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -0700919 mDirty |= DIRTY_WAKE_LOCKS;
920 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700921 if (notifyAcquire) {
922 // This needs to be done last so we are sure we have acquired the
923 // kernel wake lock. Otherwise we have a race where the system may
924 // go to sleep between the time we start the accounting in battery
925 // stats and when we actually get around to telling the kernel to
926 // stay awake.
927 notifyWakeLockAcquiredLocked(wakeLock);
928 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700929 }
930 }
931
Jeff Brownec083212013-09-11 20:45:25 -0700932 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -0800933 private static boolean isScreenLock(final WakeLock wakeLock) {
934 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
935 case PowerManager.FULL_WAKE_LOCK:
936 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
937 case PowerManager.SCREEN_DIM_WAKE_LOCK:
938 return true;
939 }
940 return false;
941 }
942
Jeff Brownc12035c2014-08-13 18:52:25 -0700943 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -0700944 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
945 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -0700946 String opPackageName;
947 int opUid;
948 if (wakeLock.mWorkSource != null && wakeLock.mWorkSource.getName(0) != null) {
949 opPackageName = wakeLock.mWorkSource.getName(0);
950 opUid = wakeLock.mWorkSource.get(0);
951 } else {
952 opPackageName = wakeLock.mPackageName;
953 opUid = wakeLock.mWorkSource != null ? wakeLock.mWorkSource.get(0)
954 : wakeLock.mOwnerUid;
955 }
956 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), wakeLock.mTag, opUid,
957 opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 }
960
Jeff Brown96307042012-07-27 15:51:34 -0700961 private void releaseWakeLockInternal(IBinder lock, int flags) {
962 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -0700963 int index = findWakeLockIndexLocked(lock);
964 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800965 if (DEBUG_SPEW) {
966 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
967 + " [not found], flags=0x" + Integer.toHexString(flags));
968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 return;
970 }
Mike Lockwood3333fa42009-10-26 14:50:42 -0400971
Jeff Brown96307042012-07-27 15:51:34 -0700972 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800973 if (DEBUG_SPEW) {
974 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
975 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
976 }
977
Michael Wright1208e272014-09-08 19:57:50 -0700978 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -0700979 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981
Jeff Brown3edf5272014-08-14 19:25:14 -0700982 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
983 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700986
Jeff Brown96307042012-07-27 15:51:34 -0700987 private void handleWakeLockDeath(WakeLock wakeLock) {
988 synchronized (mLock) {
989 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800990 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
991 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -0700992 }
993
994 int index = mWakeLocks.indexOf(wakeLock);
995 if (index < 0) {
996 return;
997 }
998
Jeff Brown3edf5272014-08-14 19:25:14 -0700999 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001000 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001002
Jeff Brown3edf5272014-08-14 19:25:14 -07001003 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1004 mWakeLocks.remove(index);
1005 notifyWakeLockReleasedLocked(wakeLock);
1006
1007 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1008 mDirty |= DIRTY_WAKE_LOCKS;
1009 updatePowerStateLocked();
1010 }
1011
Jeff Brown96307042012-07-27 15:51:34 -07001012 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001013 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1014 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001015 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1016 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1017 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1018 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
Dianne Hackbornd953c532014-08-16 18:17:38 -07001022 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1023 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001024 synchronized (mLock) {
1025 int index = findWakeLockIndexLocked(lock);
1026 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001027 if (DEBUG_SPEW) {
1028 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1029 + " [not found], ws=" + ws);
1030 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001031 throw new IllegalArgumentException("Wake lock not active: " + lock
1032 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001033 }
1034
1035 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001036 if (DEBUG_SPEW) {
1037 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1038 + " [" + wakeLock.mTag + "], ws=" + ws);
1039 }
1040
Jeff Brown96307042012-07-27 15:51:34 -07001041 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001042 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1043 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001044 ws, historyTag);
1045 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001046 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001047 }
1048 }
1049 }
1050
1051 private int findWakeLockIndexLocked(IBinder lock) {
1052 final int count = mWakeLocks.size();
1053 for (int i = 0; i < count; i++) {
1054 if (mWakeLocks.get(i).mLock == lock) {
1055 return i;
1056 }
1057 }
1058 return -1;
1059 }
1060
1061 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001062 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001063 wakeLock.mNotifiedAcquired = true;
1064 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001065 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1066 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001067 restartNofifyLongTimerLocked(wakeLock);
1068 }
1069 }
1070
1071 private void enqueueNotifyLongMsgLocked(long time) {
1072 mNotifyLongScheduled = time;
1073 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1074 msg.setAsynchronous(true);
1075 mHandler.sendMessageAtTime(msg, time);
1076 }
1077
1078 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1079 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1080 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1081 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1082 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1083 }
1084 }
1085
1086 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1087 if (mSystemReady && !wakeLock.mDisabled) {
1088 wakeLock.mNotifiedLong = true;
1089 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1090 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1091 }
1092 }
1093
1094 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1095 if (wakeLock.mNotifiedLong) {
1096 wakeLock.mNotifiedLong = false;
1097 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1098 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001099 }
1100 }
1101
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001102 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1103 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1104 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1105 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1106 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1107 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001108 notifyWakeLockLongFinishedLocked(wakeLock);
1109 // Changing the wake lock will count as releasing the old wake lock(s) and
1110 // acquiring the new ones... we do this because otherwise once a wakelock
1111 // becomes long, if we just continued to treat it as long we can get in to
1112 // situations where we spam battery stats with every following change to it.
1113 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001114 }
1115 }
1116
Jeff Brown96307042012-07-27 15:51:34 -07001117 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001118 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1119 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001120 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001121 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1122 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1123 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001124 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001125 }
1126 }
1127
Jeff Brownec083212013-09-11 20:45:25 -07001128 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001129 private boolean isWakeLockLevelSupportedInternal(int level) {
1130 synchronized (mLock) {
1131 switch (level) {
1132 case PowerManager.PARTIAL_WAKE_LOCK:
1133 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1134 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1135 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001136 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001137 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001138 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001139
1140 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001141 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001142
1143 default:
1144 return false;
1145 }
1146 }
1147 }
1148
Jeff Brown96307042012-07-27 15:51:34 -07001149 // Called from native code.
1150 private void userActivityFromNative(long eventTime, int event, int flags) {
1151 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1152 }
1153
1154 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1155 synchronized (mLock) {
1156 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1157 updatePowerStateLocked();
1158 }
1159 }
1160 }
1161
1162 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1163 if (DEBUG_SPEW) {
1164 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1165 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1166 + ", uid=" + uid);
1167 }
1168
1169 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001170 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001171 return false;
1172 }
1173
Jeff Brown3edf5272014-08-14 19:25:14 -07001174 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1175 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001176 if (eventTime > mLastInteractivePowerHintTime) {
1177 powerHintInternal(POWER_HINT_INTERACTION, 0);
1178 mLastInteractivePowerHintTime = eventTime;
1179 }
1180
Jeff Brown3edf5272014-08-14 19:25:14 -07001181 mNotifier.onUserActivity(event, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001182
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001183 if (mUserInactiveOverrideFromWindowManager) {
1184 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001185 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001186 }
1187
Jeff Brown0a571122014-08-21 21:50:43 -07001188 if (mWakefulness == WAKEFULNESS_ASLEEP
1189 || mWakefulness == WAKEFULNESS_DOZING
1190 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1191 return false;
1192 }
1193
Jeff Brown3edf5272014-08-14 19:25:14 -07001194 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1195 if (eventTime > mLastUserActivityTimeNoChangeLights
1196 && eventTime > mLastUserActivityTime) {
1197 mLastUserActivityTimeNoChangeLights = eventTime;
1198 mDirty |= DIRTY_USER_ACTIVITY;
1199 return true;
1200 }
1201 } else {
1202 if (eventTime > mLastUserActivityTime) {
1203 mLastUserActivityTime = eventTime;
1204 mDirty |= DIRTY_USER_ACTIVITY;
1205 return true;
1206 }
Jeff Brown96307042012-07-27 15:51:34 -07001207 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001208 } finally {
1209 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001210 }
1211 return false;
1212 }
1213
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001214 private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName,
1215 int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001216 synchronized (mLock) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001217 if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001218 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001219 }
1220 }
Jeff Brown96307042012-07-27 15:51:34 -07001221 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001222
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001223 private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid,
1224 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001225 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001226 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001227 }
Jeff Brown96307042012-07-27 15:51:34 -07001228
1229 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1230 || !mBootCompleted || !mSystemReady) {
1231 return false;
1232 }
1233
Jeff Brown3edf5272014-08-14 19:25:14 -07001234 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1235 try {
1236 switch (mWakefulness) {
1237 case WAKEFULNESS_ASLEEP:
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001238 Slog.i(TAG, "Waking up from sleep (uid " + reasonUid +")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001239 break;
1240 case WAKEFULNESS_DREAMING:
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001241 Slog.i(TAG, "Waking up from dream (uid " + reasonUid +")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001242 break;
1243 case WAKEFULNESS_DOZING:
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001244 Slog.i(TAG, "Waking up from dozing (uid " + reasonUid +")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001245 break;
1246 }
1247
1248 mLastWakeTime = eventTime;
Jeff Brownfbe96702014-11-19 18:30:58 -08001249 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001250
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001251 mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001252 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001253 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001254 } finally {
1255 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001256 }
Jeff Brown96307042012-07-27 15:51:34 -07001257 return true;
1258 }
1259
Jeff Brownc12035c2014-08-13 18:52:25 -07001260 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001261 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001262 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001263 updatePowerStateLocked();
1264 }
1265 }
1266 }
1267
Jeff Brown26875502014-01-30 21:47:47 -08001268 // This method is called goToSleep for historical reasons but we actually start
1269 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -07001270 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001271 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001272 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001273 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001274 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001275 }
1276
Jeff Brown26875502014-01-30 21:47:47 -08001277 if (eventTime < mLastWakeTime
1278 || mWakefulness == WAKEFULNESS_ASLEEP
1279 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001280 || !mBootCompleted || !mSystemReady) {
1281 return false;
1282 }
1283
Jeff Brown3edf5272014-08-14 19:25:14 -07001284 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1285 try {
1286 switch (reason) {
1287 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1288 Slog.i(TAG, "Going to sleep due to device administration policy "
1289 + "(uid " + uid +")...");
1290 break;
1291 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1292 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1293 break;
1294 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1295 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1296 break;
1297 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1298 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1299 break;
Filip Gruszczynski9779e122015-03-13 17:39:31 -07001300 case PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON:
1301 Slog.i(TAG, "Going to sleep due to sleep button (uid " + uid +")...");
1302 break;
Jeff Brown3edf5272014-08-14 19:25:14 -07001303 case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1304 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1305 break;
1306 default:
1307 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1308 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
Jeff Brown96307042012-07-27 15:51:34 -07001309 break;
1310 }
Jeff Brown6d8fd272014-05-20 21:24:38 -07001311
Jeff Brown3edf5272014-08-14 19:25:14 -07001312 mLastSleepTime = eventTime;
Jeff Brown3edf5272014-08-14 19:25:14 -07001313 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001314 setWakefulnessLocked(WAKEFULNESS_DOZING, reason);
Jeff Brown3edf5272014-08-14 19:25:14 -07001315
1316 // Report the number of wake locks that will be cleared by going to sleep.
1317 int numWakeLocksCleared = 0;
1318 final int numWakeLocks = mWakeLocks.size();
1319 for (int i = 0; i < numWakeLocks; i++) {
1320 final WakeLock wakeLock = mWakeLocks.get(i);
1321 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1322 case PowerManager.FULL_WAKE_LOCK:
1323 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1324 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1325 numWakeLocksCleared += 1;
1326 break;
1327 }
1328 }
1329 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
1330
1331 // Skip dozing if requested.
1332 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1333 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1334 }
1335 } finally {
1336 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001337 }
Jeff Brown96307042012-07-27 15:51:34 -07001338 return true;
1339 }
1340
Jeff Brownc12035c2014-08-13 18:52:25 -07001341 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001342 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001343 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001344 updatePowerStateLocked();
1345 }
1346 }
1347 }
1348
Jeff Brownc12035c2014-08-13 18:52:25 -07001349 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001350 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001351 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001352 }
1353
1354 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1355 || !mBootCompleted || !mSystemReady) {
1356 return false;
1357 }
1358
Jeff Brown3edf5272014-08-14 19:25:14 -07001359 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1360 try {
1361 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001362
Jeff Brown3edf5272014-08-14 19:25:14 -07001363 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001364 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001365 } finally {
1366 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1367 }
Jeff Brown26875502014-01-30 21:47:47 -08001368 return true;
1369 }
1370
1371 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001372 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001373 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001374 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1375 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001376 }
1377
1378 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1379 || !mBootCompleted || !mSystemReady) {
1380 return false;
1381 }
1382
Jeff Brown3edf5272014-08-14 19:25:14 -07001383 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1384 try {
1385 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001386
Jeff Brownfbe96702014-11-19 18:30:58 -08001387 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
Jeff Brown3edf5272014-08-14 19:25:14 -07001388 } finally {
1389 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1390 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001391 return true;
1392 }
1393
Jeff Brownfbe96702014-11-19 18:30:58 -08001394 private void setWakefulnessLocked(int wakefulness, int reason) {
1395 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001396 mWakefulness = wakefulness;
1397 mWakefulnessChanging = true;
1398 mDirty |= DIRTY_WAKEFULNESS;
1399 mNotifier.onWakefulnessChangeStarted(wakefulness, reason);
Jeff Brown037c33e2014-04-09 00:31:55 -07001400 }
1401 }
1402
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001403 /**
1404 * Logs the time the device would have spent awake before user activity timeout,
1405 * had the system not been told the user was inactive.
1406 */
1407 private void logSleepTimeoutRecapturedLocked() {
1408 final long now = SystemClock.uptimeMillis();
1409 final long savedWakeTimeMs = mOverriddenTimeout - now;
1410 if (savedWakeTimeMs >= 0) {
1411 EventLog.writeEvent(EventLogTags.POWER_SOFT_SLEEP_REQUESTED, savedWakeTimeMs);
1412 mOverriddenTimeout = -1;
1413 }
1414 }
1415
Jeff Brown416c49c2015-05-26 19:50:18 -07001416 private void finishWakefulnessChangeIfNeededLocked() {
1417 if (mWakefulnessChanging && mDisplayReady) {
1418 if (mWakefulness == WAKEFULNESS_DOZING
1419 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1420 return; // wait until dream has enabled dozing
1421 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001422 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1423 logSleepTimeoutRecapturedLocked();
1424 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001425 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001426 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001427 }
1428 }
1429
Jeff Brown96307042012-07-27 15:51:34 -07001430 /**
1431 * Updates the global power state based on dirty bits recorded in mDirty.
1432 *
1433 * This is the main function that performs power state transitions.
1434 * We centralize them here so that we can recompute the power state completely
1435 * each time something important changes, and ensure that we do it the same
1436 * way each time. The point is to gather all of the transition logic here.
1437 */
1438 private void updatePowerStateLocked() {
1439 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001440 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001442 if (!Thread.holdsLock(mLock)) {
1443 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
Jeff Brown3edf5272014-08-14 19:25:14 -07001446 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1447 try {
1448 // Phase 0: Basic state updates.
1449 updateIsPoweredLocked(mDirty);
1450 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001451 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452
Jeff Brown3edf5272014-08-14 19:25:14 -07001453 // Phase 1: Update wakefulness.
1454 // Loop because the wake lock and user activity computations are influenced
1455 // by changes in wakefulness.
1456 final long now = SystemClock.uptimeMillis();
1457 int dirtyPhase2 = 0;
1458 for (;;) {
1459 int dirtyPhase1 = mDirty;
1460 dirtyPhase2 |= dirtyPhase1;
1461 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001462
Jeff Brown3edf5272014-08-14 19:25:14 -07001463 updateWakeLockSummaryLocked(dirtyPhase1);
1464 updateUserActivitySummaryLocked(now, dirtyPhase1);
1465 if (!updateWakefulnessLocked(dirtyPhase1)) {
1466 break;
1467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001469
Jeff Brown2175e9c2014-09-12 16:11:07 -07001470 // Phase 2: Update display power state.
1471 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
Jeff Brown3edf5272014-08-14 19:25:14 -07001472
Jeff Brown2175e9c2014-09-12 16:11:07 -07001473 // Phase 3: Update dream state (depends on display ready signal).
1474 updateDreamLocked(dirtyPhase2, displayBecameReady);
1475
1476 // Phase 4: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001477 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001478
Jeff Brown2175e9c2014-09-12 16:11:07 -07001479 // Phase 5: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001480 // Because we might release the last suspend blocker here, we need to make sure
1481 // we finished everything else first!
1482 updateSuspendBlockerLocked();
1483 } finally {
1484 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
Jeff Brown96307042012-07-27 15:51:34 -07001486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487
Jim Miller92e66dd2012-02-21 18:57:12 -08001488 /**
Jeff Brown96307042012-07-27 15:51:34 -07001489 * Updates the value of mIsPowered.
1490 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001491 */
Jeff Brown96307042012-07-27 15:51:34 -07001492 private void updateIsPoweredLocked(int dirty) {
1493 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001494 final boolean wasPowered = mIsPowered;
1495 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001496 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001497 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1498 mPlugType = mBatteryManagerInternal.getPlugType();
1499 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1500 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001501
Jeff Brown26875502014-01-30 21:47:47 -08001502 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001503 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001504 + ", mIsPowered=" + mIsPowered
1505 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001506 + ", mPlugType=" + mPlugType
1507 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001508 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001509
Jeff Brownf3fb8952012-10-02 20:57:05 -07001510 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001511 mDirty |= DIRTY_IS_POWERED;
1512
Jeff Brown3b971592013-01-09 18:46:37 -08001513 // Update wireless dock detection state.
1514 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1515 mIsPowered, mPlugType, mBatteryLevel);
1516
Jeff Brown96307042012-07-27 15:51:34 -07001517 // Treat plugging and unplugging the devices as a user activity.
1518 // Users find it disconcerting when they plug or unplug the device
1519 // and it shuts off right away.
1520 // Some devices also wake the device when plugged or unplugged because
1521 // they don't have a charging LED.
1522 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001523 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1524 dockedOnWirelessCharger)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001525 wakeUpNoUpdateLocked(now, "android.server.power:POWER", Process.SYSTEM_UID,
1526 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001527 }
1528 userActivityNoUpdateLocked(
1529 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001530
1531 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001532 // it can provide feedback to the user.
1533 if (dockedOnWirelessCharger) {
Jeff Brown84e27562012-12-07 13:56:34 -08001534 mNotifier.onWirelessChargingStarted();
1535 }
Jeff Brown96307042012-07-27 15:51:34 -07001536 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001537
Dianne Hackborn14272302014-06-10 23:13:02 -07001538 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) {
John Spurlock1bb480a2014-08-02 17:12:43 -04001539 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) {
1540 if (DEBUG_SPEW) {
1541 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze");
1542 }
1543 mAutoLowPowerModeSnoozing = false;
1544 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001545 updateLowPowerModeLocked();
1546 }
Jeff Brown96307042012-07-27 15:51:34 -07001547 }
1548 }
1549
Jeff Brown3b971592013-01-09 18:46:37 -08001550 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1551 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001552 // Don't wake when powered unless configured to do so.
1553 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1554 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001555 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001556
Jeff Brown3b971592013-01-09 18:46:37 -08001557 // Don't wake when undocked from wireless charger.
1558 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001559 if (wasPowered && !mIsPowered
1560 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1561 return false;
1562 }
Jeff Brown3b971592013-01-09 18:46:37 -08001563
1564 // Don't wake when docked on wireless charger unless we are certain of it.
1565 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001566 if (!wasPowered && mIsPowered
1567 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001568 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001569 return false;
1570 }
1571
1572 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001573 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001574 return false;
1575 }
1576
Bryce Lee584a4452014-10-21 15:55:55 -07001577 // Don't wake while theater mode is enabled.
1578 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1579 return false;
1580 }
1581
Jeff Brown9fca9e92012-10-05 14:42:56 -07001582 // Otherwise wake up!
1583 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001584 }
1585
Jeff Brown96307042012-07-27 15:51:34 -07001586 /**
1587 * Updates the value of mStayOn.
1588 * Sets DIRTY_STAY_ON if a change occurred.
1589 */
1590 private void updateStayOnLocked(int dirty) {
1591 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001592 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001593 if (mStayOnWhilePluggedInSetting != 0
1594 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001595 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001596 } else {
1597 mStayOn = false;
1598 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001599
1600 if (mStayOn != wasStayOn) {
1601 mDirty |= DIRTY_STAY_ON;
1602 }
Jeff Brown96307042012-07-27 15:51:34 -07001603 }
1604 }
1605
1606 /**
1607 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1608 * Note that most wake-locks are ignored when the system is asleep.
1609 *
1610 * This function must have no other side-effects.
1611 */
Jeff Brownec083212013-09-11 20:45:25 -07001612 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001613 private void updateWakeLockSummaryLocked(int dirty) {
1614 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1615 mWakeLockSummary = 0;
1616
1617 final int numWakeLocks = mWakeLocks.size();
1618 for (int i = 0; i < numWakeLocks; i++) {
1619 final WakeLock wakeLock = mWakeLocks.get(i);
1620 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1621 case PowerManager.PARTIAL_WAKE_LOCK:
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001622 if (!wakeLock.mDisabled) {
1623 // We only respect this if the wake lock is not disabled.
1624 mWakeLockSummary |= WAKE_LOCK_CPU;
1625 }
Jeff Brown96307042012-07-27 15:51:34 -07001626 break;
1627 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001628 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001629 break;
1630 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001631 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001632 break;
1633 case PowerManager.SCREEN_DIM_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001634 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001635 break;
1636 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001637 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001638 break;
Jeff Brown26875502014-01-30 21:47:47 -08001639 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001640 mWakeLockSummary |= WAKE_LOCK_DOZE;
Jeff Brown26875502014-01-30 21:47:47 -08001641 break;
Jeff Brownc2932a12014-11-20 18:04:05 -08001642 case PowerManager.DRAW_WAKE_LOCK:
1643 mWakeLockSummary |= WAKE_LOCK_DRAW;
1644 break;
Jeff Brown96307042012-07-27 15:51:34 -07001645 }
1646 }
1647
Jeff Brown037c33e2014-04-09 00:31:55 -07001648 // Cancel wake locks that make no sense based on the current state.
1649 if (mWakefulness != WAKEFULNESS_DOZING) {
Jeff Brownc2932a12014-11-20 18:04:05 -08001650 mWakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
Jeff Brown037c33e2014-04-09 00:31:55 -07001651 }
1652 if (mWakefulness == WAKEFULNESS_ASLEEP
1653 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1654 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1655 | WAKE_LOCK_BUTTON_BRIGHT);
1656 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1657 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1658 }
1659 }
1660
1661 // Infer implied wake locks where necessary based on the current state.
1662 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1663 if (mWakefulness == WAKEFULNESS_AWAKE) {
1664 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1665 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1666 mWakeLockSummary |= WAKE_LOCK_CPU;
1667 }
1668 }
Jeff Brownc2932a12014-11-20 18:04:05 -08001669 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1670 mWakeLockSummary |= WAKE_LOCK_CPU;
1671 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001672
Jeff Brown96307042012-07-27 15:51:34 -07001673 if (DEBUG_SPEW) {
1674 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001675 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001676 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1677 }
1678 }
1679 }
1680
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001681 void checkForLongWakeLocks() {
1682 synchronized (mLock) {
1683 final long now = SystemClock.uptimeMillis();
1684 mNotifyLongDispatched = now;
1685 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1686 long nextCheckTime = Long.MAX_VALUE;
1687 final int numWakeLocks = mWakeLocks.size();
1688 for (int i = 0; i < numWakeLocks; i++) {
1689 final WakeLock wakeLock = mWakeLocks.get(i);
1690 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1691 == PowerManager.PARTIAL_WAKE_LOCK) {
1692 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1693 if (wakeLock.mAcquireTime < when) {
1694 // This wake lock has exceeded the long acquire time, report!
1695 notifyWakeLockLongStartedLocked(wakeLock);
1696 } else {
1697 // This wake lock could still become a long one, at this time.
1698 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1699 if (checkTime < nextCheckTime) {
1700 nextCheckTime = checkTime;
1701 }
1702 }
1703 }
1704 }
1705 }
1706 mNotifyLongScheduled = 0;
1707 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
1708 if (nextCheckTime != Long.MAX_VALUE) {
1709 mNotifyLongNextCheck = nextCheckTime;
1710 enqueueNotifyLongMsgLocked(nextCheckTime);
1711 } else {
1712 mNotifyLongNextCheck = 0;
1713 }
1714 }
1715 }
1716
Jeff Brown96307042012-07-27 15:51:34 -07001717 /**
1718 * Updates the value of mUserActivitySummary to summarize the user requested
1719 * state of the system such as whether the screen should be bright or dim.
1720 * Note that user activity is ignored when the system is asleep.
1721 *
1722 * This function must have no other side-effects.
1723 */
1724 private void updateUserActivitySummaryLocked(long now, int dirty) {
1725 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07001726 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08001727 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001728 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1729
1730 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001731 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07001732 || mWakefulness == WAKEFULNESS_DREAMING
1733 || mWakefulness == WAKEFULNESS_DOZING) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001734 final int sleepTimeout = getSleepTimeoutLocked();
1735 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07001736 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001737 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Jeff Brown96307042012-07-27 15:51:34 -07001738
1739 mUserActivitySummary = 0;
1740 if (mLastUserActivityTime >= mLastWakeTime) {
1741 nextTimeout = mLastUserActivityTime
1742 + screenOffTimeout - screenDimDuration;
1743 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001744 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001745 } else {
1746 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1747 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001748 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001749 }
1750 }
1751 }
1752 if (mUserActivitySummary == 0
1753 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1754 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07001755 if (now < nextTimeout) {
1756 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) {
1757 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
1758 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
1759 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
1760 }
Jeff Brown96307042012-07-27 15:51:34 -07001761 }
1762 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001763
Jeff Brown05af6ad2014-09-30 20:54:30 -07001764 if (mUserActivitySummary == 0) {
1765 if (sleepTimeout >= 0) {
1766 final long anyUserActivity = Math.max(mLastUserActivityTime,
1767 mLastUserActivityTimeNoChangeLights);
1768 if (anyUserActivity >= mLastWakeTime) {
1769 nextTimeout = anyUserActivity + sleepTimeout;
1770 if (now < nextTimeout) {
1771 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1772 }
1773 }
1774 } else {
1775 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1776 nextTimeout = -1;
1777 }
1778 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001779
1780 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07001781 if ((mUserActivitySummary &
1782 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001783 // Device is being kept awake by recent user activity
1784 if (nextTimeout >= now && mOverriddenTimeout == -1) {
1785 // Save when the next timeout would have occurred
1786 mOverriddenTimeout = nextTimeout;
1787 }
Mojtaba2d80edc2015-09-18 16:35:24 -07001788 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001789 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1790 nextTimeout = -1;
1791 }
1792
Jeff Brown05af6ad2014-09-30 20:54:30 -07001793 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001794 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1795 msg.setAsynchronous(true);
1796 mHandler.sendMessageAtTime(msg, nextTimeout);
1797 }
1798 } else {
1799 mUserActivitySummary = 0;
1800 }
1801
1802 if (DEBUG_SPEW) {
1803 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001804 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001805 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1806 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1807 }
1808 }
1809 }
1810
1811 /**
1812 * Called when a user activity timeout has occurred.
1813 * Simply indicates that something about user activity has changed so that the new
1814 * state can be recomputed when the power state is updated.
1815 *
1816 * This function must have no other side-effects besides setting the dirty
1817 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
1818 */
1819 private void handleUserActivityTimeout() { // runs on handler thread
1820 synchronized (mLock) {
1821 if (DEBUG_SPEW) {
1822 Slog.d(TAG, "handleUserActivityTimeout");
1823 }
1824
1825 mDirty |= DIRTY_USER_ACTIVITY;
1826 updatePowerStateLocked();
1827 }
1828 }
1829
Jeff Brown05af6ad2014-09-30 20:54:30 -07001830 private int getSleepTimeoutLocked() {
1831 int timeout = mSleepTimeoutSetting;
1832 if (timeout <= 0) {
1833 return -1;
1834 }
1835 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
1836 }
1837
1838 private int getScreenOffTimeoutLocked(int sleepTimeout) {
Jeff Brown96307042012-07-27 15:51:34 -07001839 int timeout = mScreenOffTimeoutSetting;
1840 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1841 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1842 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001843 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1844 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1845 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07001846 if (sleepTimeout >= 0) {
1847 timeout = Math.min(timeout, sleepTimeout);
1848 }
Jeff Brown27736f52014-05-20 17:17:10 -07001849 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07001850 }
1851
Jeff Brownff532542012-10-02 21:18:04 -07001852 private int getScreenDimDurationLocked(int screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07001853 return Math.min(mMaximumScreenDimDurationConfig,
1854 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07001855 }
1856
1857 /**
1858 * Updates the wakefulness of the device.
1859 *
Jeff Brown26875502014-01-30 21:47:47 -08001860 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07001861 * based on the current wake locks and user activity state. It may modify mDirty
1862 * if the wakefulness changes.
1863 *
1864 * Returns true if the wakefulness changed and we need to restart power state calculation.
1865 */
1866 private boolean updateWakefulnessLocked(int dirty) {
1867 boolean changed = false;
1868 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07001869 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1870 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001871 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1872 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001873 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07001874 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001875 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07001876 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001877 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001878 } else {
1879 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07001880 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001881 }
Jeff Brown96307042012-07-27 15:51:34 -07001882 }
1883 }
1884 return changed;
1885 }
1886
Jeff Brown645832d2012-10-03 14:57:03 -07001887 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07001888 * Returns true if the device should automatically nap and start dreaming when the user
1889 * activity timeout has expired and it's bedtime.
1890 */
1891 private boolean shouldNapAtBedTimeLocked() {
1892 return mDreamsActivateOnSleepSetting
1893 || (mDreamsActivateOnDockSetting
1894 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1895 }
1896
1897 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001898 * Returns true if the device should go to sleep now.
1899 * Also used when exiting a dream to determine whether we should go back
1900 * to being fully awake or else go to sleep for good.
1901 */
Jeff Brown96307042012-07-27 15:51:34 -07001902 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001903 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07001904 }
1905
1906 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07001907 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07001908 * or the stay on while powered setting. We also keep the phone awake when
1909 * the proximity sensor returns a positive result so that the device does not
1910 * lock while in a phone call. This function only controls whether the device
1911 * will go to sleep or dream which is independent of whether it will be allowed
1912 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07001913 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07001914 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001915 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07001916 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07001917 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07001918 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001919 | USER_ACTIVITY_SCREEN_DIM)) != 0
1920 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07001921 }
1922
1923 /**
1924 * Determines whether to post a message to the sandman to update the dream state.
1925 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07001926 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001927 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07001928 | DIRTY_USER_ACTIVITY
1929 | DIRTY_WAKE_LOCKS
1930 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001931 | DIRTY_SETTINGS
1932 | DIRTY_IS_POWERED
1933 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07001934 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07001935 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
1936 if (mDisplayReady) {
1937 scheduleSandmanLocked();
1938 }
Jeff Brown96307042012-07-27 15:51:34 -07001939 }
1940 }
1941
1942 private void scheduleSandmanLocked() {
1943 if (!mSandmanScheduled) {
1944 mSandmanScheduled = true;
1945 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1946 msg.setAsynchronous(true);
1947 mHandler.sendMessage(msg);
1948 }
1949 }
1950
1951 /**
Jeff Brown26875502014-01-30 21:47:47 -08001952 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07001953 *
1954 * We do this asynchronously because we must call out of the power manager to start
1955 * the dream and we don't want to hold our lock while doing so. There is a risk that
1956 * the device will wake or go to sleep in the meantime so we have to handle that case.
1957 */
1958 private void handleSandman() { // runs on handler thread
1959 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08001960 final boolean startDreaming;
1961 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07001962 synchronized (mLock) {
1963 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08001964 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07001965 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001966 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08001967 mSandmanSummoned = false;
1968 } else {
1969 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001970 }
1971 }
1972
Jeff Brown96307042012-07-27 15:51:34 -07001973 // Start dreaming if needed.
1974 // We only control the dream on the handler thread, so we don't need to worry about
1975 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08001976 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07001977 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08001978 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07001979 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07001980 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08001981 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07001982 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001983 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08001984 } else {
1985 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001986 }
1987
1988 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07001989 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08001990 // Remember the initial battery level when the dream started.
1991 if (startDreaming && isDreaming) {
1992 mBatteryLevelWhenDreamStarted = mBatteryLevel;
1993 if (wakefulness == WAKEFULNESS_DOZING) {
1994 Slog.i(TAG, "Dozing...");
1995 } else {
1996 Slog.i(TAG, "Dreaming...");
1997 }
1998 }
1999
2000 // If preconditions changed, wait for the next iteration to determine
2001 // whether the dream should continue (or be restarted).
2002 if (mSandmanSummoned || mWakefulness != wakefulness) {
2003 return; // wait for next cycle
2004 }
2005
2006 // Determine whether the dream should continue.
2007 if (wakefulness == WAKEFULNESS_DREAMING) {
2008 if (isDreaming && canDreamLocked()) {
2009 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002010 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002011 - mDreamsBatteryLevelDrainCutoffConfig
2012 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002013 // If the user activity timeout expired and the battery appears
2014 // to be draining faster than it is charging then stop dreaming
2015 // and go to sleep.
2016 Slog.i(TAG, "Stopping dream because the battery appears to "
2017 + "be draining faster than it is charging. "
2018 + "Battery level when dream started: "
2019 + mBatteryLevelWhenDreamStarted + "%. "
2020 + "Battery level now: " + mBatteryLevel + "%.");
2021 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002022 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002023 }
Jeff Brown96307042012-07-27 15:51:34 -07002024 }
Jeff Brown26875502014-01-30 21:47:47 -08002025
2026 // Dream has ended or will be stopped. Update the power state.
2027 if (isItBedTimeYetLocked()) {
2028 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002029 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002030 updatePowerStateLocked();
2031 } else {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07002032 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), "android.server.power:DREAM",
2033 Process.SYSTEM_UID, mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002034 updatePowerStateLocked();
2035 }
2036 } else if (wakefulness == WAKEFULNESS_DOZING) {
2037 if (isDreaming) {
2038 return; // continue dozing
2039 }
2040
2041 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002042 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002043 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002044 }
Jeff Brown96307042012-07-27 15:51:34 -07002045 }
2046
Jeff Brown26875502014-01-30 21:47:47 -08002047 // Stop dream.
2048 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002049 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002050 }
2051 }
2052
2053 /**
Jeff Brown26875502014-01-30 21:47:47 -08002054 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002055 */
2056 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002057 if (mWakefulness != WAKEFULNESS_DREAMING
2058 || !mDreamsSupportedConfig
2059 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002060 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordond6a56602016-09-20 15:50:35 -07002061 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002062 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2063 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002064 || !mBootCompleted) {
2065 return false;
2066 }
2067 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002068 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002069 return false;
2070 }
2071 if (!mIsPowered
2072 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2073 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2074 return false;
2075 }
2076 if (mIsPowered
2077 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2078 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2079 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002080 }
2081 }
Jeff Brown26875502014-01-30 21:47:47 -08002082 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002083 }
2084
Jeff Brown96307042012-07-27 15:51:34 -07002085 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002086 * Returns true if the device is allowed to doze in its current state.
2087 */
2088 private boolean canDozeLocked() {
2089 return mWakefulness == WAKEFULNESS_DOZING;
2090 }
2091
2092 /**
Jeff Brown96307042012-07-27 15:51:34 -07002093 * Updates the display power state asynchronously.
2094 * When the update is finished, mDisplayReady will be set to true. The display
2095 * controller posts a message to tell us when the actual display power state
2096 * has been updated so we come back here to double-check and finish up.
2097 *
2098 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002099 *
2100 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002101 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002102 private boolean updateDisplayPowerStateLocked(int dirty) {
2103 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002104 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2105 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordond6a56602016-09-20 15:50:35 -07002106 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002107 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002108
Jeff Browne333e672014-10-28 13:48:55 -07002109 // Determine appropriate screen brightness and auto-brightness adjustments.
Jeff Browna576b4d2015-04-23 19:58:06 -07002110 boolean brightnessSetByUser = true;
Jeff Brown96307042012-07-27 15:51:34 -07002111 int screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07002112 float screenAutoBrightnessAdjustment = 0.0f;
Jeff Brown96307042012-07-27 15:51:34 -07002113 boolean autoBrightness = (mScreenBrightnessModeSetting ==
2114 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Michael Wright9f818ea2016-07-29 19:59:39 +01002115 if (!mBootCompleted) {
2116 // Keep the brightness steady during boot. This requires the
2117 // bootloader brightness and the default brightness to be identical.
2118 autoBrightness = false;
2119 brightnessSetByUser = false;
Santos Cordond6a56602016-09-20 15:50:35 -07002120 } else if (mIsVrModeEnabled) {
2121 screenBrightness = mScreenBrightnessForVrSetting;
2122 autoBrightness = false;
Michael Wright9f818ea2016-07-29 19:59:39 +01002123 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002124 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
2125 autoBrightness = false;
Jeff Browna576b4d2015-04-23 19:58:06 -07002126 brightnessSetByUser = false;
Jeff Brown96307042012-07-27 15:51:34 -07002127 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
2128 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
2129 } else if (isValidBrightness(mScreenBrightnessSetting)) {
Jeff Brown330560f2012-08-21 22:10:57 -07002130 screenBrightness = mScreenBrightnessSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002131 }
2132 if (autoBrightness) {
2133 screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07002134 if (isValidAutoBrightnessAdjustment(
2135 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
2136 screenAutoBrightnessAdjustment =
2137 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
2138 } else if (isValidAutoBrightnessAdjustment(
2139 mScreenAutoBrightnessAdjustmentSetting)) {
2140 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
2141 }
Jeff Brown96307042012-07-27 15:51:34 -07002142 }
2143 screenBrightness = Math.max(Math.min(screenBrightness,
2144 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
Jeff Brown330560f2012-08-21 22:10:57 -07002145 screenAutoBrightnessAdjustment = Math.max(Math.min(
2146 screenAutoBrightnessAdjustment, 1.0f), -1.0f);
Jeff Browne333e672014-10-28 13:48:55 -07002147
2148 // Update display power request.
Jeff Brown96307042012-07-27 15:51:34 -07002149 mDisplayPowerRequest.screenBrightness = screenBrightness;
Jeff Brown330560f2012-08-21 22:10:57 -07002150 mDisplayPowerRequest.screenAutoBrightnessAdjustment =
2151 screenAutoBrightnessAdjustment;
Jeff Browna576b4d2015-04-23 19:58:06 -07002152 mDisplayPowerRequest.brightnessSetByUser = brightnessSetByUser;
Jeff Brown96307042012-07-27 15:51:34 -07002153 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002154 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002155 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled;
Santos Cordond6a56602016-09-20 15:50:35 -07002156 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Jason Monk5dbd4aa2016-02-07 13:13:39 -05002157 mDisplayPowerRequest.useTwilight = mBrightnessUseTwilight;
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002158
Jeff Brown970d4132014-07-19 11:33:47 -07002159 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2160 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Jeff Brownc2932a12014-11-20 18:04:05 -08002161 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND
2162 && (mWakeLockSummary & WAKE_LOCK_DRAW) != 0) {
2163 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2164 }
Jeff Brown970d4132014-07-19 11:33:47 -07002165 mDisplayPowerRequest.dozeScreenBrightness =
2166 mDozeScreenBrightnessOverrideFromDreamManager;
2167 } else {
2168 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2169 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2170 }
2171
Jeff Brown131206b2014-04-08 17:27:14 -07002172 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002173 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002174 mRequestWaitForNegativeProximity = false;
2175
2176 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002177 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002178 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002179 + ", mWakefulness=" + mWakefulness
2180 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2181 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002182 + ", mBootCompleted=" + mBootCompleted
Santos Cordond6a56602016-09-20 15:50:35 -07002183 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Jeff Browne333e672014-10-28 13:48:55 -07002184 + ", mScreenBrightnessBoostInProgress="
2185 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07002186 }
2187 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002188 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002189 }
2190
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002191 private void updateScreenBrightnessBoostLocked(int dirty) {
2192 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2193 if (mScreenBrightnessBoostInProgress) {
2194 final long now = SystemClock.uptimeMillis();
2195 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2196 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2197 final long boostTimeout = mLastScreenBrightnessBoostTime +
2198 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2199 if (boostTimeout > now) {
2200 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2201 msg.setAsynchronous(true);
2202 mHandler.sendMessageAtTime(msg, boostTimeout);
2203 return;
2204 }
Jeff Browne333e672014-10-28 13:48:55 -07002205 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002206 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002207 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002208 userActivityNoUpdateLocked(now,
2209 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002210 }
Jeff Browne333e672014-10-28 13:48:55 -07002211 }
2212 }
2213
Santos Cordond6a56602016-09-20 15:50:35 -07002214 private boolean shouldBoostScreenBrightness() {
2215 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2216 }
2217
Jeff Brown96307042012-07-27 15:51:34 -07002218 private static boolean isValidBrightness(int value) {
2219 return value >= 0 && value <= 255;
2220 }
2221
Jeff Brown330560f2012-08-21 22:10:57 -07002222 private static boolean isValidAutoBrightnessAdjustment(float value) {
Jeff Brown5d03a532012-08-22 13:22:02 -07002223 // Handles NaN by always returning false.
2224 return value >= -1.0f && value <= 1.0f;
Jeff Brown330560f2012-08-21 22:10:57 -07002225 }
2226
Jeff Brown970d4132014-07-19 11:33:47 -07002227 private int getDesiredScreenPolicyLocked() {
Santos Cordond6a56602016-09-20 15:50:35 -07002228 if (mIsVrModeEnabled) {
2229 return DisplayPowerRequest.POLICY_VR;
2230 }
2231
Jeff Brown96307042012-07-27 15:51:34 -07002232 if (mWakefulness == WAKEFULNESS_ASLEEP) {
Jeff Brown970d4132014-07-19 11:33:47 -07002233 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002234 }
2235
Jeff Brown2175e9c2014-09-12 16:11:07 -07002236 if (mWakefulness == WAKEFULNESS_DOZING) {
2237 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2238 return DisplayPowerRequest.POLICY_DOZE;
2239 }
2240 if (mDozeAfterScreenOffConfig) {
2241 return DisplayPowerRequest.POLICY_OFF;
2242 }
2243 // Fall through and preserve the current screen policy if not configured to
2244 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002245 }
2246
Jeff Brown96307042012-07-27 15:51:34 -07002247 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2248 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002249 || !mBootCompleted
2250 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002251 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002252 }
2253
Jeff Brown970d4132014-07-19 11:33:47 -07002254 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002255 }
2256
Jeff Brown131206b2014-04-08 17:27:14 -07002257 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2258 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002259 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002260
Jeff Brown96307042012-07-27 15:51:34 -07002261 @Override
2262 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002263 synchronized (mLock) {
2264 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2265 updatePowerStateLocked();
2266 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002267 }
2268
2269 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002270 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002271 synchronized (mLock) {
2272 mProximityPositive = true;
2273 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2274 updatePowerStateLocked();
2275 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002276 }
2277
2278 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002279 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002280 synchronized (mLock) {
2281 mProximityPositive = false;
2282 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2283 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2284 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2285 updatePowerStateLocked();
2286 }
Jeff Brown96307042012-07-27 15:51:34 -07002287 }
Jeff Brown131206b2014-04-08 17:27:14 -07002288
2289 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002290 public void onDisplayStateChange(int state) {
2291 // This method is only needed to support legacy display blanking behavior
2292 // where the display's power state is coupled to suspend or to the power HAL.
2293 // The order of operations matters here.
2294 synchronized (mLock) {
2295 if (mDisplayState != state) {
2296 mDisplayState = state;
2297 if (state == Display.STATE_OFF) {
2298 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2299 setHalInteractiveModeLocked(false);
2300 }
2301 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2302 setHalAutoSuspendModeLocked(true);
2303 }
2304 } else {
2305 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2306 setHalAutoSuspendModeLocked(false);
2307 }
2308 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2309 setHalInteractiveModeLocked(true);
2310 }
2311 }
2312 }
2313 }
2314 }
2315
2316 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002317 public void acquireSuspendBlocker() {
2318 mDisplaySuspendBlocker.acquire();
2319 }
2320
2321 @Override
2322 public void releaseSuspendBlocker() {
2323 mDisplaySuspendBlocker.release();
2324 }
2325
2326 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002327 public String toString() {
2328 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002329 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002330 }
2331 }
Jeff Brown96307042012-07-27 15:51:34 -07002332 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002333
Jeff Brown96307042012-07-27 15:51:34 -07002334 private boolean shouldUseProximitySensorLocked() {
Santos Cordond6a56602016-09-20 15:50:35 -07002335 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002336 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002337
Jeff Brown96307042012-07-27 15:51:34 -07002338 /**
2339 * Updates the suspend blocker that keeps the CPU alive.
2340 *
2341 * This function must have no other side-effects.
2342 */
2343 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002344 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002345 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2346 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002347 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002348
2349 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002350 // FIXME We should consider just leaving auto-suspend enabled forever since
2351 // we already hold the necessary wakelocks.
2352 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2353 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002354 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002355
2356 // First acquire suspend blockers if needed.
2357 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2358 mWakeLockSuspendBlocker.acquire();
2359 mHoldingWakeLockSuspendBlocker = true;
2360 }
2361 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2362 mDisplaySuspendBlocker.acquire();
2363 mHoldingDisplaySuspendBlocker = true;
2364 }
2365
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002366 // Inform the power HAL about interactive mode.
2367 // Although we could set interactive strictly based on the wakefulness
2368 // as reported by isInteractive(), it is actually more desirable to track
2369 // the display policy state instead so that the interactive state observed
2370 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2371 // Refer to getDesiredScreenPolicyLocked() for details.
2372 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2373 // When becoming non-interactive, we want to defer sending this signal
2374 // until the display is actually ready so that all transitions have
2375 // completed. This is probably a good sign that things have gotten
2376 // too tangled over here...
2377 if (interactive || mDisplayReady) {
2378 setHalInteractiveModeLocked(interactive);
2379 }
2380 }
2381
Jeff Brown27f7a862012-12-12 15:43:31 -08002382 // Then release suspend blockers if needed.
2383 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2384 mWakeLockSuspendBlocker.release();
2385 mHoldingWakeLockSuspendBlocker = false;
2386 }
2387 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2388 mDisplaySuspendBlocker.release();
2389 mHoldingDisplaySuspendBlocker = false;
2390 }
Jeff Brown26875502014-01-30 21:47:47 -08002391
2392 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002393 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2394 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002395 }
Jeff Brown96307042012-07-27 15:51:34 -07002396 }
2397
Jeff Brownec083212013-09-11 20:45:25 -07002398 /**
2399 * Return true if we must keep a suspend blocker active on behalf of the display.
2400 * We do so if the screen is on or is in transition between states.
2401 */
Jeff Brown26875502014-01-30 21:47:47 -08002402 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002403 if (!mDisplayReady) {
2404 return true;
2405 }
Jeff Brown970d4132014-07-19 11:33:47 -07002406 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002407 // If we asked for the screen to be on but it is off due to the proximity
2408 // sensor then we may suspend but only if the configuration allows it.
2409 // On some hardware it may not be safe to suspend because the proximity
2410 // sensor may not be correctly configured as a wake-up source.
2411 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2412 || !mSuspendWhenScreenOffDueToProximityConfig) {
2413 return true;
2414 }
2415 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002416 if (mScreenBrightnessBoostInProgress) {
2417 return true;
2418 }
Jeff Brown26875502014-01-30 21:47:47 -08002419 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002420 return false;
2421 }
2422
Jeff Brown037c33e2014-04-09 00:31:55 -07002423 private void setHalAutoSuspendModeLocked(boolean enable) {
2424 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002425 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002426 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002427 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002428 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002429 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2430 try {
2431 nativeSetAutoSuspend(enable);
2432 } finally {
2433 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2434 }
Jeff Brown26875502014-01-30 21:47:47 -08002435 }
2436 }
2437
Jeff Brown037c33e2014-04-09 00:31:55 -07002438 private void setHalInteractiveModeLocked(boolean enable) {
2439 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002440 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002441 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002442 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002443 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002444 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2445 try {
2446 nativeSetInteractive(enable);
2447 } finally {
2448 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2449 }
Jeff Brown26875502014-01-30 21:47:47 -08002450 }
2451 }
2452
Jeff Brown037c33e2014-04-09 00:31:55 -07002453 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002454 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002455 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002456 }
2457 }
2458
Dianne Hackborneb94fa72014-06-03 17:48:12 -07002459 private boolean isLowPowerModeInternal() {
2460 synchronized (mLock) {
2461 return mLowPowerModeEnabled;
2462 }
2463 }
2464
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002465 private boolean setLowPowerModeInternal(boolean mode) {
2466 synchronized (mLock) {
2467 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered);
2468 if (mIsPowered) {
2469 return false;
2470 }
2471 Settings.Global.putInt(mContext.getContentResolver(),
2472 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0);
2473 mLowPowerModeSetting = mode;
2474
2475 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) {
2476 if (mode && mAutoLowPowerModeSnoozing) {
2477 if (DEBUG_SPEW) {
2478 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze");
2479 }
2480 mAutoLowPowerModeSnoozing = false;
2481 } else if (!mode && !mAutoLowPowerModeSnoozing) {
2482 if (DEBUG_SPEW) {
2483 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode");
2484 }
2485 mAutoLowPowerModeSnoozing = true;
2486 }
2487 }
2488
2489 updateLowPowerModeLocked();
2490 return true;
2491 }
2492 }
2493
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002494 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002495 synchronized (mLock) {
2496 return mDeviceIdleMode;
2497 }
2498 }
2499
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002500 boolean isLightDeviceIdleModeInternal() {
2501 synchronized (mLock) {
2502 return mLightDeviceIdleMode;
2503 }
2504 }
2505
Jeff Brown96307042012-07-27 15:51:34 -07002506 private void handleBatteryStateChangedLocked() {
2507 mDirty |= DIRTY_BATTERY_STATE;
2508 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002509 }
2510
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002511 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002512 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002513 if (mHandler == null || !mSystemReady) {
Jeff Brownab887a02012-10-15 16:00:40 -07002514 throw new IllegalStateException("Too early to call shutdown() or reboot()");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002515 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002516
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002517 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002518 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002519 public void run() {
2520 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002521 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
2522 ShutdownThread.rebootSafeMode(mContext, confirm);
2523 } else if (haltMode == HALT_MODE_REBOOT) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002524 ShutdownThread.reboot(mContext, reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002525 } else {
2526 ShutdownThread.shutdown(mContext, reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002527 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002528 }
San Mehat1e512792010-01-07 10:40:29 -08002529 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002530 };
Jeff Brown96307042012-07-27 15:51:34 -07002531
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002532 // ShutdownThread must run on a looper capable of displaying the UI.
Jeff Brown96307042012-07-27 15:51:34 -07002533 Message msg = Message.obtain(mHandler, runnable);
2534 msg.setAsynchronous(true);
2535 mHandler.sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002536
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002537 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002538 if (wait) {
2539 synchronized (runnable) {
2540 while (true) {
2541 try {
2542 runnable.wait();
2543 } catch (InterruptedException e) {
2544 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002545 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002546 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002547 }
2548 }
2549
Jeff Brown96307042012-07-27 15:51:34 -07002550 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002551 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002552 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002553 public void run() {
2554 throw new RuntimeException(message);
2555 }
Dan Egnor60d87622009-12-16 16:32:58 -08002556 };
2557 try {
2558 t.start();
2559 t.join();
2560 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002561 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002562 }
2563 }
2564
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002565 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002566 Settings.Global.putInt(mContext.getContentResolver(),
2567 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002570 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
Jeff Brown96307042012-07-27 15:51:34 -07002571 synchronized (mLock) {
2572 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2573 mDirty |= DIRTY_SETTINGS;
2574 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 }
2577
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002578 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002579 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002580 if (mDeviceIdleMode == enabled) {
2581 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002582 }
Felipe Lemeea014392016-09-06 13:59:54 -07002583 mDeviceIdleMode = enabled;
2584 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002585 }
Felipe Lemeea014392016-09-06 13:59:54 -07002586 if (enabled) {
2587 EventLogTags.writeDeviceIdleOnPhase("power");
2588 } else {
2589 EventLogTags.writeDeviceIdleOffPhase("power");
2590 }
2591 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002592 }
2593
2594 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2595 synchronized (mLock) {
2596 if (mLightDeviceIdleMode != enabled) {
2597 mLightDeviceIdleMode = enabled;
2598 return true;
2599 }
2600 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002601 }
2602 }
2603
2604 void setDeviceIdleWhitelistInternal(int[] appids) {
2605 synchronized (mLock) {
2606 mDeviceIdleWhitelist = appids;
2607 if (mDeviceIdleMode) {
2608 updateWakeLockDisabledStatesLocked();
2609 }
2610 }
2611 }
2612
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002613 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2614 synchronized (mLock) {
2615 mDeviceIdleTempWhitelist = appids;
2616 if (mDeviceIdleMode) {
2617 updateWakeLockDisabledStatesLocked();
2618 }
2619 }
2620 }
2621
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002622 void updateUidProcStateInternal(int uid, int procState) {
2623 synchronized (mLock) {
2624 mUidState.put(uid, procState);
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002625 if (mDeviceIdleMode) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002626 updateWakeLockDisabledStatesLocked();
2627 }
2628 }
2629 }
2630
2631 void uidGoneInternal(int uid) {
2632 synchronized (mLock) {
2633 mUidState.delete(uid);
2634 if (mDeviceIdleMode) {
2635 updateWakeLockDisabledStatesLocked();
2636 }
2637 }
2638 }
2639
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002640 private void updateWakeLockDisabledStatesLocked() {
2641 boolean changed = false;
2642 final int numWakeLocks = mWakeLocks.size();
2643 for (int i = 0; i < numWakeLocks; i++) {
2644 final WakeLock wakeLock = mWakeLocks.get(i);
2645 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002646 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002647 if (setWakeLockDisabledStateLocked(wakeLock)) {
2648 changed = true;
2649 if (wakeLock.mDisabled) {
2650 // This wake lock is no longer being respected.
2651 notifyWakeLockReleasedLocked(wakeLock);
2652 } else {
2653 notifyWakeLockAcquiredLocked(wakeLock);
2654 }
2655 }
2656 }
2657 }
2658 if (changed) {
2659 mDirty |= DIRTY_WAKE_LOCKS;
2660 updatePowerStateLocked();
2661 }
2662 }
2663
2664 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
2665 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2666 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002667 boolean disabled = false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002668 if (mDeviceIdleMode) {
2669 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
2670 // If we are in idle mode, we will ignore all partial wake locks that are
2671 // for application uids that are not whitelisted.
2672 if (appid >= Process.FIRST_APPLICATION_UID &&
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002673 Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002674 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002675 mUidState.get(wakeLock.mOwnerUid,
2676 ActivityManager.PROCESS_STATE_CACHED_EMPTY)
2677 > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002678 disabled = true;
2679 }
2680 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002681 if (wakeLock.mDisabled != disabled) {
2682 wakeLock.mDisabled = disabled;
2683 return true;
2684 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002685 }
2686 return false;
2687 }
2688
Jeff Brown96307042012-07-27 15:51:34 -07002689 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
2690 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
2691 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002693
Jeff Brown96307042012-07-27 15:51:34 -07002694 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002695 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07002696 synchronized (mLock) {
2697 if (!mSystemReady) {
2698 return;
2699 }
2700 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002701 }
Jeff Brown96307042012-07-27 15:51:34 -07002702
2703 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002704 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07002705 }
2706
Jeff Browne333e672014-10-28 13:48:55 -07002707 private void boostScreenBrightnessInternal(long eventTime, int uid) {
2708 synchronized (mLock) {
2709 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
2710 || eventTime < mLastScreenBrightnessBoostTime) {
2711 return;
2712 }
2713
2714 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
2715 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002716 if (!mScreenBrightnessBoostInProgress) {
2717 mScreenBrightnessBoostInProgress = true;
2718 mNotifier.onScreenBrightnessBoostChanged();
2719 }
Jeff Browne333e672014-10-28 13:48:55 -07002720 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
2721
2722 userActivityNoUpdateLocked(eventTime,
2723 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
2724 updatePowerStateLocked();
2725 }
2726 }
2727
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002728 private boolean isScreenBrightnessBoostedInternal() {
2729 synchronized (mLock) {
2730 return mScreenBrightnessBoostInProgress;
2731 }
2732 }
2733
Jeff Browne333e672014-10-28 13:48:55 -07002734 /**
2735 * Called when a screen brightness boost timeout has occurred.
2736 *
2737 * This function must have no other side-effects besides setting the dirty
2738 * bit and calling update power state.
2739 */
2740 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
2741 synchronized (mLock) {
2742 if (DEBUG_SPEW) {
2743 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
2744 }
2745
2746 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
2747 updatePowerStateLocked();
2748 }
2749 }
2750
Jeff Brown96307042012-07-27 15:51:34 -07002751 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
2752 synchronized (mLock) {
2753 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
2754 mScreenBrightnessOverrideFromWindowManager = brightness;
2755 mDirty |= DIRTY_SETTINGS;
2756 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002757 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002758 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002759 }
2760
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002761 private void setUserInactiveOverrideFromWindowManagerInternal() {
2762 synchronized (mLock) {
2763 mUserInactiveOverrideFromWindowManager = true;
2764 mDirty |= DIRTY_USER_ACTIVITY;
2765 updatePowerStateLocked();
2766 }
2767 }
2768
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002769 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
2770 synchronized (mLock) {
2771 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
2772 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
2773 mDirty |= DIRTY_SETTINGS;
2774 updatePowerStateLocked();
2775 }
2776 }
2777 }
2778
Jeff Brown96307042012-07-27 15:51:34 -07002779 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
2780 synchronized (mLock) {
2781 if (mTemporaryScreenBrightnessSettingOverride != brightness) {
2782 mTemporaryScreenBrightnessSettingOverride = brightness;
2783 mDirty |= DIRTY_SETTINGS;
2784 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002785 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002786 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002787 }
2788
Jeff Brown330560f2012-08-21 22:10:57 -07002789 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
2790 synchronized (mLock) {
2791 // Note: This condition handles NaN because NaN is not equal to any other
2792 // value, including itself.
2793 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
2794 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
2795 mDirty |= DIRTY_SETTINGS;
2796 updatePowerStateLocked();
2797 }
2798 }
Jeff Brown96307042012-07-27 15:51:34 -07002799 }
2800
Jeff Brown970d4132014-07-19 11:33:47 -07002801 private void setDozeOverrideFromDreamManagerInternal(
2802 int screenState, int screenBrightness) {
2803 synchronized (mLock) {
2804 if (mDozeScreenStateOverrideFromDreamManager != screenState
2805 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
2806 mDozeScreenStateOverrideFromDreamManager = screenState;
2807 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
2808 mDirty |= DIRTY_SETTINGS;
2809 updatePowerStateLocked();
2810 }
2811 }
2812 }
2813
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07002814 private void powerHintInternal(int hintId, int data) {
2815 nativeSendPowerHint(hintId, data);
2816 }
2817
Jeff Brown96307042012-07-27 15:51:34 -07002818 /**
2819 * Low-level function turn the device off immediately, without trying
2820 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07002821 *
2822 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07002823 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07002824 public static void lowLevelShutdown(String reason) {
2825 if (reason == null) {
2826 reason = "";
2827 }
2828 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07002829 }
2830
2831 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08002832 * Low-level function to reboot the device. On success, this
2833 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07002834 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07002835 *
2836 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07002837 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002838 public static void lowLevelReboot(String reason) {
2839 if (reason == null) {
2840 reason = "";
2841 }
Tao Baoe8a403d2015-12-31 07:44:55 -08002842 if (reason.equals(PowerManager.REBOOT_RECOVERY)
2843 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
2844 SystemProperties.set("sys.powerctl", "reboot,recovery");
Doug Zongker3b0218b2014-01-14 12:29:06 -08002845 } else {
2846 SystemProperties.set("sys.powerctl", "reboot," + reason);
Doug Zongker3b0218b2014-01-14 12:29:06 -08002847 }
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002848 try {
Tao Bao90237f72015-05-21 16:25:19 -07002849 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002850 } catch (InterruptedException e) {
2851 Thread.currentThread().interrupt();
2852 }
Tao Bao90237f72015-05-21 16:25:19 -07002853 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07002854 }
2855
2856 @Override // Watchdog.Monitor implementation
2857 public void monitor() {
2858 // Grab and release lock for watchdog monitor to detect deadlocks.
2859 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002860 }
Jeff Brown96307042012-07-27 15:51:34 -07002861 }
2862
Jeff Brown6f357d32014-01-15 20:40:55 -08002863 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07002864 pw.println("POWER MANAGER (dumpsys power)\n");
2865
Jeff Brown3b971592013-01-09 18:46:37 -08002866 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07002867 synchronized (mLock) {
2868 pw.println("Power Manager State:");
2869 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08002870 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
2871 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07002872 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07002873 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07002874 pw.println(" mBatteryLevel=" + mBatteryLevel);
2875 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07002876 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07002877 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07002878 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07002879 pw.println(" mBootCompleted=" + mBootCompleted);
2880 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07002881 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
2882 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07002883 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07002884 pw.print(" mNotifyLongScheduled=");
2885 if (mNotifyLongScheduled == 0) {
2886 pw.print("(none)");
2887 } else {
2888 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
2889 }
2890 pw.println();
2891 pw.print(" mNotifyLongDispatched=");
2892 if (mNotifyLongDispatched == 0) {
2893 pw.print("(none)");
2894 } else {
2895 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
2896 }
2897 pw.println();
2898 pw.print(" mNotifyLongNextCheck=");
2899 if (mNotifyLongNextCheck == 0) {
2900 pw.print("(none)");
2901 } else {
2902 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
2903 }
2904 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07002905 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2906 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2907 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08002908 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07002909 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled);
2910 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002911 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002912 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
2913 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002914 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07002915 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2916 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Jeff Brown96307042012-07-27 15:51:34 -07002917 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2918 pw.println(" mLastUserActivityTimeNoChangeLights="
2919 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07002920 pw.println(" mLastInteractivePowerHintTime="
2921 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07002922 pw.println(" mLastScreenBrightnessBoostTime="
2923 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
2924 pw.println(" mScreenBrightnessBoostInProgress="
2925 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07002926 pw.println(" mDisplayReady=" + mDisplayReady);
2927 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08002928 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07002929
2930 pw.println();
2931 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07002932 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
2933 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
2934 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
2935 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002936 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
2937 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07002938 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
2939 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
2940 pw.println(" mTheaterModeEnabled="
2941 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07002942 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
2943 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002944 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002945 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2946 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
2947 + mDreamsActivatedOnSleepByDefaultConfig);
2948 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
2949 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08002950 pw.println(" mDreamsEnabledOnBatteryConfig="
2951 + mDreamsEnabledOnBatteryConfig);
2952 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
2953 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2954 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2955 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2956 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
2957 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002958 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04002959 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07002960 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown2175e9c2014-09-12 16:11:07 -07002961 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig);
Dianne Hackborn14272302014-06-10 23:13:02 -07002962 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002963 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured);
John Spurlock1bb480a2014-08-02 17:12:43 -04002964 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing);
Jeff Brown27736f52014-05-20 17:17:10 -07002965 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
2966 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
2967 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002968 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07002969 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002970 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
2971 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2972 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2973 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2974 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
Jeff Brown330560f2012-08-21 22:10:57 -07002975 pw.println(" mScreenAutoBrightnessAdjustmentSetting="
2976 + mScreenAutoBrightnessAdjustmentSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002977 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2978 pw.println(" mScreenBrightnessOverrideFromWindowManager="
2979 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002980 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
2981 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002982 pw.println(" mUserInactiveOverrideFromWindowManager="
2983 + mUserInactiveOverrideFromWindowManager);
Jeff Brown96307042012-07-27 15:51:34 -07002984 pw.println(" mTemporaryScreenBrightnessSettingOverride="
2985 + mTemporaryScreenBrightnessSettingOverride);
Jeff Brown330560f2012-08-21 22:10:57 -07002986 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2987 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
Jeff Brown970d4132014-07-19 11:33:47 -07002988 pw.println(" mDozeScreenStateOverrideFromDreamManager="
2989 + mDozeScreenStateOverrideFromDreamManager);
2990 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
2991 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07002992 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2993 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2994 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Santos Cordond6a56602016-09-20 15:50:35 -07002995 pw.println(" mScreenBrightnessForVrSettingDefault="
2996 + mScreenBrightnessForVrSettingDefault);
2997 pw.println(" mScreenBrightnessForVrSetting=" + mScreenBrightnessForVrSetting);
Jason Monk27bbb2d2015-03-31 16:46:39 -04002998 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordond6a56602016-09-20 15:50:35 -07002999 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003000
Jeff Brown05af6ad2014-09-30 20:54:30 -07003001 final int sleepTimeout = getSleepTimeoutLocked();
3002 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003003 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
3004 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003005 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003006 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3007 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3008
Jeff Brown96307042012-07-27 15:51:34 -07003009 pw.println();
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003010 pw.println("UID states:");
3011 for (int i=0; i<mUidState.size(); i++) {
3012 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
3013 pw.print(": "); pw.println(mUidState.valueAt(i));
3014 }
3015
3016 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003017 pw.println("Looper state:");
3018 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3019
3020 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003021 pw.println("Wake Locks: size=" + mWakeLocks.size());
3022 for (WakeLock wl : mWakeLocks) {
3023 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003024 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003025
Jeff Brown96307042012-07-27 15:51:34 -07003026 pw.println();
3027 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3028 for (SuspendBlocker sb : mSuspendBlockers) {
3029 pw.println(" " + sb);
3030 }
3031
Jeff Brownc38c9be2012-10-04 13:16:19 -07003032 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003033 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003034
Jeff Brown3b971592013-01-09 18:46:37 -08003035 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003036 }
3037
Jeff Brown3b971592013-01-09 18:46:37 -08003038 if (wcd != null) {
3039 wcd.dump(pw);
3040 }
Jeff Brown96307042012-07-27 15:51:34 -07003041 }
3042
3043 private SuspendBlocker createSuspendBlockerLocked(String name) {
3044 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
3045 mSuspendBlockers.add(suspendBlocker);
3046 return suspendBlocker;
3047 }
3048
Daichi Hirono82ab9802016-03-02 13:23:29 +09003049 private void incrementBootCount() {
3050 synchronized (mLock) {
3051 int count;
3052 try {
3053 count = Settings.Global.getInt(
3054 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3055 } catch (SettingNotFoundException e) {
3056 count = 0;
3057 }
3058 Settings.Global.putInt(
3059 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3060 }
3061 }
3062
Jeff Brown96307042012-07-27 15:51:34 -07003063 private static WorkSource copyWorkSource(WorkSource workSource) {
3064 return workSource != null ? new WorkSource(workSource) : null;
3065 }
3066
3067 private final class BatteryReceiver extends BroadcastReceiver {
3068 @Override
3069 public void onReceive(Context context, Intent intent) {
3070 synchronized (mLock) {
3071 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003072 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003073 }
3074 }
3075
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003076 private final class DreamReceiver extends BroadcastReceiver {
3077 @Override
3078 public void onReceive(Context context, Intent intent) {
3079 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003080 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003081 }
3082 }
3083 }
3084
Jeff Brownd4935962012-09-25 13:27:20 -07003085 private final class UserSwitchedReceiver extends BroadcastReceiver {
3086 @Override
3087 public void onReceive(Context context, Intent intent) {
3088 synchronized (mLock) {
3089 handleSettingsChangedLocked();
3090 }
3091 }
3092 }
3093
Jeff Brownec6aa592012-10-17 20:30:25 -07003094 private final class DockReceiver extends BroadcastReceiver {
3095 @Override
3096 public void onReceive(Context context, Intent intent) {
3097 synchronized (mLock) {
3098 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3099 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3100 if (mDockState != dockState) {
3101 mDockState = dockState;
3102 mDirty |= DIRTY_DOCK_STATE;
3103 updatePowerStateLocked();
3104 }
3105 }
3106 }
3107 }
3108
Jeff Brown96307042012-07-27 15:51:34 -07003109 private final class SettingsObserver extends ContentObserver {
3110 public SettingsObserver(Handler handler) {
3111 super(handler);
3112 }
3113
3114 @Override
3115 public void onChange(boolean selfChange, Uri uri) {
3116 synchronized (mLock) {
3117 handleSettingsChangedLocked();
3118 }
3119 }
3120 }
3121
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003122 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003123 @Override
3124 public void onVrStateChanged(boolean enabled) {
3125 powerHintInternal(POWER_HINT_VR_MODE, enabled ? 1 : 0);
Santos Cordond6a56602016-09-20 15:50:35 -07003126
3127 synchronized (mLock) {
3128 if (mIsVrModeEnabled != enabled) {
3129 mIsVrModeEnabled = enabled;
3130 mDirty |= DIRTY_VR_MODE_CHANGED;
3131 updatePowerStateLocked();
3132 }
3133 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003134 }
3135 };
3136
Jeff Brown96307042012-07-27 15:51:34 -07003137 /**
3138 * Handler for asynchronous operations performed by the power manager.
3139 */
3140 private final class PowerManagerHandler extends Handler {
3141 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003142 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003143 }
3144
3145 @Override
3146 public void handleMessage(Message msg) {
3147 switch (msg.what) {
3148 case MSG_USER_ACTIVITY_TIMEOUT:
3149 handleUserActivityTimeout();
3150 break;
3151 case MSG_SANDMAN:
3152 handleSandman();
3153 break;
Jeff Browne333e672014-10-28 13:48:55 -07003154 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3155 handleScreenBrightnessBoostTimeout();
3156 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003157 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3158 checkForLongWakeLocks();
3159 break;
Jeff Brown96307042012-07-27 15:51:34 -07003160 }
3161 }
3162 }
3163
3164 /**
3165 * Represents a wake lock that has been acquired by an application.
3166 */
3167 private final class WakeLock implements IBinder.DeathRecipient {
3168 public final IBinder mLock;
3169 public int mFlags;
3170 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003171 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07003172 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003173 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003174 public final int mOwnerUid;
3175 public final int mOwnerPid;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003176 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07003177 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003178 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003179 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07003180
Dianne Hackborn713df152013-05-17 11:27:57 -07003181 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003182 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Jeff Brown96307042012-07-27 15:51:34 -07003183 mLock = lock;
3184 mFlags = flags;
3185 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003186 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07003187 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003188 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003189 mOwnerUid = ownerUid;
3190 mOwnerPid = ownerPid;
3191 }
3192
3193 @Override
3194 public void binderDied() {
3195 PowerManagerService.this.handleWakeLockDeath(this);
3196 }
3197
3198 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
3199 int ownerUid, int ownerPid) {
3200 return mFlags == flags
3201 && mTag.equals(tag)
3202 && hasSameWorkSource(workSource)
3203 && mOwnerUid == ownerUid
3204 && mOwnerPid == ownerPid;
3205 }
3206
Dianne Hackborn713df152013-05-17 11:27:57 -07003207 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003208 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07003209 if (!mPackageName.equals(packageName)) {
3210 throw new IllegalStateException("Existing wake lock package name changed: "
3211 + mPackageName + " to " + packageName);
3212 }
3213 if (mOwnerUid != ownerUid) {
3214 throw new IllegalStateException("Existing wake lock uid changed: "
3215 + mOwnerUid + " to " + ownerUid);
3216 }
3217 if (mOwnerPid != ownerPid) {
3218 throw new IllegalStateException("Existing wake lock pid changed: "
3219 + mOwnerPid + " to " + ownerPid);
3220 }
Jeff Brown96307042012-07-27 15:51:34 -07003221 mFlags = flags;
3222 mTag = tag;
3223 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003224 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003225 }
3226
3227 public boolean hasSameWorkSource(WorkSource workSource) {
3228 return Objects.equal(mWorkSource, workSource);
3229 }
3230
3231 public void updateWorkSource(WorkSource workSource) {
3232 mWorkSource = copyWorkSource(workSource);
3233 }
3234
3235 @Override
3236 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003237 StringBuilder sb = new StringBuilder();
3238 sb.append(getLockLevelString());
3239 sb.append(" '");
3240 sb.append(mTag);
3241 sb.append("'");
3242 sb.append(getLockFlagsString());
3243 if (mDisabled) {
3244 sb.append(" DISABLED");
3245 }
3246 if (mNotifiedAcquired) {
3247 sb.append(" ACQ=");
3248 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
3249 }
3250 if (mNotifiedLong) {
3251 sb.append(" LONG");
3252 }
3253 sb.append(" (uid=");
3254 sb.append(mOwnerUid);
3255 if (mOwnerPid != 0) {
3256 sb.append(" pid=");
3257 sb.append(mOwnerPid);
3258 }
3259 if (mWorkSource != null) {
3260 sb.append(" ws=");
3261 sb.append(mWorkSource);
3262 }
3263 sb.append(")");
3264 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07003265 }
3266
Jeff Brown26875502014-01-30 21:47:47 -08003267 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07003268 private String getLockLevelString() {
3269 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
3270 case PowerManager.FULL_WAKE_LOCK:
3271 return "FULL_WAKE_LOCK ";
3272 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
3273 return "SCREEN_BRIGHT_WAKE_LOCK ";
3274 case PowerManager.SCREEN_DIM_WAKE_LOCK:
3275 return "SCREEN_DIM_WAKE_LOCK ";
3276 case PowerManager.PARTIAL_WAKE_LOCK:
3277 return "PARTIAL_WAKE_LOCK ";
3278 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
3279 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08003280 case PowerManager.DOZE_WAKE_LOCK:
3281 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08003282 case PowerManager.DRAW_WAKE_LOCK:
3283 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07003284 default:
3285 return "??? ";
3286 }
3287 }
3288
3289 private String getLockFlagsString() {
3290 String result = "";
3291 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
3292 result += " ACQUIRE_CAUSES_WAKEUP";
3293 }
3294 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
3295 result += " ON_AFTER_RELEASE";
3296 }
3297 return result;
3298 }
3299 }
3300
3301 private final class SuspendBlockerImpl implements SuspendBlocker {
3302 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07003303 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07003304 private int mReferenceCount;
3305
3306 public SuspendBlockerImpl(String name) {
3307 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07003308 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07003309 }
3310
3311 @Override
3312 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003313 try {
Jeff Brown96307042012-07-27 15:51:34 -07003314 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07003315 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07003316 + "\" was finalized without being released!");
3317 mReferenceCount = 0;
3318 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07003319 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003320 }
3321 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07003322 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003323 }
3324 }
3325
Craig Mautner75fc9de2012-06-18 16:53:27 -07003326 @Override
Jeff Brown96307042012-07-27 15:51:34 -07003327 public void acquire() {
3328 synchronized (this) {
3329 mReferenceCount += 1;
3330 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08003331 if (DEBUG_SPEW) {
3332 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
3333 }
Jeff Brown3edf5272014-08-14 19:25:14 -07003334 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07003335 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07003336 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003337 }
3338 }
3339
Craig Mautner75fc9de2012-06-18 16:53:27 -07003340 @Override
Jeff Brown96307042012-07-27 15:51:34 -07003341 public void release() {
3342 synchronized (this) {
3343 mReferenceCount -= 1;
3344 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08003345 if (DEBUG_SPEW) {
3346 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
3347 }
Jeff Brown96307042012-07-27 15:51:34 -07003348 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07003349 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07003350 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07003351 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07003352 + "\" was released without being acquired!", new Throwable());
3353 mReferenceCount = 0;
3354 }
3355 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003356 }
Jeff Brown96307042012-07-27 15:51:34 -07003357
3358 @Override
3359 public String toString() {
3360 synchronized (this) {
3361 return mName + ": ref count=" + mReferenceCount;
3362 }
3363 }
3364 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07003365
Jeff Brown6f357d32014-01-15 20:40:55 -08003366 private final class BinderService extends IPowerManager.Stub {
3367 @Override // Binder call
3368 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
3369 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07003370 if (uid < 0) {
3371 uid = Binder.getCallingUid();
3372 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003373 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08003374 }
3375
3376 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07003377 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07003378 if (!mSystemReady) {
3379 // Service not ready yet, so who the heck cares about power hints, bah.
3380 return;
3381 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07003382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003383 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07003384 }
3385
3386 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08003387 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003388 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003389 if (lock == null) {
3390 throw new IllegalArgumentException("lock must not be null");
3391 }
3392 if (packageName == null) {
3393 throw new IllegalArgumentException("packageName must not be null");
3394 }
3395 PowerManager.validateWakeLockParameters(flags, tag);
3396
3397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07003398 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
3399 mContext.enforceCallingOrSelfPermission(
3400 android.Manifest.permission.DEVICE_POWER, null);
3401 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003402 if (ws != null && ws.size() != 0) {
3403 mContext.enforceCallingOrSelfPermission(
3404 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
3405 } else {
3406 ws = null;
3407 }
3408
3409 final int uid = Binder.getCallingUid();
3410 final int pid = Binder.getCallingPid();
3411 final long ident = Binder.clearCallingIdentity();
3412 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003413 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
3417 }
3418
3419 @Override // Binder call
3420 public void releaseWakeLock(IBinder lock, int flags) {
3421 if (lock == null) {
3422 throw new IllegalArgumentException("lock must not be null");
3423 }
3424
3425 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
3426
3427 final long ident = Binder.clearCallingIdentity();
3428 try {
3429 releaseWakeLockInternal(lock, flags);
3430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
3433 }
3434
3435 @Override // Binder call
3436 public void updateWakeLockUids(IBinder lock, int[] uids) {
3437 WorkSource ws = null;
3438
3439 if (uids != null) {
3440 ws = new WorkSource();
3441 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
3442 // one at a time?
3443 for (int i = 0; i < uids.length; i++) {
3444 ws.add(uids[i]);
3445 }
3446 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07003447 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08003448 }
3449
3450 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07003451 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003452 if (lock == null) {
3453 throw new IllegalArgumentException("lock must not be null");
3454 }
3455
3456 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
3457 if (ws != null && ws.size() != 0) {
3458 mContext.enforceCallingOrSelfPermission(
3459 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
3460 } else {
3461 ws = null;
3462 }
3463
Dianne Hackbornd953c532014-08-16 18:17:38 -07003464 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003465 final long ident = Binder.clearCallingIdentity();
3466 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07003467 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003468 } finally {
3469 Binder.restoreCallingIdentity(ident);
3470 }
3471 }
3472
3473 @Override // Binder call
3474 public boolean isWakeLockLevelSupported(int level) {
3475 final long ident = Binder.clearCallingIdentity();
3476 try {
3477 return isWakeLockLevelSupportedInternal(level);
3478 } finally {
3479 Binder.restoreCallingIdentity(ident);
3480 }
3481 }
3482
3483 @Override // Binder call
3484 public void userActivity(long eventTime, int event, int flags) {
3485 final long now = SystemClock.uptimeMillis();
3486 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07003487 != PackageManager.PERMISSION_GRANTED
3488 && mContext.checkCallingOrSelfPermission(
3489 android.Manifest.permission.USER_ACTIVITY)
3490 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003491 // Once upon a time applications could call userActivity().
3492 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
3493 // request instead of throwing a SecurityException so we don't break old apps.
3494 synchronized (mLock) {
3495 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
3496 mLastWarningAboutUserActivityPermission = now;
3497 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07003498 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
3499 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08003500 + " pid=" + Binder.getCallingPid()
3501 + " uid=" + Binder.getCallingUid());
3502 }
3503 }
3504 return;
3505 }
3506
Jim Millerdca15d22015-06-16 20:55:13 -07003507 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003508 throw new IllegalArgumentException("event time must not be in the future");
3509 }
3510
3511 final int uid = Binder.getCallingUid();
3512 final long ident = Binder.clearCallingIdentity();
3513 try {
3514 userActivityInternal(eventTime, event, flags, uid);
3515 } finally {
3516 Binder.restoreCallingIdentity(ident);
3517 }
3518 }
3519
3520 @Override // Binder call
Dianne Hackborn280a64e2015-07-13 14:48:08 -07003521 public void wakeUp(long eventTime, String reason, String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003522 if (eventTime > SystemClock.uptimeMillis()) {
3523 throw new IllegalArgumentException("event time must not be in the future");
3524 }
3525
3526 mContext.enforceCallingOrSelfPermission(
3527 android.Manifest.permission.DEVICE_POWER, null);
3528
Jeff Brownc12035c2014-08-13 18:52:25 -07003529 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003530 final long ident = Binder.clearCallingIdentity();
3531 try {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07003532 wakeUpInternal(eventTime, reason, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003533 } finally {
3534 Binder.restoreCallingIdentity(ident);
3535 }
3536 }
3537
3538 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07003539 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003540 if (eventTime > SystemClock.uptimeMillis()) {
3541 throw new IllegalArgumentException("event time must not be in the future");
3542 }
3543
3544 mContext.enforceCallingOrSelfPermission(
3545 android.Manifest.permission.DEVICE_POWER, null);
3546
Jeff Brownc12035c2014-08-13 18:52:25 -07003547 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003548 final long ident = Binder.clearCallingIdentity();
3549 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07003550 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003551 } finally {
3552 Binder.restoreCallingIdentity(ident);
3553 }
3554 }
3555
3556 @Override // Binder call
3557 public void nap(long eventTime) {
3558 if (eventTime > SystemClock.uptimeMillis()) {
3559 throw new IllegalArgumentException("event time must not be in the future");
3560 }
3561
3562 mContext.enforceCallingOrSelfPermission(
3563 android.Manifest.permission.DEVICE_POWER, null);
3564
Jeff Brownc12035c2014-08-13 18:52:25 -07003565 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003566 final long ident = Binder.clearCallingIdentity();
3567 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07003568 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003569 } finally {
3570 Binder.restoreCallingIdentity(ident);
3571 }
3572 }
3573
3574 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07003575 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08003576 final long ident = Binder.clearCallingIdentity();
3577 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07003578 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08003579 } finally {
3580 Binder.restoreCallingIdentity(ident);
3581 }
3582 }
3583
Dianne Hackborneb94fa72014-06-03 17:48:12 -07003584 @Override // Binder call
3585 public boolean isPowerSaveMode() {
3586 final long ident = Binder.clearCallingIdentity();
3587 try {
3588 return isLowPowerModeInternal();
3589 } finally {
3590 Binder.restoreCallingIdentity(ident);
3591 }
3592 }
3593
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003594 @Override // Binder call
3595 public boolean setPowerSaveMode(boolean mode) {
3596 mContext.enforceCallingOrSelfPermission(
3597 android.Manifest.permission.DEVICE_POWER, null);
3598 final long ident = Binder.clearCallingIdentity();
3599 try {
3600 return setLowPowerModeInternal(mode);
3601 } finally {
3602 Binder.restoreCallingIdentity(ident);
3603 }
3604 }
3605
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003606 @Override // Binder call
3607 public boolean isDeviceIdleMode() {
3608 final long ident = Binder.clearCallingIdentity();
3609 try {
3610 return isDeviceIdleModeInternal();
3611 } finally {
3612 Binder.restoreCallingIdentity(ident);
3613 }
3614 }
3615
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003616 @Override // Binder call
3617 public boolean isLightDeviceIdleMode() {
3618 final long ident = Binder.clearCallingIdentity();
3619 try {
3620 return isLightDeviceIdleModeInternal();
3621 } finally {
3622 Binder.restoreCallingIdentity(ident);
3623 }
3624 }
3625
Jeff Brown6f357d32014-01-15 20:40:55 -08003626 /**
3627 * Reboots the device.
3628 *
3629 * @param confirm If true, shows a reboot confirmation dialog.
3630 * @param reason The reason for the reboot, or null if none.
3631 * @param wait If true, this call waits for the reboot to complete and does not return.
3632 */
3633 @Override // Binder call
3634 public void reboot(boolean confirm, String reason, boolean wait) {
3635 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08003636 if (PowerManager.REBOOT_RECOVERY.equals(reason)
3637 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08003638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
3639 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003640
3641 final long ident = Binder.clearCallingIdentity();
3642 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003643 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
3644 } finally {
3645 Binder.restoreCallingIdentity(ident);
3646 }
3647 }
3648
3649 /**
3650 * Reboots the device into safe mode
3651 *
3652 * @param confirm If true, shows a reboot confirmation dialog.
3653 * @param wait If true, this call waits for the reboot to complete and does not return.
3654 */
3655 @Override // Binder call
3656 public void rebootSafeMode(boolean confirm, boolean wait) {
3657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3658
3659 final long ident = Binder.clearCallingIdentity();
3660 try {
3661 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
3662 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08003663 } finally {
3664 Binder.restoreCallingIdentity(ident);
3665 }
3666 }
3667
3668 /**
3669 * Shuts down the device.
3670 *
3671 * @param confirm If true, shows a shutdown confirmation dialog.
3672 * @param wait If true, this call waits for the shutdown to complete and does not return.
3673 */
3674 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07003675 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003676 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3677
3678 final long ident = Binder.clearCallingIdentity();
3679 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003680 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08003681 } finally {
3682 Binder.restoreCallingIdentity(ident);
3683 }
3684 }
3685
3686 /**
3687 * Crash the runtime (causing a complete restart of the Android framework).
3688 * Requires REBOOT permission. Mostly for testing. Should not return.
3689 */
3690 @Override // Binder call
3691 public void crash(String message) {
3692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3693
3694 final long ident = Binder.clearCallingIdentity();
3695 try {
3696 crashInternal(message);
3697 } finally {
3698 Binder.restoreCallingIdentity(ident);
3699 }
3700 }
3701
3702 /**
3703 * Set the setting that determines whether the device stays on when plugged in.
3704 * The argument is a bit string, with each bit specifying a power source that,
3705 * when the device is connected to that source, causes the device to stay on.
3706 * See {@link android.os.BatteryManager} for the list of power sources that
3707 * can be specified. Current values include
3708 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
3709 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
3710 *
3711 * Used by "adb shell svc power stayon ..."
3712 *
3713 * @param val an {@code int} containing the bits that specify which power sources
3714 * should cause the device to stay on.
3715 */
3716 @Override // Binder call
3717 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01003718 int uid = Binder.getCallingUid();
3719 // if uid is of root's, we permit this operation straight away
3720 if (uid != Process.ROOT_UID) {
3721 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
3722 Settings.getPackageNameForUid(mContext, uid), true)) {
3723 return;
3724 }
3725 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003726
3727 final long ident = Binder.clearCallingIdentity();
3728 try {
3729 setStayOnSettingInternal(val);
3730 } finally {
3731 Binder.restoreCallingIdentity(ident);
3732 }
3733 }
3734
3735 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08003736 * Used by the settings application and brightness control widgets to
3737 * temporarily override the current screen brightness setting so that the
3738 * user can observe the effect of an intended settings change without applying
3739 * it immediately.
3740 *
3741 * The override will be canceled when the setting value is next updated.
3742 *
3743 * @param brightness The overridden brightness.
3744 *
3745 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
3746 */
3747 @Override // Binder call
3748 public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
3749 mContext.enforceCallingOrSelfPermission(
3750 android.Manifest.permission.DEVICE_POWER, null);
3751
3752 final long ident = Binder.clearCallingIdentity();
3753 try {
3754 setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
3755 } finally {
3756 Binder.restoreCallingIdentity(ident);
3757 }
3758 }
3759
3760 /**
3761 * Used by the settings application and brightness control widgets to
3762 * temporarily override the current screen auto-brightness adjustment setting so that the
3763 * user can observe the effect of an intended settings change without applying
3764 * it immediately.
3765 *
3766 * The override will be canceled when the setting value is next updated.
3767 *
3768 * @param adj The overridden brightness, or Float.NaN to disable the override.
3769 *
Jeff Brown131206b2014-04-08 17:27:14 -07003770 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
Jeff Brown6f357d32014-01-15 20:40:55 -08003771 */
3772 @Override // Binder call
3773 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
3774 mContext.enforceCallingOrSelfPermission(
3775 android.Manifest.permission.DEVICE_POWER, null);
3776
3777 final long ident = Binder.clearCallingIdentity();
3778 try {
3779 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
3780 } finally {
3781 Binder.restoreCallingIdentity(ident);
3782 }
3783 }
3784
3785 /**
3786 * Used by the phone application to make the attention LED flash when ringing.
3787 */
3788 @Override // Binder call
3789 public void setAttentionLight(boolean on, int color) {
3790 mContext.enforceCallingOrSelfPermission(
3791 android.Manifest.permission.DEVICE_POWER, null);
3792
3793 final long ident = Binder.clearCallingIdentity();
3794 try {
3795 setAttentionLightInternal(on, color);
3796 } finally {
3797 Binder.restoreCallingIdentity(ident);
3798 }
3799 }
3800
3801 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07003802 public void boostScreenBrightness(long eventTime) {
3803 if (eventTime > SystemClock.uptimeMillis()) {
3804 throw new IllegalArgumentException("event time must not be in the future");
3805 }
3806
3807 mContext.enforceCallingOrSelfPermission(
3808 android.Manifest.permission.DEVICE_POWER, null);
3809
3810 final int uid = Binder.getCallingUid();
3811 final long ident = Binder.clearCallingIdentity();
3812 try {
3813 boostScreenBrightnessInternal(eventTime, uid);
3814 } finally {
3815 Binder.restoreCallingIdentity(ident);
3816 }
3817 }
3818
3819 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003820 public boolean isScreenBrightnessBoosted() {
3821 final long ident = Binder.clearCallingIdentity();
3822 try {
3823 return isScreenBrightnessBoostedInternal();
3824 } finally {
3825 Binder.restoreCallingIdentity(ident);
3826 }
3827 }
3828
3829 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08003830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3831 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
3832 != PackageManager.PERMISSION_GRANTED) {
3833 pw.println("Permission Denial: can't dump PowerManager from from pid="
3834 + Binder.getCallingPid()
3835 + ", uid=" + Binder.getCallingUid());
3836 return;
3837 }
3838
3839 final long ident = Binder.clearCallingIdentity();
3840 try {
3841 dumpInternal(pw);
3842 } finally {
3843 Binder.restoreCallingIdentity(ident);
3844 }
3845 }
3846 }
3847
Jeff Brown4ccb8232014-01-16 22:16:42 -08003848 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08003849 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003850 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
3851 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3852 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3853 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08003854 }
Jeff Brown970d4132014-07-19 11:33:47 -07003855 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08003856 }
3857
Jeff Brown6f357d32014-01-15 20:40:55 -08003858 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003859 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003860 // Do nothing.
3861 // Button lights are not currently supported in the new implementation.
Jeff Brown6f357d32014-01-15 20:40:55 -08003862 }
3863
Jeff Brown970d4132014-07-19 11:33:47 -07003864 @Override
3865 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
3866 switch (screenState) {
3867 case Display.STATE_UNKNOWN:
3868 case Display.STATE_OFF:
3869 case Display.STATE_DOZE:
3870 case Display.STATE_DOZE_SUSPEND:
3871 case Display.STATE_ON:
Santos Cordond6a56602016-09-20 15:50:35 -07003872 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07003873 break;
3874 default:
3875 screenState = Display.STATE_UNKNOWN;
3876 break;
3877 }
3878 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3879 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3880 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
3881 }
3882 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
3883 }
3884
Jeff Brown6f357d32014-01-15 20:40:55 -08003885 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003886 public void setUserInactiveOverrideFromWindowManager() {
3887 setUserInactiveOverrideFromWindowManagerInternal();
3888 }
3889
3890 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08003891 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07003892 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08003893 }
3894
3895 @Override
Jeff Brown5ce1cb22014-11-06 19:05:33 -08003896 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
3897 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
3898 }
3899
3900 @Override
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003901 public boolean getLowPowerModeEnabled() {
3902 synchronized (mLock) {
3903 return mLowPowerModeEnabled;
3904 }
3905 }
3906
3907 @Override
3908 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
3909 synchronized (mLock) {
3910 mLowPowerModeListeners.add(listener);
3911 }
3912 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003913
3914 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003915 public boolean setDeviceIdleMode(boolean enabled) {
3916 return setDeviceIdleModeInternal(enabled);
3917 }
3918
3919 @Override
3920 public boolean setLightDeviceIdleMode(boolean enabled) {
3921 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003922 }
3923
3924 @Override
3925 public void setDeviceIdleWhitelist(int[] appids) {
3926 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003927 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003928
3929 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003930 public void setDeviceIdleTempWhitelist(int[] appids) {
3931 setDeviceIdleTempWhitelistInternal(appids);
3932 }
3933
3934 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003935 public void updateUidProcState(int uid, int procState) {
3936 updateUidProcStateInternal(uid, procState);
3937 }
3938
3939 @Override
3940 public void uidGone(int uid) {
3941 uidGoneInternal(uid);
3942 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01003943
3944 @Override
3945 public void powerHint(int hintId, int data) {
3946 powerHintInternal(hintId, data);
3947 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949}