blob: 8682f5cfe5361b881f50263cdab1b8d79ca0ac7e [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
Dianne Hackborn713df152013-05-17 11:27:57 -070019import com.android.internal.app.IAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.IBatteryStats;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -070021import com.android.internal.os.BackgroundThread;
Jeff Brown4f8ecd82012-06-18 18:29:13 -070022import com.android.server.EventLogTags;
Jeff Brown6f357d32014-01-15 20:40:55 -080023import com.android.server.ServiceThread;
Jeff Brown2175e9c2014-09-12 16:11:07 -070024import com.android.server.SystemService;
Jeff Brown2c43c332014-06-12 22:38:59 -070025import com.android.server.am.BatteryStatsService;
Adam Lesinski182f73f2013-12-05 16:48:06 -080026import com.android.server.lights.Light;
27import com.android.server.lights.LightsManager;
Jeff Brown4f8ecd82012-06-18 18:29:13 -070028import com.android.server.Watchdog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Jeff Brown96307042012-07-27 15:51:34 -070030import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070037import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080038import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080039import android.hardware.SensorManager;
40import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080041import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070042import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Jeff Brown96307042012-07-27 15:51:34 -070043import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070044import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070045import android.os.BatteryManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Binder;
47import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.IBinder;
49import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070050import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080051import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.PowerManager;
Jeff Brown6f357d32014-01-15 20:40:55 -080053import android.os.PowerManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Process;
55import android.os.RemoteException;
56import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070057import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070058import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070059import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070060import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.provider.Settings;
Jeff Brown567f7ca2014-01-30 23:38:03 -080062import android.service.dreams.DreamManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.EventLog;
64import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080065import android.util.Slog;
Jeff Brown96307042012-07-27 15:51:34 -070066import android.util.TimeUtils;
Jeff Brown037c33e2014-04-09 00:31:55 -070067import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.view.WindowManagerPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70import java.io.FileDescriptor;
71import java.io.PrintWriter;
72import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
Jeff Brown96307042012-07-27 15:51:34 -070074import libcore.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
Jeff Brown96307042012-07-27 15:51:34 -070076/**
77 * The power manager service is responsible for coordinating power management
78 * functions on the device.
79 */
Jeff Brown2175e9c2014-09-12 16:11:07 -070080public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -070081 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Jeff Brown88c997a2012-06-22 13:57:45 -070084 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -070085 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -070086
Jeff Brown96307042012-07-27 15:51:34 -070087 // Message: Sent when a user activity timeout occurs to update the power state.
88 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -080089 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -070090 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -070091 // Message: Sent when the screen brightness boost expires.
92 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Jeff Brown7304c342012-05-11 18:42:42 -070093
Jeff Brown96307042012-07-27 15:51:34 -070094 // Dirty bit: mWakeLocks changed
95 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
96 // Dirty bit: mWakefulness changed
97 private static final int DIRTY_WAKEFULNESS = 1 << 1;
98 // Dirty bit: user activity was poked or may have timed out
99 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
100 // Dirty bit: actual display power state was updated asynchronously
101 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
102 // Dirty bit: mBootCompleted changed
103 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
104 // Dirty bit: settings changed
105 private static final int DIRTY_SETTINGS = 1 << 5;
106 // Dirty bit: mIsPowered changed
107 private static final int DIRTY_IS_POWERED = 1 << 6;
108 // Dirty bit: mStayOn changed
109 private static final int DIRTY_STAY_ON = 1 << 7;
110 // Dirty bit: battery state changed
111 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700112 // Dirty bit: proximity state changed
113 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700114 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700115 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700116 // Dirty bit: brightness boost changed
117 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Jeff Brown7304c342012-05-11 18:42:42 -0700118
Jeff Brown96307042012-07-27 15:51:34 -0700119 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp().
120 // The screen should be off or in the process of being turned off by the display controller.
Jeff Brown26875502014-01-30 21:47:47 -0800121 // The device typically passes through the dozing state first.
Jeff Brown96307042012-07-27 15:51:34 -0700122 private static final int WAKEFULNESS_ASLEEP = 0;
123 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep().
Jeff Brown26875502014-01-30 21:47:47 -0800124 // When the user activity timeout expires, the device may start dreaming or go to sleep.
Jeff Brown96307042012-07-27 15:51:34 -0700125 private static final int WAKEFULNESS_AWAKE = 1;
Jeff Brown96307042012-07-27 15:51:34 -0700126 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(),
127 // which ends the dream. The device goes to sleep when goToSleep() is called, when
128 // the dream ends or when unplugged.
129 // User activity may brighten the screen but does not end the dream.
Jeff Brown26875502014-01-30 21:47:47 -0800130 private static final int WAKEFULNESS_DREAMING = 2;
131 // Wakefulness: The device is dozing. It is almost asleep but is allowing a special
132 // low-power "doze" dream to run which keeps the display on but lets the application
133 // processor be suspended. It can be awoken by a call to wakeUp() which ends the dream.
134 // The device fully goes to sleep if the dream cannot be started or ends on its own.
135 private static final int WAKEFULNESS_DOZING = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Jeff Brown96307042012-07-27 15:51:34 -0700137 // Summarizes the state of all active wakelocks.
138 private static final int WAKE_LOCK_CPU = 1 << 0;
139 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
140 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
141 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
142 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700143 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800144 private static final int WAKE_LOCK_DOZE = 1 << 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Jeff Brown96307042012-07-27 15:51:34 -0700146 // Summarizes the user activity state.
147 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
148 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700149 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Jeff Brown27736f52014-05-20 17:17:10 -0700151 // Default timeout in milliseconds. This is only used until the settings
152 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700153 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700154 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700155
Jeff Browne333e672014-10-28 13:48:55 -0700156 // Screen brightness boost timeout.
157 // Hardcoded for now until we decide what the right policy should be.
158 // This should perhaps be a setting.
159 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
160
Jeff Brown0a571122014-08-21 21:50:43 -0700161 // Power hints defined in hardware/libhardware/include/hardware/power.h.
162 private static final int POWER_HINT_INTERACTION = 2;
163 private static final int POWER_HINT_LOW_POWER = 5;
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700164
Jeff Brownb880d882014-02-10 19:47:07 -0800165 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700166 private final ServiceThread mHandlerThread;
167 private final PowerManagerHandler mHandler;
168
Adam Lesinski182f73f2013-12-05 16:48:06 -0800169 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700170 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800171 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700172 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700173 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700174 private WindowManagerPolicy mPolicy;
175 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800176 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700177 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800178 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800179 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700180
Jeff Brown96307042012-07-27 15:51:34 -0700181 private final Object mLock = new Object();
182
183 // A bitfield that indicates what parts of the power state have
184 // changed and need to be recalculated.
185 private int mDirty;
186
187 // Indicates whether the device is awake or asleep or somewhere in between.
188 // This is distinct from the screen power state, which is managed separately.
189 private int mWakefulness;
190
Jeff Brown26875502014-01-30 21:47:47 -0800191 // True if the sandman has just been summoned for the first time since entering the
192 // dreaming or dozing state. Indicates whether a new dream should begin.
193 private boolean mSandmanSummoned;
194
Jeff Brown96307042012-07-27 15:51:34 -0700195 // True if MSG_SANDMAN has been scheduled.
196 private boolean mSandmanScheduled;
197
198 // Table of all suspend blockers.
199 // There should only be a few of these.
200 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
201
202 // Table of all wake locks acquired by applications.
203 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
204
205 // A bitfield that summarizes the state of all active wakelocks.
206 private int mWakeLockSummary;
207
Jeff Brown037c33e2014-04-09 00:31:55 -0700208 // True if the device is in an interactive state.
209 private boolean mInteractive;
210 private boolean mInteractiveChanging;
211
Jeff Brown96307042012-07-27 15:51:34 -0700212 // If true, instructs the display controller to wait for the proximity sensor to
213 // go negative before turning the screen on.
214 private boolean mRequestWaitForNegativeProximity;
215
216 // Timestamp of the last time the device was awoken or put to sleep.
217 private long mLastWakeTime;
218 private long mLastSleepTime;
219
Jeff Brown96307042012-07-27 15:51:34 -0700220 // Timestamp of the last call to user activity.
221 private long mLastUserActivityTime;
222 private long mLastUserActivityTimeNoChangeLights;
223
Jeff Brown0a571122014-08-21 21:50:43 -0700224 // Timestamp of last interactive power hint.
225 private long mLastInteractivePowerHintTime;
226
Jeff Browne333e672014-10-28 13:48:55 -0700227 // Timestamp of the last screen brightness boost.
228 private long mLastScreenBrightnessBoostTime;
229 private boolean mScreenBrightnessBoostInProgress;
230
Jeff Brown96307042012-07-27 15:51:34 -0700231 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700232 private int mUserActivitySummary;
233
234 // The desired display power state. The actual state may lag behind the
235 // requested because it is updated asynchronously by the display power controller.
236 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
237
Jeff Brown96307042012-07-27 15:51:34 -0700238 // True if the display power state has been fully applied, which means the display
239 // is actually on or actually off or whatever was requested.
240 private boolean mDisplayReady;
241
Jeff Brown27f7a862012-12-12 15:43:31 -0800242 // The suspend blocker used to keep the CPU alive when an application has acquired
243 // a wake lock.
244 private final SuspendBlocker mWakeLockSuspendBlocker;
245
246 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700247 private boolean mHoldingWakeLockSuspendBlocker;
248
Jeff Brown27f7a862012-12-12 15:43:31 -0800249 // The suspend blocker used to keep the CPU alive when the display is on, the
250 // display is getting ready or there is user activity (in which case the display
251 // must be on).
252 private final SuspendBlocker mDisplaySuspendBlocker;
253
254 // True if the display suspend blocker has been acquired.
255 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700256
257 // True if systemReady() has been called.
258 private boolean mSystemReady;
259
260 // True if boot completed occurred. We keep the screen on until this happens.
261 private boolean mBootCompleted;
262
Jeff Brown26875502014-01-30 21:47:47 -0800263 // True if auto-suspend mode is enabled.
264 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700265 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800266
267 // True if interactive mode is enabled.
268 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700269 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800270
Jeff Brown96307042012-07-27 15:51:34 -0700271 // True if the device is plugged into a power source.
272 private boolean mIsPowered;
273
Jeff Brownf3fb8952012-10-02 20:57:05 -0700274 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
275 private int mPlugType;
276
Jeff Brown016ff142012-10-15 16:47:22 -0700277 // The current battery level percentage.
278 private int mBatteryLevel;
279
280 // The battery level percentage at the time the dream started.
281 // This is used to terminate a dream and go to sleep if the battery is
282 // draining faster than it is charging and the user activity timeout has expired.
283 private int mBatteryLevelWhenDreamStarted;
284
Jeff Brownec6aa592012-10-17 20:30:25 -0700285 // The current dock state.
286 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
287
Jeff Brown26875502014-01-30 21:47:47 -0800288 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700289 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800290
291 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700292 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800293
Jeff Brown96307042012-07-27 15:51:34 -0700294 // True if the device should wake up when plugged or unplugged.
295 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
296
Bryce Lee584a4452014-10-21 15:55:55 -0700297 // True if the device should wake up when plugged or unplugged in theater mode.
298 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
299
Jeff Brownec083212013-09-11 20:45:25 -0700300 // True if the device should suspend when the screen is off due to proximity.
301 private boolean mSuspendWhenScreenOffDueToProximityConfig;
302
Jeff Brown96307042012-07-27 15:51:34 -0700303 // True if dreams are supported on this device.
304 private boolean mDreamsSupportedConfig;
305
John Spurlocked108f32012-10-18 16:49:24 -0400306 // Default value for dreams enabled
307 private boolean mDreamsEnabledByDefaultConfig;
308
309 // Default value for dreams activate-on-sleep
310 private boolean mDreamsActivatedOnSleepByDefaultConfig;
311
312 // Default value for dreams activate-on-dock
313 private boolean mDreamsActivatedOnDockByDefaultConfig;
314
Jeff Brown26875502014-01-30 21:47:47 -0800315 // True if dreams can run while not plugged in.
316 private boolean mDreamsEnabledOnBatteryConfig;
317
318 // Minimum battery level to allow dreaming when powered.
319 // Use -1 to disable this safety feature.
320 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
321
322 // Minimum battery level to allow dreaming when not powered.
323 // Use -1 to disable this safety feature.
324 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
325
326 // If the battery level drops by this percentage and the user activity timeout
327 // has expired, then assume the device is receiving insufficient current to charge
328 // effectively and terminate the dream. Use -1 to disable this safety feature.
329 private int mDreamsBatteryLevelDrainCutoffConfig;
330
Jeff Brown96307042012-07-27 15:51:34 -0700331 // True if dreams are enabled by the user.
332 private boolean mDreamsEnabledSetting;
333
John Spurlock1a868b72012-08-22 09:56:51 -0400334 // True if dreams should be activated on sleep.
335 private boolean mDreamsActivateOnSleepSetting;
336
Jeff Brownec6aa592012-10-17 20:30:25 -0700337 // True if dreams should be activated on dock.
338 private boolean mDreamsActivateOnDockSetting;
339
Jeff Brown2175e9c2014-09-12 16:11:07 -0700340 // True if doze should not be started until after the screen off transition.
341 private boolean mDozeAfterScreenOffConfig;
342
Jeff Brown27736f52014-05-20 17:17:10 -0700343 // The minimum screen off timeout, in milliseconds.
344 private int mMinimumScreenOffTimeoutConfig;
345
346 // The screen dim duration, in milliseconds.
347 // This is subtracted from the end of the screen off timeout so the
348 // minimum screen off timeout should be longer than this.
349 private int mMaximumScreenDimDurationConfig;
350
351 // The maximum screen dim time expressed as a ratio relative to the screen
352 // off timeout. If the screen off timeout is very short then we want the
353 // dim timeout to also be quite short so that most of the time is spent on.
354 // Otherwise the user won't get much screen on time before dimming occurs.
355 private float mMaximumScreenDimRatioConfig;
356
Jeff Brown96307042012-07-27 15:51:34 -0700357 // The screen off timeout setting value in milliseconds.
358 private int mScreenOffTimeoutSetting;
359
Jeff Brown05af6ad2014-09-30 20:54:30 -0700360 // The sleep timeout setting value in milliseconds.
361 private int mSleepTimeoutSetting;
362
Jeff Brown96307042012-07-27 15:51:34 -0700363 // The maximum allowable screen off timeout according to the device
364 // administration policy. Overrides other settings.
365 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
366
367 // The stay on while plugged in setting.
368 // A bitfield of battery conditions under which to make the screen stay on.
369 private int mStayOnWhilePluggedInSetting;
370
371 // True if the device should stay on.
372 private boolean mStayOn;
373
Jeff Brown93cbbb22012-10-04 13:18:36 -0700374 // True if the proximity sensor reads a positive result.
375 private boolean mProximityPositive;
376
Jeff Brown96307042012-07-27 15:51:34 -0700377 // Screen brightness setting limits.
378 private int mScreenBrightnessSettingMinimum;
379 private int mScreenBrightnessSettingMaximum;
380 private int mScreenBrightnessSettingDefault;
381
382 // The screen brightness setting, from 0 to 255.
383 // Use -1 if no value has been set.
384 private int mScreenBrightnessSetting;
385
Jeff Brown330560f2012-08-21 22:10:57 -0700386 // The screen auto-brightness adjustment setting, from -1 to 1.
387 // Use 0 if there is no adjustment.
388 private float mScreenAutoBrightnessAdjustmentSetting;
389
Jeff Brown96307042012-07-27 15:51:34 -0700390 // The screen brightness mode.
391 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
392 private int mScreenBrightnessModeSetting;
393
394 // The screen brightness setting override from the window manager
395 // to allow the current foreground activity to override the brightness.
396 // Use -1 to disable.
397 private int mScreenBrightnessOverrideFromWindowManager = -1;
398
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700399 // The user activity timeout override from the window manager
400 // to allow the current foreground activity to override the user activity timeout.
401 // Use -1 to disable.
402 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
403
Jeff Brown96307042012-07-27 15:51:34 -0700404 // The screen brightness setting override from the settings application
405 // to temporarily adjust the brightness until next updated,
406 // Use -1 to disable.
407 private int mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408
Jeff Brown330560f2012-08-21 22:10:57 -0700409 // The screen brightness adjustment setting override from the settings
410 // application to temporarily adjust the auto-brightness adjustment factor
411 // until next updated, in the range -1..1.
412 // Use NaN to disable.
413 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
414
Jeff Brown970d4132014-07-19 11:33:47 -0700415 // The screen state to use while dozing.
416 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
417
418 // The screen brightness to use while dozing.
419 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
420
Jeff Brown9ba8d782012-10-01 16:38:23 -0700421 // Time when we last logged a warning about calling userActivity() without permission.
422 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
423
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700424 // If true, the device is in low power mode.
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700425 private boolean mLowPowerModeEnabled;
426
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700427 // Current state of the low power mode setting.
428 private boolean mLowPowerModeSetting;
429
Dianne Hackborn14272302014-06-10 23:13:02 -0700430 // Current state of whether the settings are allowing auto low power mode.
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400431 private boolean mAutoLowPowerModeConfigured;
Dianne Hackborn14272302014-06-10 23:13:02 -0700432
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400433 // The user turned off low power mode below the trigger level
John Spurlock1bb480a2014-08-02 17:12:43 -0400434 private boolean mAutoLowPowerModeSnoozing;
435
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700436 // True if the battery level is currently considered low.
437 private boolean mBatteryLevelLow;
438
Bryce Lee584a4452014-10-21 15:55:55 -0700439 // True if theater mode is enabled
440 private boolean mTheaterModeEnabled;
441
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700442 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners
443 = new ArrayList<PowerManagerInternal.LowPowerModeListener>();
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700444
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700445 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446
Jeff Brown96307042012-07-27 15:51:34 -0700447 private static native void nativeAcquireSuspendBlocker(String name);
448 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700449 private static native void nativeSetInteractive(boolean enable);
450 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700451 private static native void nativeSendPowerHint(int hintId, int data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452
Jeff Brownb880d882014-02-10 19:47:07 -0800453 public PowerManagerService(Context context) {
454 super(context);
455 mContext = context;
Jeff Brown2c43c332014-06-12 22:38:59 -0700456 mHandlerThread = new ServiceThread(TAG,
457 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
458 mHandlerThread.start();
459 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
460
Jeff Brown96307042012-07-27 15:51:34 -0700461 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800462 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
463 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
464 mDisplaySuspendBlocker.acquire();
465 mHoldingDisplaySuspendBlocker = true;
Jeff Brown037c33e2014-04-09 00:31:55 -0700466 mHalAutoSuspendModeEnabled = false;
467 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800468
Jeff Brown96307042012-07-27 15:51:34 -0700469 mWakefulness = WAKEFULNESS_AWAKE;
Jeff Brown037c33e2014-04-09 00:31:55 -0700470 mInteractive = true;
Jeff Brown7304c342012-05-11 18:42:42 -0700471
Jeff Brown037c33e2014-04-09 00:31:55 -0700472 nativeInit();
473 nativeSetAutoSuspend(false);
474 nativeSetInteractive(true);
475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 }
477
Jeff Brown6f357d32014-01-15 20:40:55 -0800478 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800479 public void onStart() {
480 publishBinderService(Context.POWER_SERVICE, new BinderService());
481 publishLocalService(PowerManagerInternal.class, new LocalService());
Jeff Brown9e316a12012-10-08 19:17:06 -0700482
483 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800484 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700485 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800486
Jeff Brown6d2a9492014-08-07 19:06:49 -0700487 @Override
488 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700489 synchronized (mLock) {
490 if (phase == PHASE_BOOT_COMPLETED) {
491 final long now = SystemClock.uptimeMillis();
492 mBootCompleted = true;
493 mDirty |= DIRTY_BOOT_COMPLETED;
494 userActivityNoUpdateLocked(
495 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
496 updatePowerStateLocked();
497 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700498 }
499 }
500
Jeff Brown21392762014-06-13 19:00:36 -0700501 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700502 synchronized (mLock) {
503 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700504 mAppOps = appOps;
505 mDreamManager = getLocalService(DreamManagerInternal.class);
506 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
507 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700508 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509
Adam Lesinski182f73f2013-12-05 16:48:06 -0800510 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700511 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
512 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
513 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700515 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800516
Jeff Brownc38c9be2012-10-04 13:16:19 -0700517 // The notifier runs on the system server's main looper so as not to interfere
518 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700519 mBatteryStats = BatteryStatsService.getService();
Jeff Brownc38c9be2012-10-04 13:16:19 -0700520 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700521 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brown3ee549c2014-09-22 20:14:39 -0700522 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700523
Jeff Brown3b971592013-01-09 18:46:37 -0800524 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700525 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
526 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700527 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700528
529 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800530 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400531
Jeff Brown131206b2014-04-08 17:27:14 -0700532 // Initialize display power management.
533 mDisplayManagerInternal.initPowerManagement(
534 mDisplayPowerCallbacks, mHandler, sensorManager);
535
Jeff Brown96307042012-07-27 15:51:34 -0700536 // Register for broadcasts from other components of the system.
537 IntentFilter filter = new IntentFilter();
538 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700539 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Jeff Brownd4935962012-09-25 13:27:20 -0700540 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700541
Jeff Brown96307042012-07-27 15:51:34 -0700542 filter = new IntentFilter();
Dianne Hackbornbe87e2f2012-09-28 16:31:34 -0700543 filter.addAction(Intent.ACTION_DREAMING_STARTED);
544 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
Jeff Brownd4935962012-09-25 13:27:20 -0700545 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
546
547 filter = new IntentFilter();
548 filter.addAction(Intent.ACTION_USER_SWITCHED);
549 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
John Spurlockf4f6b4c2012-08-25 12:08:03 -0400550
Jeff Brownec6aa592012-10-17 20:30:25 -0700551 filter = new IntentFilter();
552 filter.addAction(Intent.ACTION_DOCK_EVENT);
553 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
554
Jeff Brown96307042012-07-27 15:51:34 -0700555 // Register for settings changes.
556 final ContentResolver resolver = mContext.getContentResolver();
557 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700558 Settings.Secure.SCREENSAVER_ENABLED),
559 false, mSettingsObserver, UserHandle.USER_ALL);
John Spurlock1a868b72012-08-22 09:56:51 -0400560 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700561 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
562 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brownec6aa592012-10-17 20:30:25 -0700563 resolver.registerContentObserver(Settings.Secure.getUriFor(
564 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
565 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700566 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700567 Settings.System.SCREEN_OFF_TIMEOUT),
568 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700569 resolver.registerContentObserver(Settings.Secure.getUriFor(
570 Settings.Secure.SLEEP_TIMEOUT),
571 false, mSettingsObserver, UserHandle.USER_ALL);
Christopher Tatead735322012-09-07 14:19:43 -0700572 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700573 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
574 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700575 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700576 Settings.System.SCREEN_BRIGHTNESS),
577 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700578 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700579 Settings.System.SCREEN_BRIGHTNESS_MODE),
580 false, mSettingsObserver, UserHandle.USER_ALL);
Adrian Roos6dee6052014-05-14 19:44:18 +0200581 resolver.registerContentObserver(Settings.System.getUriFor(
582 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
583 false, mSettingsObserver, UserHandle.USER_ALL);
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700584 resolver.registerContentObserver(Settings.Global.getUriFor(
585 Settings.Global.LOW_POWER_MODE),
586 false, mSettingsObserver, UserHandle.USER_ALL);
Dianne Hackborn14272302014-06-10 23:13:02 -0700587 resolver.registerContentObserver(Settings.Global.getUriFor(
588 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
589 false, mSettingsObserver, UserHandle.USER_ALL);
Bryce Lee584a4452014-10-21 15:55:55 -0700590 resolver.registerContentObserver(Settings.Global.getUriFor(
591 Settings.Global.THEATER_MODE_ON),
592 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700593 // Go.
594 readConfigurationLocked();
595 updateSettingsLocked();
596 mDirty |= DIRTY_BATTERY_STATE;
597 updatePowerStateLocked();
598 }
599 }
600
601 private void readConfigurationLocked() {
602 final Resources resources = mContext.getResources();
603
Jeff Brown037c33e2014-04-09 00:31:55 -0700604 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800605 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700606 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800607 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700608 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700609 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700610 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
611 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700612 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
613 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700614 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400615 com.android.internal.R.bool.config_dreamsSupported);
616 mDreamsEnabledByDefaultConfig = resources.getBoolean(
617 com.android.internal.R.bool.config_dreamsEnabledByDefault);
618 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
619 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
620 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
621 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800622 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
623 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
624 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
625 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
626 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
627 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
628 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
629 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Jeff Brown2175e9c2014-09-12 16:11:07 -0700630 mDozeAfterScreenOffConfig = resources.getBoolean(
631 com.android.internal.R.bool.config_dozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -0700632 mMinimumScreenOffTimeoutConfig = resources.getInteger(
633 com.android.internal.R.integer.config_minimumScreenOffTimeout);
634 mMaximumScreenDimDurationConfig = resources.getInteger(
635 com.android.internal.R.integer.config_maximumScreenDimDuration);
636 mMaximumScreenDimRatioConfig = resources.getFraction(
637 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639
Jeff Brown96307042012-07-27 15:51:34 -0700640 private void updateSettingsLocked() {
641 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700642
Jeff Brownd4935962012-09-25 13:27:20 -0700643 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400644 Settings.Secure.SCREENSAVER_ENABLED,
645 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700646 UserHandle.USER_CURRENT) != 0);
647 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400648 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
649 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700650 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700651 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400652 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
653 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700654 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700655 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
656 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
657 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700658 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
659 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
660 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700661 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700662 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -0700663 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
664 Settings.Global.THEATER_MODE_ON, 0) == 1;
Jeff Brown7304c342012-05-11 18:42:42 -0700665
Jeff Brown96307042012-07-27 15:51:34 -0700666 final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700667 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
668 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
669 UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700670 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
671 mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
Jeff Brown96307042012-07-27 15:51:34 -0700673
Jeff Brown330560f2012-08-21 22:10:57 -0700674 final float oldScreenAutoBrightnessAdjustmentSetting =
675 mScreenAutoBrightnessAdjustmentSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700676 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
677 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
678 UserHandle.USER_CURRENT);
Jeff Brown330560f2012-08-21 22:10:57 -0700679 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
Jeff Brown5d03a532012-08-22 13:22:02 -0700680 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
Jeff Brown330560f2012-08-21 22:10:57 -0700681 }
682
Jeff Brownd4935962012-09-25 13:27:20 -0700683 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700684 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700685 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700686
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700687 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver,
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700688 Settings.Global.LOW_POWER_MODE, 0) != 0;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400689 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver,
John Spurlock1bb480a2014-08-02 17:12:43 -0400690 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0;
Dianne Hackborn14272302014-06-10 23:13:02 -0700691 if (lowPowerModeEnabled != mLowPowerModeSetting
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400692 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700693 mLowPowerModeSetting = lowPowerModeEnabled;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400694 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured;
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700695 updateLowPowerModeLocked();
696 }
697
698 mDirty |= DIRTY_SETTINGS;
699 }
700
701 void updateLowPowerModeLocked() {
John Spurlock1bb480a2014-08-02 17:12:43 -0400702 if (mIsPowered && mLowPowerModeSetting) {
703 if (DEBUG_SPEW) {
704 Slog.d(TAG, "updateLowPowerModeLocked: powered, turning setting off");
705 }
706 // Turn setting off if powered
707 Settings.Global.putInt(mContext.getContentResolver(),
708 Settings.Global.LOW_POWER_MODE, 0);
709 mLowPowerModeSetting = false;
John Spurlock1bb480a2014-08-02 17:12:43 -0400710 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400711 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured
712 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow;
713 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled;
714
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700715 if (mLowPowerModeEnabled != lowPowerModeEnabled) {
716 mLowPowerModeEnabled = lowPowerModeEnabled;
Jeff Brown0a571122014-08-21 21:50:43 -0700717 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700718 BackgroundThread.getHandler().post(new Runnable() {
719 @Override
720 public void run() {
John Spurlock1bb480a2014-08-02 17:12:43 -0400721 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)
722 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled)
723 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
724 mContext.sendBroadcast(intent);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700725 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners;
726 synchronized (mLock) {
727 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>(
728 mLowPowerModeListeners);
729 }
730 for (int i=0; i<listeners.size(); i++) {
731 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled);
732 }
John Spurlock1bb480a2014-08-02 17:12:43 -0400733 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700734 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
735 mContext.sendBroadcast(intent);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700736 }
737 });
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 }
740
Jeff Brown96307042012-07-27 15:51:34 -0700741 private void handleSettingsChangedLocked() {
742 updateSettingsLocked();
743 updatePowerStateLocked();
744 }
745
Dianne Hackborn713df152013-05-17 11:27:57 -0700746 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800747 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700748 synchronized (mLock) {
749 if (DEBUG_SPEW) {
750 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
751 + ", flags=0x" + Integer.toHexString(flags)
752 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754
Jeff Brown96307042012-07-27 15:51:34 -0700755 WakeLock wakeLock;
756 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700757 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -0700758 if (index >= 0) {
759 wakeLock = mWakeLocks.get(index);
760 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
761 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800762 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
763 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800764 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700766 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } else {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800768 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700769 try {
770 lock.linkToDeath(wakeLock, 0);
771 } catch (RemoteException ex) {
772 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
Jeff Brown96307042012-07-27 15:51:34 -0700774 mWakeLocks.add(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700775 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777
Jeff Brownc12035c2014-08-13 18:52:25 -0700778 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -0700779 mDirty |= DIRTY_WAKE_LOCKS;
780 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700781 if (notifyAcquire) {
782 // This needs to be done last so we are sure we have acquired the
783 // kernel wake lock. Otherwise we have a race where the system may
784 // go to sleep between the time we start the accounting in battery
785 // stats and when we actually get around to telling the kernel to
786 // stay awake.
787 notifyWakeLockAcquiredLocked(wakeLock);
788 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700789 }
790 }
791
Jeff Brownec083212013-09-11 20:45:25 -0700792 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -0800793 private static boolean isScreenLock(final WakeLock wakeLock) {
794 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
795 case PowerManager.FULL_WAKE_LOCK:
796 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
797 case PowerManager.SCREEN_DIM_WAKE_LOCK:
798 return true;
799 }
800 return false;
801 }
802
Jeff Brownc12035c2014-08-13 18:52:25 -0700803 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -0700804 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
805 && isScreenLock(wakeLock)) {
Jeff Brownc12035c2014-08-13 18:52:25 -0700806 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
808 }
809
Jeff Brown96307042012-07-27 15:51:34 -0700810 private void releaseWakeLockInternal(IBinder lock, int flags) {
811 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -0700812 int index = findWakeLockIndexLocked(lock);
813 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800814 if (DEBUG_SPEW) {
815 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
816 + " [not found], flags=0x" + Integer.toHexString(flags));
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 return;
819 }
Mike Lockwood3333fa42009-10-26 14:50:42 -0400820
Jeff Brown96307042012-07-27 15:51:34 -0700821 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800822 if (DEBUG_SPEW) {
823 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
824 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
825 }
826
Michael Wright1208e272014-09-08 19:57:50 -0700827 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -0700828 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830
Jeff Brown3edf5272014-08-14 19:25:14 -0700831 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
832 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700835
Jeff Brown96307042012-07-27 15:51:34 -0700836 private void handleWakeLockDeath(WakeLock wakeLock) {
837 synchronized (mLock) {
838 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800839 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
840 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -0700841 }
842
843 int index = mWakeLocks.indexOf(wakeLock);
844 if (index < 0) {
845 return;
846 }
847
Jeff Brown3edf5272014-08-14 19:25:14 -0700848 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700849 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800851
Jeff Brown3edf5272014-08-14 19:25:14 -0700852 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
853 mWakeLocks.remove(index);
854 notifyWakeLockReleasedLocked(wakeLock);
855
856 applyWakeLockFlagsOnReleaseLocked(wakeLock);
857 mDirty |= DIRTY_WAKE_LOCKS;
858 updatePowerStateLocked();
859 }
860
Jeff Brown96307042012-07-27 15:51:34 -0700861 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700862 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
863 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700864 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
865 PowerManager.USER_ACTIVITY_EVENT_OTHER,
866 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
867 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870
Dianne Hackbornd953c532014-08-16 18:17:38 -0700871 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
872 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -0700873 synchronized (mLock) {
874 int index = findWakeLockIndexLocked(lock);
875 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800876 if (DEBUG_SPEW) {
877 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
878 + " [not found], ws=" + ws);
879 }
Dianne Hackbornd953c532014-08-16 18:17:38 -0700880 throw new IllegalArgumentException("Wake lock not active: " + lock
881 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -0700882 }
883
884 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800885 if (DEBUG_SPEW) {
886 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
887 + " [" + wakeLock.mTag + "], ws=" + ws);
888 }
889
Jeff Brown96307042012-07-27 15:51:34 -0700890 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800891 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
892 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -0700893 ws, historyTag);
894 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -0700895 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -0700896 }
897 }
898 }
899
900 private int findWakeLockIndexLocked(IBinder lock) {
901 final int count = mWakeLocks.size();
902 for (int i = 0; i < count; i++) {
903 if (mWakeLocks.get(i).mLock == lock) {
904 return i;
905 }
906 }
907 return -1;
908 }
909
910 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
911 if (mSystemReady) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700912 wakeLock.mNotifiedAcquired = true;
913 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800914 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
915 wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -0700916 }
917 }
918
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800919 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
920 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
921 if (mSystemReady && wakeLock.mNotifiedAcquired) {
922 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
923 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
924 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
925 }
926 }
927
Jeff Brown96307042012-07-27 15:51:34 -0700928 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700929 if (mSystemReady && wakeLock.mNotifiedAcquired) {
930 wakeLock.mNotifiedAcquired = false;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700931 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
932 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
933 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -0700934 }
935 }
936
Jeff Brownec083212013-09-11 20:45:25 -0700937 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700938 private boolean isWakeLockLevelSupportedInternal(int level) {
939 synchronized (mLock) {
940 switch (level) {
941 case PowerManager.PARTIAL_WAKE_LOCK:
942 case PowerManager.SCREEN_DIM_WAKE_LOCK:
943 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
944 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -0800945 case PowerManager.DOZE_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700946 return true;
Jeff Brown96307042012-07-27 15:51:34 -0700947
948 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -0700949 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -0700950
951 default:
952 return false;
953 }
954 }
955 }
956
Jeff Brown96307042012-07-27 15:51:34 -0700957 // Called from native code.
958 private void userActivityFromNative(long eventTime, int event, int flags) {
959 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
960 }
961
962 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
963 synchronized (mLock) {
964 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
965 updatePowerStateLocked();
966 }
967 }
968 }
969
970 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
971 if (DEBUG_SPEW) {
972 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
973 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
974 + ", uid=" + uid);
975 }
976
977 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -0800978 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -0700979 return false;
980 }
981
Jeff Brown3edf5272014-08-14 19:25:14 -0700982 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
983 try {
Jeff Brown0a571122014-08-21 21:50:43 -0700984 if (eventTime > mLastInteractivePowerHintTime) {
985 powerHintInternal(POWER_HINT_INTERACTION, 0);
986 mLastInteractivePowerHintTime = eventTime;
987 }
988
Jeff Brown3edf5272014-08-14 19:25:14 -0700989 mNotifier.onUserActivity(event, uid);
Jeff Brown96307042012-07-27 15:51:34 -0700990
Jeff Brown0a571122014-08-21 21:50:43 -0700991 if (mWakefulness == WAKEFULNESS_ASLEEP
992 || mWakefulness == WAKEFULNESS_DOZING
993 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
994 return false;
995 }
996
Jeff Brown3edf5272014-08-14 19:25:14 -0700997 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
998 if (eventTime > mLastUserActivityTimeNoChangeLights
999 && eventTime > mLastUserActivityTime) {
1000 mLastUserActivityTimeNoChangeLights = eventTime;
1001 mDirty |= DIRTY_USER_ACTIVITY;
1002 return true;
1003 }
1004 } else {
1005 if (eventTime > mLastUserActivityTime) {
1006 mLastUserActivityTime = eventTime;
1007 mDirty |= DIRTY_USER_ACTIVITY;
1008 return true;
1009 }
Jeff Brown96307042012-07-27 15:51:34 -07001010 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001011 } finally {
1012 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001013 }
1014 return false;
1015 }
1016
Jeff Brownc12035c2014-08-13 18:52:25 -07001017 private void wakeUpInternal(long eventTime, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001018 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001019 if (wakeUpNoUpdateLocked(eventTime, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001020 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001021 }
1022 }
Jeff Brown96307042012-07-27 15:51:34 -07001023 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001024
Jeff Brownc12035c2014-08-13 18:52:25 -07001025 private boolean wakeUpNoUpdateLocked(long eventTime, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001026 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001027 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Joe Onorato60607a92010-10-23 14:49:30 -07001028 }
Jeff Brown96307042012-07-27 15:51:34 -07001029
1030 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1031 || !mBootCompleted || !mSystemReady) {
1032 return false;
1033 }
1034
Jeff Brown3edf5272014-08-14 19:25:14 -07001035 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1036 try {
1037 switch (mWakefulness) {
1038 case WAKEFULNESS_ASLEEP:
1039 Slog.i(TAG, "Waking up from sleep (uid " + uid +")...");
1040 break;
1041 case WAKEFULNESS_DREAMING:
1042 Slog.i(TAG, "Waking up from dream (uid " + uid +")...");
1043 break;
1044 case WAKEFULNESS_DOZING:
1045 Slog.i(TAG, "Waking up from dozing (uid " + uid +")...");
1046 break;
1047 }
1048
1049 mLastWakeTime = eventTime;
1050 mDirty |= DIRTY_WAKEFULNESS;
1051 mWakefulness = WAKEFULNESS_AWAKE;
1052 setInteractiveStateLocked(true, 0);
1053
1054 userActivityNoUpdateLocked(
1055 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
1056 } finally {
1057 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001058 }
Jeff Brown96307042012-07-27 15:51:34 -07001059 return true;
1060 }
1061
Jeff Brownc12035c2014-08-13 18:52:25 -07001062 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001063 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001064 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001065 updatePowerStateLocked();
1066 }
1067 }
1068 }
1069
Jeff Brown26875502014-01-30 21:47:47 -08001070 // This method is called goToSleep for historical reasons but we actually start
1071 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -07001072 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001073 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001074 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001075 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001076 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001077 }
1078
Jeff Brown26875502014-01-30 21:47:47 -08001079 if (eventTime < mLastWakeTime
1080 || mWakefulness == WAKEFULNESS_ASLEEP
1081 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001082 || !mBootCompleted || !mSystemReady) {
1083 return false;
1084 }
1085
Jeff Brown3edf5272014-08-14 19:25:14 -07001086 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1087 try {
1088 switch (reason) {
1089 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1090 Slog.i(TAG, "Going to sleep due to device administration policy "
1091 + "(uid " + uid +")...");
1092 break;
1093 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1094 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1095 break;
1096 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1097 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1098 break;
1099 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1100 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1101 break;
1102 case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1103 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1104 break;
1105 default:
1106 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1107 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
Jeff Brown96307042012-07-27 15:51:34 -07001108 break;
1109 }
Jeff Brown6d8fd272014-05-20 21:24:38 -07001110
Jeff Brown3edf5272014-08-14 19:25:14 -07001111 mLastSleepTime = eventTime;
1112 mDirty |= DIRTY_WAKEFULNESS;
1113 mWakefulness = WAKEFULNESS_DOZING;
1114 mSandmanSummoned = true;
1115 setInteractiveStateLocked(false, reason);
1116
1117 // Report the number of wake locks that will be cleared by going to sleep.
1118 int numWakeLocksCleared = 0;
1119 final int numWakeLocks = mWakeLocks.size();
1120 for (int i = 0; i < numWakeLocks; i++) {
1121 final WakeLock wakeLock = mWakeLocks.get(i);
1122 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1123 case PowerManager.FULL_WAKE_LOCK:
1124 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1125 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1126 numWakeLocksCleared += 1;
1127 break;
1128 }
1129 }
1130 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
1131
1132 // Skip dozing if requested.
1133 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1134 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1135 }
1136 } finally {
1137 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001138 }
Jeff Brown96307042012-07-27 15:51:34 -07001139 return true;
1140 }
1141
Jeff Brownc12035c2014-08-13 18:52:25 -07001142 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001143 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001144 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001145 updatePowerStateLocked();
1146 }
1147 }
1148 }
1149
Jeff Brownc12035c2014-08-13 18:52:25 -07001150 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001151 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001152 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001153 }
1154
1155 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1156 || !mBootCompleted || !mSystemReady) {
1157 return false;
1158 }
1159
Jeff Brown3edf5272014-08-14 19:25:14 -07001160 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1161 try {
1162 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001163
Jeff Brown3edf5272014-08-14 19:25:14 -07001164 mDirty |= DIRTY_WAKEFULNESS;
1165 mWakefulness = WAKEFULNESS_DREAMING;
1166 mSandmanSummoned = true;
1167 setInteractiveStateLocked(true, 0);
1168 } finally {
1169 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1170 }
Jeff Brown26875502014-01-30 21:47:47 -08001171 return true;
1172 }
1173
1174 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001175 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001176 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001177 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1178 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001179 }
1180
1181 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1182 || !mBootCompleted || !mSystemReady) {
1183 return false;
1184 }
1185
Jeff Brown3edf5272014-08-14 19:25:14 -07001186 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1187 try {
1188 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001189
Jeff Brown3edf5272014-08-14 19:25:14 -07001190 mDirty |= DIRTY_WAKEFULNESS;
1191 mWakefulness = WAKEFULNESS_ASLEEP;
1192 setInteractiveStateLocked(false, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1193 } finally {
1194 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1195 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001196 return true;
1197 }
1198
Jeff Brown037c33e2014-04-09 00:31:55 -07001199 private void setInteractiveStateLocked(boolean interactive, int reason) {
1200 if (mInteractive != interactive) {
1201 finishInteractiveStateChangeLocked();
1202
1203 mInteractive = interactive;
1204 mInteractiveChanging = true;
1205 mNotifier.onInteractiveStateChangeStarted(interactive, reason);
1206 }
1207 }
1208
1209 private void finishInteractiveStateChangeLocked() {
1210 if (mInteractiveChanging) {
1211 mNotifier.onInteractiveStateChangeFinished(mInteractive);
1212 mInteractiveChanging = false;
1213 }
1214 }
1215
Jeff Brown96307042012-07-27 15:51:34 -07001216 /**
1217 * Updates the global power state based on dirty bits recorded in mDirty.
1218 *
1219 * This is the main function that performs power state transitions.
1220 * We centralize them here so that we can recompute the power state completely
1221 * each time something important changes, and ensure that we do it the same
1222 * way each time. The point is to gather all of the transition logic here.
1223 */
1224 private void updatePowerStateLocked() {
1225 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001226 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001228 if (!Thread.holdsLock(mLock)) {
1229 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001231
Jeff Brown3edf5272014-08-14 19:25:14 -07001232 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1233 try {
1234 // Phase 0: Basic state updates.
1235 updateIsPoweredLocked(mDirty);
1236 updateStayOnLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
Jeff Brown3edf5272014-08-14 19:25:14 -07001238 // Phase 1: Update wakefulness.
1239 // Loop because the wake lock and user activity computations are influenced
1240 // by changes in wakefulness.
1241 final long now = SystemClock.uptimeMillis();
1242 int dirtyPhase2 = 0;
1243 for (;;) {
1244 int dirtyPhase1 = mDirty;
1245 dirtyPhase2 |= dirtyPhase1;
1246 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001247
Jeff Brown3edf5272014-08-14 19:25:14 -07001248 updateWakeLockSummaryLocked(dirtyPhase1);
1249 updateUserActivitySummaryLocked(now, dirtyPhase1);
1250 if (!updateWakefulnessLocked(dirtyPhase1)) {
1251 break;
1252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001254
Jeff Brown2175e9c2014-09-12 16:11:07 -07001255 // Phase 2: Update display power state.
1256 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
Jeff Brown3edf5272014-08-14 19:25:14 -07001257
Jeff Brown2175e9c2014-09-12 16:11:07 -07001258 // Phase 3: Update dream state (depends on display ready signal).
1259 updateDreamLocked(dirtyPhase2, displayBecameReady);
1260
1261 // Phase 4: Send notifications, if needed.
Jeff Brown3edf5272014-08-14 19:25:14 -07001262 if (mDisplayReady) {
1263 finishInteractiveStateChangeLocked();
1264 }
1265
Jeff Brown2175e9c2014-09-12 16:11:07 -07001266 // Phase 5: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001267 // Because we might release the last suspend blocker here, we need to make sure
1268 // we finished everything else first!
1269 updateSuspendBlockerLocked();
1270 } finally {
1271 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
Jeff Brown96307042012-07-27 15:51:34 -07001273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001274
Jim Miller92e66dd2012-02-21 18:57:12 -08001275 /**
Jeff Brown96307042012-07-27 15:51:34 -07001276 * Updates the value of mIsPowered.
1277 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001278 */
Jeff Brown96307042012-07-27 15:51:34 -07001279 private void updateIsPoweredLocked(int dirty) {
1280 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001281 final boolean wasPowered = mIsPowered;
1282 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001283 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001284 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1285 mPlugType = mBatteryManagerInternal.getPlugType();
1286 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1287 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001288
Jeff Brown26875502014-01-30 21:47:47 -08001289 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001290 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001291 + ", mIsPowered=" + mIsPowered
1292 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001293 + ", mPlugType=" + mPlugType
1294 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001295 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001296
Jeff Brownf3fb8952012-10-02 20:57:05 -07001297 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001298 mDirty |= DIRTY_IS_POWERED;
1299
Jeff Brown3b971592013-01-09 18:46:37 -08001300 // Update wireless dock detection state.
1301 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1302 mIsPowered, mPlugType, mBatteryLevel);
1303
Jeff Brown96307042012-07-27 15:51:34 -07001304 // Treat plugging and unplugging the devices as a user activity.
1305 // Users find it disconcerting when they plug or unplug the device
1306 // and it shuts off right away.
1307 // Some devices also wake the device when plugged or unplugged because
1308 // they don't have a charging LED.
1309 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001310 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1311 dockedOnWirelessCharger)) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001312 wakeUpNoUpdateLocked(now, Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001313 }
1314 userActivityNoUpdateLocked(
1315 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001316
1317 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001318 // it can provide feedback to the user.
1319 if (dockedOnWirelessCharger) {
Jeff Brown84e27562012-12-07 13:56:34 -08001320 mNotifier.onWirelessChargingStarted();
1321 }
Jeff Brown96307042012-07-27 15:51:34 -07001322 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001323
Dianne Hackborn14272302014-06-10 23:13:02 -07001324 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) {
John Spurlock1bb480a2014-08-02 17:12:43 -04001325 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) {
1326 if (DEBUG_SPEW) {
1327 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze");
1328 }
1329 mAutoLowPowerModeSnoozing = false;
1330 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001331 updateLowPowerModeLocked();
1332 }
Jeff Brown96307042012-07-27 15:51:34 -07001333 }
1334 }
1335
Jeff Brown3b971592013-01-09 18:46:37 -08001336 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1337 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001338 // Don't wake when powered unless configured to do so.
1339 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1340 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001341 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001342
Jeff Brown3b971592013-01-09 18:46:37 -08001343 // Don't wake when undocked from wireless charger.
1344 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001345 if (wasPowered && !mIsPowered
1346 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1347 return false;
1348 }
Jeff Brown3b971592013-01-09 18:46:37 -08001349
1350 // Don't wake when docked on wireless charger unless we are certain of it.
1351 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001352 if (!wasPowered && mIsPowered
1353 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001354 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001355 return false;
1356 }
1357
1358 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001359 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001360 return false;
1361 }
1362
Bryce Lee584a4452014-10-21 15:55:55 -07001363 // Don't wake while theater mode is enabled.
1364 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1365 return false;
1366 }
1367
Jeff Brown9fca9e92012-10-05 14:42:56 -07001368 // Otherwise wake up!
1369 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001370 }
1371
Jeff Brown96307042012-07-27 15:51:34 -07001372 /**
1373 * Updates the value of mStayOn.
1374 * Sets DIRTY_STAY_ON if a change occurred.
1375 */
1376 private void updateStayOnLocked(int dirty) {
1377 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001378 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001379 if (mStayOnWhilePluggedInSetting != 0
1380 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001381 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001382 } else {
1383 mStayOn = false;
1384 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001385
1386 if (mStayOn != wasStayOn) {
1387 mDirty |= DIRTY_STAY_ON;
1388 }
Jeff Brown96307042012-07-27 15:51:34 -07001389 }
1390 }
1391
1392 /**
1393 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1394 * Note that most wake-locks are ignored when the system is asleep.
1395 *
1396 * This function must have no other side-effects.
1397 */
Jeff Brownec083212013-09-11 20:45:25 -07001398 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001399 private void updateWakeLockSummaryLocked(int dirty) {
1400 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1401 mWakeLockSummary = 0;
1402
1403 final int numWakeLocks = mWakeLocks.size();
1404 for (int i = 0; i < numWakeLocks; i++) {
1405 final WakeLock wakeLock = mWakeLocks.get(i);
1406 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1407 case PowerManager.PARTIAL_WAKE_LOCK:
1408 mWakeLockSummary |= WAKE_LOCK_CPU;
1409 break;
1410 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001411 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001412 break;
1413 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001414 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001415 break;
1416 case PowerManager.SCREEN_DIM_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001417 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001418 break;
1419 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001420 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001421 break;
Jeff Brown26875502014-01-30 21:47:47 -08001422 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001423 mWakeLockSummary |= WAKE_LOCK_DOZE;
Jeff Brown26875502014-01-30 21:47:47 -08001424 break;
Jeff Brown96307042012-07-27 15:51:34 -07001425 }
1426 }
1427
Jeff Brown037c33e2014-04-09 00:31:55 -07001428 // Cancel wake locks that make no sense based on the current state.
1429 if (mWakefulness != WAKEFULNESS_DOZING) {
1430 mWakeLockSummary &= ~WAKE_LOCK_DOZE;
1431 }
1432 if (mWakefulness == WAKEFULNESS_ASLEEP
1433 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1434 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1435 | WAKE_LOCK_BUTTON_BRIGHT);
1436 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1437 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1438 }
1439 }
1440
1441 // Infer implied wake locks where necessary based on the current state.
1442 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1443 if (mWakefulness == WAKEFULNESS_AWAKE) {
1444 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1445 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1446 mWakeLockSummary |= WAKE_LOCK_CPU;
1447 }
1448 }
1449
Jeff Brown96307042012-07-27 15:51:34 -07001450 if (DEBUG_SPEW) {
1451 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1452 + wakefulnessToString(mWakefulness)
1453 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1454 }
1455 }
1456 }
1457
1458 /**
1459 * Updates the value of mUserActivitySummary to summarize the user requested
1460 * state of the system such as whether the screen should be bright or dim.
1461 * Note that user activity is ignored when the system is asleep.
1462 *
1463 * This function must have no other side-effects.
1464 */
1465 private void updateUserActivitySummaryLocked(long now, int dirty) {
1466 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07001467 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
1468 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001469 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1470
1471 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001472 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07001473 || mWakefulness == WAKEFULNESS_DREAMING
1474 || mWakefulness == WAKEFULNESS_DOZING) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001475 final int sleepTimeout = getSleepTimeoutLocked();
1476 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07001477 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07001478
1479 mUserActivitySummary = 0;
1480 if (mLastUserActivityTime >= mLastWakeTime) {
1481 nextTimeout = mLastUserActivityTime
1482 + screenOffTimeout - screenDimDuration;
1483 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001484 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001485 } else {
1486 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1487 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001488 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001489 }
1490 }
1491 }
1492 if (mUserActivitySummary == 0
1493 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1494 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07001495 if (now < nextTimeout) {
1496 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) {
1497 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
1498 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
1499 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
1500 }
Jeff Brown96307042012-07-27 15:51:34 -07001501 }
1502 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07001503 if (mUserActivitySummary == 0) {
1504 if (sleepTimeout >= 0) {
1505 final long anyUserActivity = Math.max(mLastUserActivityTime,
1506 mLastUserActivityTimeNoChangeLights);
1507 if (anyUserActivity >= mLastWakeTime) {
1508 nextTimeout = anyUserActivity + sleepTimeout;
1509 if (now < nextTimeout) {
1510 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1511 }
1512 }
1513 } else {
1514 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1515 nextTimeout = -1;
1516 }
1517 }
1518 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001519 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1520 msg.setAsynchronous(true);
1521 mHandler.sendMessageAtTime(msg, nextTimeout);
1522 }
1523 } else {
1524 mUserActivitySummary = 0;
1525 }
1526
1527 if (DEBUG_SPEW) {
1528 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1529 + wakefulnessToString(mWakefulness)
1530 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1531 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1532 }
1533 }
1534 }
1535
1536 /**
1537 * Called when a user activity timeout has occurred.
1538 * Simply indicates that something about user activity has changed so that the new
1539 * state can be recomputed when the power state is updated.
1540 *
1541 * This function must have no other side-effects besides setting the dirty
1542 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
1543 */
1544 private void handleUserActivityTimeout() { // runs on handler thread
1545 synchronized (mLock) {
1546 if (DEBUG_SPEW) {
1547 Slog.d(TAG, "handleUserActivityTimeout");
1548 }
1549
1550 mDirty |= DIRTY_USER_ACTIVITY;
1551 updatePowerStateLocked();
1552 }
1553 }
1554
Jeff Brown05af6ad2014-09-30 20:54:30 -07001555 private int getSleepTimeoutLocked() {
1556 int timeout = mSleepTimeoutSetting;
1557 if (timeout <= 0) {
1558 return -1;
1559 }
1560 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
1561 }
1562
1563 private int getScreenOffTimeoutLocked(int sleepTimeout) {
Jeff Brown96307042012-07-27 15:51:34 -07001564 int timeout = mScreenOffTimeoutSetting;
1565 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1566 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1567 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001568 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1569 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1570 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07001571 if (sleepTimeout >= 0) {
1572 timeout = Math.min(timeout, sleepTimeout);
1573 }
Jeff Brown27736f52014-05-20 17:17:10 -07001574 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07001575 }
1576
Jeff Brownff532542012-10-02 21:18:04 -07001577 private int getScreenDimDurationLocked(int screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07001578 return Math.min(mMaximumScreenDimDurationConfig,
1579 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07001580 }
1581
1582 /**
1583 * Updates the wakefulness of the device.
1584 *
Jeff Brown26875502014-01-30 21:47:47 -08001585 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07001586 * based on the current wake locks and user activity state. It may modify mDirty
1587 * if the wakefulness changes.
1588 *
1589 * Returns true if the wakefulness changed and we need to restart power state calculation.
1590 */
1591 private boolean updateWakefulnessLocked(int dirty) {
1592 boolean changed = false;
1593 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07001594 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1595 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001596 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1597 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001598 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07001599 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001600 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07001601 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001602 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001603 } else {
1604 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07001605 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001606 }
Jeff Brown96307042012-07-27 15:51:34 -07001607 }
1608 }
1609 return changed;
1610 }
1611
Jeff Brown645832d2012-10-03 14:57:03 -07001612 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07001613 * Returns true if the device should automatically nap and start dreaming when the user
1614 * activity timeout has expired and it's bedtime.
1615 */
1616 private boolean shouldNapAtBedTimeLocked() {
1617 return mDreamsActivateOnSleepSetting
1618 || (mDreamsActivateOnDockSetting
1619 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1620 }
1621
1622 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001623 * Returns true if the device should go to sleep now.
1624 * Also used when exiting a dream to determine whether we should go back
1625 * to being fully awake or else go to sleep for good.
1626 */
Jeff Brown96307042012-07-27 15:51:34 -07001627 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001628 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07001629 }
1630
1631 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07001632 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07001633 * or the stay on while powered setting. We also keep the phone awake when
1634 * the proximity sensor returns a positive result so that the device does not
1635 * lock while in a phone call. This function only controls whether the device
1636 * will go to sleep or dream which is independent of whether it will be allowed
1637 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07001638 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07001639 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001640 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07001641 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07001642 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07001643 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1644 | USER_ACTIVITY_SCREEN_DIM)) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07001645 }
1646
1647 /**
1648 * Determines whether to post a message to the sandman to update the dream state.
1649 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07001650 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001651 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07001652 | DIRTY_USER_ACTIVITY
1653 | DIRTY_WAKE_LOCKS
1654 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001655 | DIRTY_SETTINGS
1656 | DIRTY_IS_POWERED
1657 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07001658 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07001659 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
1660 if (mDisplayReady) {
1661 scheduleSandmanLocked();
1662 }
Jeff Brown96307042012-07-27 15:51:34 -07001663 }
1664 }
1665
1666 private void scheduleSandmanLocked() {
1667 if (!mSandmanScheduled) {
1668 mSandmanScheduled = true;
1669 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1670 msg.setAsynchronous(true);
1671 mHandler.sendMessage(msg);
1672 }
1673 }
1674
1675 /**
Jeff Brown26875502014-01-30 21:47:47 -08001676 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07001677 *
1678 * We do this asynchronously because we must call out of the power manager to start
1679 * the dream and we don't want to hold our lock while doing so. There is a risk that
1680 * the device will wake or go to sleep in the meantime so we have to handle that case.
1681 */
1682 private void handleSandman() { // runs on handler thread
1683 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08001684 final boolean startDreaming;
1685 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07001686 synchronized (mLock) {
1687 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08001688 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07001689 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001690 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08001691 mSandmanSummoned = false;
1692 } else {
1693 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001694 }
1695 }
1696
Jeff Brown96307042012-07-27 15:51:34 -07001697 // Start dreaming if needed.
1698 // We only control the dream on the handler thread, so we don't need to worry about
1699 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08001700 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07001701 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08001702 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07001703 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07001704 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08001705 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07001706 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001707 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08001708 } else {
1709 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001710 }
1711
1712 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07001713 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08001714 // Remember the initial battery level when the dream started.
1715 if (startDreaming && isDreaming) {
1716 mBatteryLevelWhenDreamStarted = mBatteryLevel;
1717 if (wakefulness == WAKEFULNESS_DOZING) {
1718 Slog.i(TAG, "Dozing...");
1719 } else {
1720 Slog.i(TAG, "Dreaming...");
1721 }
1722 }
1723
1724 // If preconditions changed, wait for the next iteration to determine
1725 // whether the dream should continue (or be restarted).
1726 if (mSandmanSummoned || mWakefulness != wakefulness) {
1727 return; // wait for next cycle
1728 }
1729
1730 // Determine whether the dream should continue.
1731 if (wakefulness == WAKEFULNESS_DREAMING) {
1732 if (isDreaming && canDreamLocked()) {
1733 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07001734 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08001735 - mDreamsBatteryLevelDrainCutoffConfig
1736 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07001737 // If the user activity timeout expired and the battery appears
1738 // to be draining faster than it is charging then stop dreaming
1739 // and go to sleep.
1740 Slog.i(TAG, "Stopping dream because the battery appears to "
1741 + "be draining faster than it is charging. "
1742 + "Battery level when dream started: "
1743 + mBatteryLevelWhenDreamStarted + "%. "
1744 + "Battery level now: " + mBatteryLevel + "%.");
1745 } else {
Jeff Brown26875502014-01-30 21:47:47 -08001746 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07001747 }
Jeff Brown96307042012-07-27 15:51:34 -07001748 }
Jeff Brown26875502014-01-30 21:47:47 -08001749
1750 // Dream has ended or will be stopped. Update the power state.
1751 if (isItBedTimeYetLocked()) {
1752 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07001753 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001754 updatePowerStateLocked();
1755 } else {
Jeff Brownc12035c2014-08-13 18:52:25 -07001756 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001757 updatePowerStateLocked();
1758 }
1759 } else if (wakefulness == WAKEFULNESS_DOZING) {
1760 if (isDreaming) {
1761 return; // continue dozing
1762 }
1763
1764 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07001765 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001766 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001767 }
Jeff Brown96307042012-07-27 15:51:34 -07001768 }
1769
Jeff Brown26875502014-01-30 21:47:47 -08001770 // Stop dream.
1771 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07001772 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07001773 }
1774 }
1775
1776 /**
Jeff Brown26875502014-01-30 21:47:47 -08001777 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07001778 */
1779 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08001780 if (mWakefulness != WAKEFULNESS_DREAMING
1781 || !mDreamsSupportedConfig
1782 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07001783 || !mDisplayPowerRequest.isBrightOrDim()
Jeff Brown05af6ad2014-09-30 20:54:30 -07001784 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1785 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08001786 || !mBootCompleted) {
1787 return false;
1788 }
1789 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08001790 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08001791 return false;
1792 }
1793 if (!mIsPowered
1794 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
1795 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
1796 return false;
1797 }
1798 if (mIsPowered
1799 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
1800 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
1801 return false;
Jeff Brown96307042012-07-27 15:51:34 -07001802 }
1803 }
Jeff Brown26875502014-01-30 21:47:47 -08001804 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001805 }
1806
Jeff Brown96307042012-07-27 15:51:34 -07001807 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07001808 * Returns true if the device is allowed to doze in its current state.
1809 */
1810 private boolean canDozeLocked() {
1811 return mWakefulness == WAKEFULNESS_DOZING;
1812 }
1813
1814 /**
Jeff Brown96307042012-07-27 15:51:34 -07001815 * Updates the display power state asynchronously.
1816 * When the update is finished, mDisplayReady will be set to true. The display
1817 * controller posts a message to tell us when the actual display power state
1818 * has been updated so we come back here to double-check and finish up.
1819 *
1820 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07001821 *
1822 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07001823 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07001824 private boolean updateDisplayPowerStateLocked(int dirty) {
1825 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07001826 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1827 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Jeff Browne333e672014-10-28 13:48:55 -07001828 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07001829 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001830
Jeff Browne333e672014-10-28 13:48:55 -07001831 // Handle screen brightness boost timeout.
1832 updateScreenBrightnessBoostLocked();
1833
1834 // Determine appropriate screen brightness and auto-brightness adjustments.
Jeff Brown96307042012-07-27 15:51:34 -07001835 int screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001836 float screenAutoBrightnessAdjustment = 0.0f;
Jeff Brown96307042012-07-27 15:51:34 -07001837 boolean autoBrightness = (mScreenBrightnessModeSetting ==
1838 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1839 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1840 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1841 autoBrightness = false;
1842 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1843 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1844 } else if (isValidBrightness(mScreenBrightnessSetting)) {
Jeff Brown330560f2012-08-21 22:10:57 -07001845 screenBrightness = mScreenBrightnessSetting;
Jeff Brown96307042012-07-27 15:51:34 -07001846 }
1847 if (autoBrightness) {
1848 screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001849 if (isValidAutoBrightnessAdjustment(
1850 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1851 screenAutoBrightnessAdjustment =
1852 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1853 } else if (isValidAutoBrightnessAdjustment(
1854 mScreenAutoBrightnessAdjustmentSetting)) {
1855 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1856 }
Jeff Brown96307042012-07-27 15:51:34 -07001857 }
1858 screenBrightness = Math.max(Math.min(screenBrightness,
1859 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
Jeff Brown330560f2012-08-21 22:10:57 -07001860 screenAutoBrightnessAdjustment = Math.max(Math.min(
1861 screenAutoBrightnessAdjustment, 1.0f), -1.0f);
Jeff Browne333e672014-10-28 13:48:55 -07001862
1863 // Update display power request.
Jeff Brown96307042012-07-27 15:51:34 -07001864 mDisplayPowerRequest.screenBrightness = screenBrightness;
Jeff Brown330560f2012-08-21 22:10:57 -07001865 mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1866 screenAutoBrightnessAdjustment;
Jeff Brown96307042012-07-27 15:51:34 -07001867 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07001868 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07001869 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled;
Jeff Browne333e672014-10-28 13:48:55 -07001870 mDisplayPowerRequest.boostScreenBrightness = mScreenBrightnessBoostInProgress;
Ruchi Kandoif974cc82014-05-01 11:25:10 -07001871
Jeff Brown970d4132014-07-19 11:33:47 -07001872 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
1873 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
1874 mDisplayPowerRequest.dozeScreenBrightness =
1875 mDozeScreenBrightnessOverrideFromDreamManager;
1876 } else {
1877 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
1878 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
1879 }
1880
Jeff Brown131206b2014-04-08 17:27:14 -07001881 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Browne333e672014-10-28 13:48:55 -07001882 mRequestWaitForNegativeProximity) && !mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07001883 mRequestWaitForNegativeProximity = false;
1884
1885 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07001886 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07001887 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07001888 + ", mWakefulness=" + mWakefulness
1889 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1890 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07001891 + ", mBootCompleted=" + mBootCompleted
1892 + ", mScreenBrightnessBoostInProgress="
1893 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07001894 }
1895 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07001896 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07001897 }
1898
Jeff Browne333e672014-10-28 13:48:55 -07001899 private void updateScreenBrightnessBoostLocked() {
1900 if (mScreenBrightnessBoostInProgress) {
1901 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
1902 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
1903 final long boostTimeout = mLastScreenBrightnessBoostTime +
1904 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
1905 if (boostTimeout > SystemClock.uptimeMillis()) {
1906 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
1907 msg.setAsynchronous(true);
1908 mHandler.sendMessageAtTime(msg, boostTimeout);
1909 return;
1910 }
1911 }
1912 mScreenBrightnessBoostInProgress = false;
1913 }
1914 }
1915
Jeff Brown96307042012-07-27 15:51:34 -07001916 private static boolean isValidBrightness(int value) {
1917 return value >= 0 && value <= 255;
1918 }
1919
Jeff Brown330560f2012-08-21 22:10:57 -07001920 private static boolean isValidAutoBrightnessAdjustment(float value) {
Jeff Brown5d03a532012-08-22 13:22:02 -07001921 // Handles NaN by always returning false.
1922 return value >= -1.0f && value <= 1.0f;
Jeff Brown330560f2012-08-21 22:10:57 -07001923 }
1924
Jeff Brown970d4132014-07-19 11:33:47 -07001925 private int getDesiredScreenPolicyLocked() {
Jeff Brown96307042012-07-27 15:51:34 -07001926 if (mWakefulness == WAKEFULNESS_ASLEEP) {
Jeff Brown970d4132014-07-19 11:33:47 -07001927 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001928 }
1929
Jeff Brown2175e9c2014-09-12 16:11:07 -07001930 if (mWakefulness == WAKEFULNESS_DOZING) {
1931 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1932 return DisplayPowerRequest.POLICY_DOZE;
1933 }
1934 if (mDozeAfterScreenOffConfig) {
1935 return DisplayPowerRequest.POLICY_OFF;
1936 }
1937 // Fall through and preserve the current screen policy if not configured to
1938 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08001939 }
1940
Jeff Brown96307042012-07-27 15:51:34 -07001941 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1942 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1943 || !mBootCompleted) {
Jeff Brown970d4132014-07-19 11:33:47 -07001944 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001945 }
1946
Jeff Brown970d4132014-07-19 11:33:47 -07001947 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001948 }
1949
Jeff Brown131206b2014-04-08 17:27:14 -07001950 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
1951 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07001952 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07001953
Jeff Brown96307042012-07-27 15:51:34 -07001954 @Override
1955 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001956 synchronized (mLock) {
1957 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1958 updatePowerStateLocked();
1959 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001960 }
1961
1962 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07001963 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001964 synchronized (mLock) {
1965 mProximityPositive = true;
1966 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1967 updatePowerStateLocked();
1968 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001969 }
1970
1971 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001972 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001973 synchronized (mLock) {
1974 mProximityPositive = false;
1975 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1976 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1977 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1978 updatePowerStateLocked();
1979 }
Jeff Brown96307042012-07-27 15:51:34 -07001980 }
Jeff Brown131206b2014-04-08 17:27:14 -07001981
1982 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07001983 public void onDisplayStateChange(int state) {
1984 // This method is only needed to support legacy display blanking behavior
1985 // where the display's power state is coupled to suspend or to the power HAL.
1986 // The order of operations matters here.
1987 synchronized (mLock) {
1988 if (mDisplayState != state) {
1989 mDisplayState = state;
1990 if (state == Display.STATE_OFF) {
1991 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
1992 setHalInteractiveModeLocked(false);
1993 }
1994 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1995 setHalAutoSuspendModeLocked(true);
1996 }
1997 } else {
1998 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1999 setHalAutoSuspendModeLocked(false);
2000 }
2001 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2002 setHalInteractiveModeLocked(true);
2003 }
2004 }
2005 }
2006 }
2007 }
2008
2009 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002010 public void acquireSuspendBlocker() {
2011 mDisplaySuspendBlocker.acquire();
2012 }
2013
2014 @Override
2015 public void releaseSuspendBlocker() {
2016 mDisplaySuspendBlocker.release();
2017 }
2018
2019 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002020 public String toString() {
2021 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002022 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002023 }
2024 }
Jeff Brown96307042012-07-27 15:51:34 -07002025 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002026
Jeff Brown96307042012-07-27 15:51:34 -07002027 private boolean shouldUseProximitySensorLocked() {
2028 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
2029 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002030
Jeff Brown96307042012-07-27 15:51:34 -07002031 /**
2032 * Updates the suspend blocker that keeps the CPU alive.
2033 *
2034 * This function must have no other side-effects.
2035 */
2036 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002037 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002038 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2039 final boolean autoSuspend = !needDisplaySuspendBlocker;
2040
2041 // Disable auto-suspend if needed.
2042 if (!autoSuspend) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002043 if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2044 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002045 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002046 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2047 setHalInteractiveModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002048 }
2049 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002050
2051 // First acquire suspend blockers if needed.
2052 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2053 mWakeLockSuspendBlocker.acquire();
2054 mHoldingWakeLockSuspendBlocker = true;
2055 }
2056 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2057 mDisplaySuspendBlocker.acquire();
2058 mHoldingDisplaySuspendBlocker = true;
2059 }
2060
2061 // Then release suspend blockers if needed.
2062 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2063 mWakeLockSuspendBlocker.release();
2064 mHoldingWakeLockSuspendBlocker = false;
2065 }
2066 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2067 mDisplaySuspendBlocker.release();
2068 mHoldingDisplaySuspendBlocker = false;
2069 }
Jeff Brown26875502014-01-30 21:47:47 -08002070
2071 // Enable auto-suspend if needed.
2072 if (autoSuspend) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002073 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2074 setHalInteractiveModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002075 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002076 if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2077 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002078 }
2079 }
Jeff Brown96307042012-07-27 15:51:34 -07002080 }
2081
Jeff Brownec083212013-09-11 20:45:25 -07002082 /**
2083 * Return true if we must keep a suspend blocker active on behalf of the display.
2084 * We do so if the screen is on or is in transition between states.
2085 */
Jeff Brown26875502014-01-30 21:47:47 -08002086 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002087 if (!mDisplayReady) {
2088 return true;
2089 }
Jeff Brown970d4132014-07-19 11:33:47 -07002090 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002091 // If we asked for the screen to be on but it is off due to the proximity
2092 // sensor then we may suspend but only if the configuration allows it.
2093 // On some hardware it may not be safe to suspend because the proximity
2094 // sensor may not be correctly configured as a wake-up source.
2095 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2096 || !mSuspendWhenScreenOffDueToProximityConfig) {
2097 return true;
2098 }
2099 }
Jeff Brown26875502014-01-30 21:47:47 -08002100 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002101 return false;
2102 }
2103
Jeff Brown037c33e2014-04-09 00:31:55 -07002104 private void setHalAutoSuspendModeLocked(boolean enable) {
2105 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002106 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002107 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002108 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002109 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002110 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2111 try {
2112 nativeSetAutoSuspend(enable);
2113 } finally {
2114 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2115 }
Jeff Brown26875502014-01-30 21:47:47 -08002116 }
2117 }
2118
Jeff Brown037c33e2014-04-09 00:31:55 -07002119 private void setHalInteractiveModeLocked(boolean enable) {
2120 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002121 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002122 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002123 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002124 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002125 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2126 try {
2127 nativeSetInteractive(enable);
2128 } finally {
2129 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2130 }
Jeff Brown26875502014-01-30 21:47:47 -08002131 }
2132 }
2133
Jeff Brown037c33e2014-04-09 00:31:55 -07002134 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002135 synchronized (mLock) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002136 return mInteractive;
Mike Lockwoodb2865412010-02-02 22:40:33 -05002137 }
2138 }
2139
Dianne Hackborneb94fa72014-06-03 17:48:12 -07002140 private boolean isLowPowerModeInternal() {
2141 synchronized (mLock) {
2142 return mLowPowerModeEnabled;
2143 }
2144 }
2145
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002146 private boolean setLowPowerModeInternal(boolean mode) {
2147 synchronized (mLock) {
2148 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered);
2149 if (mIsPowered) {
2150 return false;
2151 }
2152 Settings.Global.putInt(mContext.getContentResolver(),
2153 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0);
2154 mLowPowerModeSetting = mode;
2155
2156 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) {
2157 if (mode && mAutoLowPowerModeSnoozing) {
2158 if (DEBUG_SPEW) {
2159 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze");
2160 }
2161 mAutoLowPowerModeSnoozing = false;
2162 } else if (!mode && !mAutoLowPowerModeSnoozing) {
2163 if (DEBUG_SPEW) {
2164 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode");
2165 }
2166 mAutoLowPowerModeSnoozing = true;
2167 }
2168 }
2169
2170 updateLowPowerModeLocked();
2171 return true;
2172 }
2173 }
2174
Jeff Brown96307042012-07-27 15:51:34 -07002175 private void handleBatteryStateChangedLocked() {
2176 mDirty |= DIRTY_BATTERY_STATE;
2177 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002178 }
2179
Jeff Brownab887a02012-10-15 16:00:40 -07002180 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002181 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002182 if (mHandler == null || !mSystemReady) {
Jeff Brownab887a02012-10-15 16:00:40 -07002183 throw new IllegalStateException("Too early to call shutdown() or reboot()");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002184 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002185
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002186 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002187 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002188 public void run() {
2189 synchronized (this) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002190 if (shutdown) {
2191 ShutdownThread.shutdown(mContext, confirm);
2192 } else {
2193 ShutdownThread.reboot(mContext, reason, confirm);
2194 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002195 }
San Mehat1e512792010-01-07 10:40:29 -08002196 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002197 };
Jeff Brown96307042012-07-27 15:51:34 -07002198
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002199 // ShutdownThread must run on a looper capable of displaying the UI.
Jeff Brown96307042012-07-27 15:51:34 -07002200 Message msg = Message.obtain(mHandler, runnable);
2201 msg.setAsynchronous(true);
2202 mHandler.sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002203
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002204 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002205 if (wait) {
2206 synchronized (runnable) {
2207 while (true) {
2208 try {
2209 runnable.wait();
2210 } catch (InterruptedException e) {
2211 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002212 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002213 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002214 }
2215 }
2216
Jeff Brown96307042012-07-27 15:51:34 -07002217 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002218 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002219 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002220 public void run() {
2221 throw new RuntimeException(message);
2222 }
Dan Egnor60d87622009-12-16 16:32:58 -08002223 };
2224 try {
2225 t.start();
2226 t.join();
2227 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002228 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002229 }
2230 }
2231
Jeff Brown96307042012-07-27 15:51:34 -07002232 private void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002233 Settings.Global.putInt(mContext.getContentResolver(),
2234 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236
Jeff Brown96307042012-07-27 15:51:34 -07002237 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
2238 synchronized (mLock) {
2239 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2240 mDirty |= DIRTY_SETTINGS;
2241 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
2243 }
2244
Jeff Brown96307042012-07-27 15:51:34 -07002245 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
2246 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
2247 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002249
Jeff Brown96307042012-07-27 15:51:34 -07002250 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002251 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07002252 synchronized (mLock) {
2253 if (!mSystemReady) {
2254 return;
2255 }
2256 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002257 }
Jeff Brown96307042012-07-27 15:51:34 -07002258
2259 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002260 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07002261 }
2262
Jeff Browne333e672014-10-28 13:48:55 -07002263 private void boostScreenBrightnessInternal(long eventTime, int uid) {
2264 synchronized (mLock) {
2265 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
2266 || eventTime < mLastScreenBrightnessBoostTime) {
2267 return;
2268 }
2269
2270 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
2271 mLastScreenBrightnessBoostTime = eventTime;
2272 mScreenBrightnessBoostInProgress = true;
2273 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
2274
2275 userActivityNoUpdateLocked(eventTime,
2276 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
2277 updatePowerStateLocked();
2278 }
2279 }
2280
2281 /**
2282 * Called when a screen brightness boost timeout has occurred.
2283 *
2284 * This function must have no other side-effects besides setting the dirty
2285 * bit and calling update power state.
2286 */
2287 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
2288 synchronized (mLock) {
2289 if (DEBUG_SPEW) {
2290 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
2291 }
2292
2293 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
2294 updatePowerStateLocked();
2295 }
2296 }
2297
Jeff Brown96307042012-07-27 15:51:34 -07002298 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
2299 synchronized (mLock) {
2300 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
2301 mScreenBrightnessOverrideFromWindowManager = brightness;
2302 mDirty |= DIRTY_SETTINGS;
2303 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002304 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002305 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002306 }
2307
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002308 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
2309 synchronized (mLock) {
2310 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
2311 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
2312 mDirty |= DIRTY_SETTINGS;
2313 updatePowerStateLocked();
2314 }
2315 }
2316 }
2317
Jeff Brown96307042012-07-27 15:51:34 -07002318 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
2319 synchronized (mLock) {
2320 if (mTemporaryScreenBrightnessSettingOverride != brightness) {
2321 mTemporaryScreenBrightnessSettingOverride = brightness;
2322 mDirty |= DIRTY_SETTINGS;
2323 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002324 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002325 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002326 }
2327
Jeff Brown330560f2012-08-21 22:10:57 -07002328 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
2329 synchronized (mLock) {
2330 // Note: This condition handles NaN because NaN is not equal to any other
2331 // value, including itself.
2332 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
2333 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
2334 mDirty |= DIRTY_SETTINGS;
2335 updatePowerStateLocked();
2336 }
2337 }
Jeff Brown96307042012-07-27 15:51:34 -07002338 }
2339
Jeff Brown970d4132014-07-19 11:33:47 -07002340 private void setDozeOverrideFromDreamManagerInternal(
2341 int screenState, int screenBrightness) {
2342 synchronized (mLock) {
2343 if (mDozeScreenStateOverrideFromDreamManager != screenState
2344 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
2345 mDozeScreenStateOverrideFromDreamManager = screenState;
2346 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
2347 mDirty |= DIRTY_SETTINGS;
2348 updatePowerStateLocked();
2349 }
2350 }
2351 }
2352
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07002353 private void powerHintInternal(int hintId, int data) {
2354 nativeSendPowerHint(hintId, data);
2355 }
2356
Jeff Brown96307042012-07-27 15:51:34 -07002357 /**
2358 * Low-level function turn the device off immediately, without trying
2359 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
2360 */
2361 public static void lowLevelShutdown() {
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002362 SystemProperties.set("sys.powerctl", "shutdown");
Jeff Brown96307042012-07-27 15:51:34 -07002363 }
2364
2365 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08002366 * Low-level function to reboot the device. On success, this
2367 * function doesn't return. If more than 20 seconds passes from
2368 * the time a reboot is requested (120 seconds for reboot to
2369 * recovery), this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07002370 *
2371 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07002372 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002373 public static void lowLevelReboot(String reason) {
2374 if (reason == null) {
2375 reason = "";
2376 }
Doug Zongker3b0218b2014-01-14 12:29:06 -08002377 long duration;
2378 if (reason.equals(PowerManager.REBOOT_RECOVERY)) {
2379 // If we are rebooting to go into recovery, instead of
2380 // setting sys.powerctl directly we'll start the
2381 // pre-recovery service which will do some preparation for
2382 // recovery and then reboot for us.
2383 //
2384 // This preparation can take more than 20 seconds if
2385 // there's a very large update package, so lengthen the
2386 // timeout.
2387 SystemProperties.set("ctl.start", "pre-recovery");
2388 duration = 120 * 1000L;
2389 } else {
2390 SystemProperties.set("sys.powerctl", "reboot," + reason);
2391 duration = 20 * 1000L;
2392 }
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002393 try {
Doug Zongker3b0218b2014-01-14 12:29:06 -08002394 Thread.sleep(duration);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002395 } catch (InterruptedException e) {
2396 Thread.currentThread().interrupt();
2397 }
Jeff Brown96307042012-07-27 15:51:34 -07002398 }
2399
2400 @Override // Watchdog.Monitor implementation
2401 public void monitor() {
2402 // Grab and release lock for watchdog monitor to detect deadlocks.
2403 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002404 }
Jeff Brown96307042012-07-27 15:51:34 -07002405 }
2406
Jeff Brown6f357d32014-01-15 20:40:55 -08002407 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07002408 pw.println("POWER MANAGER (dumpsys power)\n");
2409
Jeff Brown3b971592013-01-09 18:46:37 -08002410 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07002411 synchronized (mLock) {
2412 pw.println("Power Manager State:");
2413 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
2414 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness));
Jeff Brown037c33e2014-04-09 00:31:55 -07002415 pw.println(" mInteractive=" + mInteractive);
Jeff Brown96307042012-07-27 15:51:34 -07002416 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07002417 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07002418 pw.println(" mBatteryLevel=" + mBatteryLevel);
2419 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07002420 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07002421 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07002422 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07002423 pw.println(" mBootCompleted=" + mBootCompleted);
2424 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07002425 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
2426 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07002427 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2428 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2429 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2430 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08002431 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07002432 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled);
2433 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07002434 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2435 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Jeff Brown96307042012-07-27 15:51:34 -07002436 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2437 pw.println(" mLastUserActivityTimeNoChangeLights="
2438 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07002439 pw.println(" mLastInteractivePowerHintTime="
2440 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07002441 pw.println(" mLastScreenBrightnessBoostTime="
2442 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
2443 pw.println(" mScreenBrightnessBoostInProgress="
2444 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07002445 pw.println(" mDisplayReady=" + mDisplayReady);
2446 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08002447 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07002448
2449 pw.println();
2450 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07002451 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
2452 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
2453 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
2454 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002455 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
2456 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07002457 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
2458 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
2459 pw.println(" mTheaterModeEnabled="
2460 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07002461 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
2462 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002463 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002464 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2465 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
2466 + mDreamsActivatedOnSleepByDefaultConfig);
2467 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
2468 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08002469 pw.println(" mDreamsEnabledOnBatteryConfig="
2470 + mDreamsEnabledOnBatteryConfig);
2471 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
2472 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2473 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2474 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2475 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
2476 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002477 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04002478 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07002479 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown2175e9c2014-09-12 16:11:07 -07002480 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig);
Dianne Hackborn14272302014-06-10 23:13:02 -07002481 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002482 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured);
John Spurlock1bb480a2014-08-02 17:12:43 -04002483 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing);
Jeff Brown27736f52014-05-20 17:17:10 -07002484 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
2485 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
2486 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002487 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07002488 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002489 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
2490 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2491 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2492 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2493 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
Jeff Brown330560f2012-08-21 22:10:57 -07002494 pw.println(" mScreenAutoBrightnessAdjustmentSetting="
2495 + mScreenAutoBrightnessAdjustmentSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002496 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2497 pw.println(" mScreenBrightnessOverrideFromWindowManager="
2498 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002499 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
2500 + mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown96307042012-07-27 15:51:34 -07002501 pw.println(" mTemporaryScreenBrightnessSettingOverride="
2502 + mTemporaryScreenBrightnessSettingOverride);
Jeff Brown330560f2012-08-21 22:10:57 -07002503 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2504 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
Jeff Brown970d4132014-07-19 11:33:47 -07002505 pw.println(" mDozeScreenStateOverrideFromDreamManager="
2506 + mDozeScreenStateOverrideFromDreamManager);
2507 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
2508 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07002509 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2510 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2511 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
2512
Jeff Brown05af6ad2014-09-30 20:54:30 -07002513 final int sleepTimeout = getSleepTimeoutLocked();
2514 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07002515 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2516 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07002517 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07002518 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
2519 pw.println("Screen dim duration: " + screenDimDuration + " ms");
2520
Jeff Brown96307042012-07-27 15:51:34 -07002521 pw.println();
2522 pw.println("Wake Locks: size=" + mWakeLocks.size());
2523 for (WakeLock wl : mWakeLocks) {
2524 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04002525 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002526
Jeff Brown96307042012-07-27 15:51:34 -07002527 pw.println();
2528 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
2529 for (SuspendBlocker sb : mSuspendBlockers) {
2530 pw.println(" " + sb);
2531 }
2532
Jeff Brownc38c9be2012-10-04 13:16:19 -07002533 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07002534 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07002535
Jeff Brown3b971592013-01-09 18:46:37 -08002536 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07002537 }
2538
Jeff Brown3b971592013-01-09 18:46:37 -08002539 if (wcd != null) {
2540 wcd.dump(pw);
2541 }
Jeff Brown96307042012-07-27 15:51:34 -07002542 }
2543
2544 private SuspendBlocker createSuspendBlockerLocked(String name) {
2545 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
2546 mSuspendBlockers.add(suspendBlocker);
2547 return suspendBlocker;
2548 }
2549
2550 private static String wakefulnessToString(int wakefulness) {
2551 switch (wakefulness) {
2552 case WAKEFULNESS_ASLEEP:
2553 return "Asleep";
2554 case WAKEFULNESS_AWAKE:
2555 return "Awake";
2556 case WAKEFULNESS_DREAMING:
2557 return "Dreaming";
Jeff Brown26875502014-01-30 21:47:47 -08002558 case WAKEFULNESS_DOZING:
2559 return "Dozing";
Jeff Brown96307042012-07-27 15:51:34 -07002560 default:
2561 return Integer.toString(wakefulness);
2562 }
2563 }
2564
2565 private static WorkSource copyWorkSource(WorkSource workSource) {
2566 return workSource != null ? new WorkSource(workSource) : null;
2567 }
2568
2569 private final class BatteryReceiver extends BroadcastReceiver {
2570 @Override
2571 public void onReceive(Context context, Intent intent) {
2572 synchronized (mLock) {
2573 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002574 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002575 }
2576 }
2577
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002578 private final class DreamReceiver extends BroadcastReceiver {
2579 @Override
2580 public void onReceive(Context context, Intent intent) {
2581 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002582 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002583 }
2584 }
2585 }
2586
Jeff Brownd4935962012-09-25 13:27:20 -07002587 private final class UserSwitchedReceiver extends BroadcastReceiver {
2588 @Override
2589 public void onReceive(Context context, Intent intent) {
2590 synchronized (mLock) {
2591 handleSettingsChangedLocked();
2592 }
2593 }
2594 }
2595
Jeff Brownec6aa592012-10-17 20:30:25 -07002596 private final class DockReceiver extends BroadcastReceiver {
2597 @Override
2598 public void onReceive(Context context, Intent intent) {
2599 synchronized (mLock) {
2600 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2601 Intent.EXTRA_DOCK_STATE_UNDOCKED);
2602 if (mDockState != dockState) {
2603 mDockState = dockState;
2604 mDirty |= DIRTY_DOCK_STATE;
2605 updatePowerStateLocked();
2606 }
2607 }
2608 }
2609 }
2610
Jeff Brown96307042012-07-27 15:51:34 -07002611 private final class SettingsObserver extends ContentObserver {
2612 public SettingsObserver(Handler handler) {
2613 super(handler);
2614 }
2615
2616 @Override
2617 public void onChange(boolean selfChange, Uri uri) {
2618 synchronized (mLock) {
2619 handleSettingsChangedLocked();
2620 }
2621 }
2622 }
2623
Jeff Brown96307042012-07-27 15:51:34 -07002624 /**
2625 * Handler for asynchronous operations performed by the power manager.
2626 */
2627 private final class PowerManagerHandler extends Handler {
2628 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07002629 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07002630 }
2631
2632 @Override
2633 public void handleMessage(Message msg) {
2634 switch (msg.what) {
2635 case MSG_USER_ACTIVITY_TIMEOUT:
2636 handleUserActivityTimeout();
2637 break;
2638 case MSG_SANDMAN:
2639 handleSandman();
2640 break;
Jeff Browne333e672014-10-28 13:48:55 -07002641 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
2642 handleScreenBrightnessBoostTimeout();
2643 break;
Jeff Brown96307042012-07-27 15:51:34 -07002644 }
2645 }
2646 }
2647
2648 /**
2649 * Represents a wake lock that has been acquired by an application.
2650 */
2651 private final class WakeLock implements IBinder.DeathRecipient {
2652 public final IBinder mLock;
2653 public int mFlags;
2654 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002655 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07002656 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002657 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002658 public final int mOwnerUid;
2659 public final int mOwnerPid;
2660 public boolean mNotifiedAcquired;
Jeff Brown96307042012-07-27 15:51:34 -07002661
Dianne Hackborn713df152013-05-17 11:27:57 -07002662 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002663 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Jeff Brown96307042012-07-27 15:51:34 -07002664 mLock = lock;
2665 mFlags = flags;
2666 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002667 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07002668 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002669 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07002670 mOwnerUid = ownerUid;
2671 mOwnerPid = ownerPid;
2672 }
2673
2674 @Override
2675 public void binderDied() {
2676 PowerManagerService.this.handleWakeLockDeath(this);
2677 }
2678
2679 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2680 int ownerUid, int ownerPid) {
2681 return mFlags == flags
2682 && mTag.equals(tag)
2683 && hasSameWorkSource(workSource)
2684 && mOwnerUid == ownerUid
2685 && mOwnerPid == ownerPid;
2686 }
2687
Dianne Hackborn713df152013-05-17 11:27:57 -07002688 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002689 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07002690 if (!mPackageName.equals(packageName)) {
2691 throw new IllegalStateException("Existing wake lock package name changed: "
2692 + mPackageName + " to " + packageName);
2693 }
2694 if (mOwnerUid != ownerUid) {
2695 throw new IllegalStateException("Existing wake lock uid changed: "
2696 + mOwnerUid + " to " + ownerUid);
2697 }
2698 if (mOwnerPid != ownerPid) {
2699 throw new IllegalStateException("Existing wake lock pid changed: "
2700 + mOwnerPid + " to " + ownerPid);
2701 }
Jeff Brown96307042012-07-27 15:51:34 -07002702 mFlags = flags;
2703 mTag = tag;
2704 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002705 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07002706 }
2707
2708 public boolean hasSameWorkSource(WorkSource workSource) {
2709 return Objects.equal(mWorkSource, workSource);
2710 }
2711
2712 public void updateWorkSource(WorkSource workSource) {
2713 mWorkSource = copyWorkSource(workSource);
2714 }
2715
2716 @Override
2717 public String toString() {
2718 return getLockLevelString()
2719 + " '" + mTag + "'" + getLockFlagsString()
2720 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2721 }
2722
Jeff Brown26875502014-01-30 21:47:47 -08002723 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07002724 private String getLockLevelString() {
2725 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2726 case PowerManager.FULL_WAKE_LOCK:
2727 return "FULL_WAKE_LOCK ";
2728 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2729 return "SCREEN_BRIGHT_WAKE_LOCK ";
2730 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2731 return "SCREEN_DIM_WAKE_LOCK ";
2732 case PowerManager.PARTIAL_WAKE_LOCK:
2733 return "PARTIAL_WAKE_LOCK ";
2734 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2735 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08002736 case PowerManager.DOZE_WAKE_LOCK:
2737 return "DOZE_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07002738 default:
2739 return "??? ";
2740 }
2741 }
2742
2743 private String getLockFlagsString() {
2744 String result = "";
2745 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2746 result += " ACQUIRE_CAUSES_WAKEUP";
2747 }
2748 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2749 result += " ON_AFTER_RELEASE";
2750 }
2751 return result;
2752 }
2753 }
2754
2755 private final class SuspendBlockerImpl implements SuspendBlocker {
2756 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07002757 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07002758 private int mReferenceCount;
2759
2760 public SuspendBlockerImpl(String name) {
2761 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07002762 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07002763 }
2764
2765 @Override
2766 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002767 try {
Jeff Brown96307042012-07-27 15:51:34 -07002768 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07002769 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07002770 + "\" was finalized without being released!");
2771 mReferenceCount = 0;
2772 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07002773 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002774 }
2775 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07002776 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002777 }
2778 }
2779
Craig Mautner75fc9de2012-06-18 16:53:27 -07002780 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002781 public void acquire() {
2782 synchronized (this) {
2783 mReferenceCount += 1;
2784 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002785 if (DEBUG_SPEW) {
2786 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2787 }
Jeff Brown3edf5272014-08-14 19:25:14 -07002788 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07002789 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07002790 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002791 }
2792 }
2793
Craig Mautner75fc9de2012-06-18 16:53:27 -07002794 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002795 public void release() {
2796 synchronized (this) {
2797 mReferenceCount -= 1;
2798 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002799 if (DEBUG_SPEW) {
2800 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2801 }
Jeff Brown96307042012-07-27 15:51:34 -07002802 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07002803 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07002804 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07002805 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07002806 + "\" was released without being acquired!", new Throwable());
2807 mReferenceCount = 0;
2808 }
2809 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002810 }
Jeff Brown96307042012-07-27 15:51:34 -07002811
2812 @Override
2813 public String toString() {
2814 synchronized (this) {
2815 return mName + ": ref count=" + mReferenceCount;
2816 }
2817 }
2818 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002819
Jeff Brown6f357d32014-01-15 20:40:55 -08002820 private final class BinderService extends IPowerManager.Stub {
2821 @Override // Binder call
2822 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2823 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07002824 if (uid < 0) {
2825 uid = Binder.getCallingUid();
2826 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002827 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08002828 }
2829
2830 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002831 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07002832 if (!mSystemReady) {
2833 // Service not ready yet, so who the heck cares about power hints, bah.
2834 return;
2835 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07002837 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002838 }
2839
2840 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08002841 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002842 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002843 if (lock == null) {
2844 throw new IllegalArgumentException("lock must not be null");
2845 }
2846 if (packageName == null) {
2847 throw new IllegalArgumentException("packageName must not be null");
2848 }
2849 PowerManager.validateWakeLockParameters(flags, tag);
2850
2851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07002852 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
2853 mContext.enforceCallingOrSelfPermission(
2854 android.Manifest.permission.DEVICE_POWER, null);
2855 }
Jeff Brown6f357d32014-01-15 20:40:55 -08002856 if (ws != null && ws.size() != 0) {
2857 mContext.enforceCallingOrSelfPermission(
2858 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2859 } else {
2860 ws = null;
2861 }
2862
2863 final int uid = Binder.getCallingUid();
2864 final int pid = Binder.getCallingPid();
2865 final long ident = Binder.clearCallingIdentity();
2866 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002867 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override // Binder call
2874 public void releaseWakeLock(IBinder lock, int flags) {
2875 if (lock == null) {
2876 throw new IllegalArgumentException("lock must not be null");
2877 }
2878
2879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2880
2881 final long ident = Binder.clearCallingIdentity();
2882 try {
2883 releaseWakeLockInternal(lock, flags);
2884 } finally {
2885 Binder.restoreCallingIdentity(ident);
2886 }
2887 }
2888
2889 @Override // Binder call
2890 public void updateWakeLockUids(IBinder lock, int[] uids) {
2891 WorkSource ws = null;
2892
2893 if (uids != null) {
2894 ws = new WorkSource();
2895 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2896 // one at a time?
2897 for (int i = 0; i < uids.length; i++) {
2898 ws.add(uids[i]);
2899 }
2900 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07002901 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08002902 }
2903
2904 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07002905 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002906 if (lock == null) {
2907 throw new IllegalArgumentException("lock must not be null");
2908 }
2909
2910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2911 if (ws != null && ws.size() != 0) {
2912 mContext.enforceCallingOrSelfPermission(
2913 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2914 } else {
2915 ws = null;
2916 }
2917
Dianne Hackbornd953c532014-08-16 18:17:38 -07002918 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002919 final long ident = Binder.clearCallingIdentity();
2920 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07002921 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002922 } finally {
2923 Binder.restoreCallingIdentity(ident);
2924 }
2925 }
2926
2927 @Override // Binder call
2928 public boolean isWakeLockLevelSupported(int level) {
2929 final long ident = Binder.clearCallingIdentity();
2930 try {
2931 return isWakeLockLevelSupportedInternal(level);
2932 } finally {
2933 Binder.restoreCallingIdentity(ident);
2934 }
2935 }
2936
2937 @Override // Binder call
2938 public void userActivity(long eventTime, int event, int flags) {
2939 final long now = SystemClock.uptimeMillis();
2940 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07002941 != PackageManager.PERMISSION_GRANTED
2942 && mContext.checkCallingOrSelfPermission(
2943 android.Manifest.permission.USER_ACTIVITY)
2944 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002945 // Once upon a time applications could call userActivity().
2946 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
2947 // request instead of throwing a SecurityException so we don't break old apps.
2948 synchronized (mLock) {
2949 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2950 mLastWarningAboutUserActivityPermission = now;
2951 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07002952 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
2953 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08002954 + " pid=" + Binder.getCallingPid()
2955 + " uid=" + Binder.getCallingUid());
2956 }
2957 }
2958 return;
2959 }
2960
2961 if (eventTime > SystemClock.uptimeMillis()) {
2962 throw new IllegalArgumentException("event time must not be in the future");
2963 }
2964
2965 final int uid = Binder.getCallingUid();
2966 final long ident = Binder.clearCallingIdentity();
2967 try {
2968 userActivityInternal(eventTime, event, flags, uid);
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
2974 @Override // Binder call
2975 public void wakeUp(long eventTime) {
2976 if (eventTime > SystemClock.uptimeMillis()) {
2977 throw new IllegalArgumentException("event time must not be in the future");
2978 }
2979
2980 mContext.enforceCallingOrSelfPermission(
2981 android.Manifest.permission.DEVICE_POWER, null);
2982
Jeff Brownc12035c2014-08-13 18:52:25 -07002983 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002984 final long ident = Binder.clearCallingIdentity();
2985 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07002986 wakeUpInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002987 } finally {
2988 Binder.restoreCallingIdentity(ident);
2989 }
2990 }
2991
2992 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07002993 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002994 if (eventTime > SystemClock.uptimeMillis()) {
2995 throw new IllegalArgumentException("event time must not be in the future");
2996 }
2997
2998 mContext.enforceCallingOrSelfPermission(
2999 android.Manifest.permission.DEVICE_POWER, null);
3000
Jeff Brownc12035c2014-08-13 18:52:25 -07003001 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003002 final long ident = Binder.clearCallingIdentity();
3003 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07003004 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003005 } finally {
3006 Binder.restoreCallingIdentity(ident);
3007 }
3008 }
3009
3010 @Override // Binder call
3011 public void nap(long eventTime) {
3012 if (eventTime > SystemClock.uptimeMillis()) {
3013 throw new IllegalArgumentException("event time must not be in the future");
3014 }
3015
3016 mContext.enforceCallingOrSelfPermission(
3017 android.Manifest.permission.DEVICE_POWER, null);
3018
Jeff Brownc12035c2014-08-13 18:52:25 -07003019 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08003020 final long ident = Binder.clearCallingIdentity();
3021 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07003022 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08003023 } finally {
3024 Binder.restoreCallingIdentity(ident);
3025 }
3026 }
3027
3028 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07003029 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08003030 final long ident = Binder.clearCallingIdentity();
3031 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07003032 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08003033 } finally {
3034 Binder.restoreCallingIdentity(ident);
3035 }
3036 }
3037
Dianne Hackborneb94fa72014-06-03 17:48:12 -07003038 @Override // Binder call
3039 public boolean isPowerSaveMode() {
3040 final long ident = Binder.clearCallingIdentity();
3041 try {
3042 return isLowPowerModeInternal();
3043 } finally {
3044 Binder.restoreCallingIdentity(ident);
3045 }
3046 }
3047
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003048 @Override // Binder call
3049 public boolean setPowerSaveMode(boolean mode) {
3050 mContext.enforceCallingOrSelfPermission(
3051 android.Manifest.permission.DEVICE_POWER, null);
3052 final long ident = Binder.clearCallingIdentity();
3053 try {
3054 return setLowPowerModeInternal(mode);
3055 } finally {
3056 Binder.restoreCallingIdentity(ident);
3057 }
3058 }
3059
Jeff Brown6f357d32014-01-15 20:40:55 -08003060 /**
3061 * Reboots the device.
3062 *
3063 * @param confirm If true, shows a reboot confirmation dialog.
3064 * @param reason The reason for the reboot, or null if none.
3065 * @param wait If true, this call waits for the reboot to complete and does not return.
3066 */
3067 @Override // Binder call
3068 public void reboot(boolean confirm, String reason, boolean wait) {
3069 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Doug Zongker3b0218b2014-01-14 12:29:06 -08003070 if (PowerManager.REBOOT_RECOVERY.equals(reason)) {
3071 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
3072 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003073
3074 final long ident = Binder.clearCallingIdentity();
3075 try {
3076 shutdownOrRebootInternal(false, confirm, reason, wait);
3077 } finally {
3078 Binder.restoreCallingIdentity(ident);
3079 }
3080 }
3081
3082 /**
3083 * Shuts down the device.
3084 *
3085 * @param confirm If true, shows a shutdown confirmation dialog.
3086 * @param wait If true, this call waits for the shutdown to complete and does not return.
3087 */
3088 @Override // Binder call
3089 public void shutdown(boolean confirm, boolean wait) {
3090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3091
3092 final long ident = Binder.clearCallingIdentity();
3093 try {
3094 shutdownOrRebootInternal(true, confirm, null, wait);
3095 } finally {
3096 Binder.restoreCallingIdentity(ident);
3097 }
3098 }
3099
3100 /**
3101 * Crash the runtime (causing a complete restart of the Android framework).
3102 * Requires REBOOT permission. Mostly for testing. Should not return.
3103 */
3104 @Override // Binder call
3105 public void crash(String message) {
3106 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3107
3108 final long ident = Binder.clearCallingIdentity();
3109 try {
3110 crashInternal(message);
3111 } finally {
3112 Binder.restoreCallingIdentity(ident);
3113 }
3114 }
3115
3116 /**
3117 * Set the setting that determines whether the device stays on when plugged in.
3118 * The argument is a bit string, with each bit specifying a power source that,
3119 * when the device is connected to that source, causes the device to stay on.
3120 * See {@link android.os.BatteryManager} for the list of power sources that
3121 * can be specified. Current values include
3122 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
3123 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
3124 *
3125 * Used by "adb shell svc power stayon ..."
3126 *
3127 * @param val an {@code int} containing the bits that specify which power sources
3128 * should cause the device to stay on.
3129 */
3130 @Override // Binder call
3131 public void setStayOnSetting(int val) {
3132 mContext.enforceCallingOrSelfPermission(
3133 android.Manifest.permission.WRITE_SETTINGS, null);
3134
3135 final long ident = Binder.clearCallingIdentity();
3136 try {
3137 setStayOnSettingInternal(val);
3138 } finally {
3139 Binder.restoreCallingIdentity(ident);
3140 }
3141 }
3142
3143 /**
3144 * Used by device administration to set the maximum screen off timeout.
3145 *
3146 * This method must only be called by the device administration policy manager.
3147 */
3148 @Override // Binder call
3149 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
3150 final long ident = Binder.clearCallingIdentity();
3151 try {
3152 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
3153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157
3158 /**
3159 * Used by the settings application and brightness control widgets to
3160 * temporarily override the current screen brightness setting so that the
3161 * user can observe the effect of an intended settings change without applying
3162 * it immediately.
3163 *
3164 * The override will be canceled when the setting value is next updated.
3165 *
3166 * @param brightness The overridden brightness.
3167 *
3168 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
3169 */
3170 @Override // Binder call
3171 public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
3172 mContext.enforceCallingOrSelfPermission(
3173 android.Manifest.permission.DEVICE_POWER, null);
3174
3175 final long ident = Binder.clearCallingIdentity();
3176 try {
3177 setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
3178 } finally {
3179 Binder.restoreCallingIdentity(ident);
3180 }
3181 }
3182
3183 /**
3184 * Used by the settings application and brightness control widgets to
3185 * temporarily override the current screen auto-brightness adjustment setting so that the
3186 * user can observe the effect of an intended settings change without applying
3187 * it immediately.
3188 *
3189 * The override will be canceled when the setting value is next updated.
3190 *
3191 * @param adj The overridden brightness, or Float.NaN to disable the override.
3192 *
Jeff Brown131206b2014-04-08 17:27:14 -07003193 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
Jeff Brown6f357d32014-01-15 20:40:55 -08003194 */
3195 @Override // Binder call
3196 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
3197 mContext.enforceCallingOrSelfPermission(
3198 android.Manifest.permission.DEVICE_POWER, null);
3199
3200 final long ident = Binder.clearCallingIdentity();
3201 try {
3202 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
3203 } finally {
3204 Binder.restoreCallingIdentity(ident);
3205 }
3206 }
3207
3208 /**
3209 * Used by the phone application to make the attention LED flash when ringing.
3210 */
3211 @Override // Binder call
3212 public void setAttentionLight(boolean on, int color) {
3213 mContext.enforceCallingOrSelfPermission(
3214 android.Manifest.permission.DEVICE_POWER, null);
3215
3216 final long ident = Binder.clearCallingIdentity();
3217 try {
3218 setAttentionLightInternal(on, color);
3219 } finally {
3220 Binder.restoreCallingIdentity(ident);
3221 }
3222 }
3223
3224 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07003225 public void boostScreenBrightness(long eventTime) {
3226 if (eventTime > SystemClock.uptimeMillis()) {
3227 throw new IllegalArgumentException("event time must not be in the future");
3228 }
3229
3230 mContext.enforceCallingOrSelfPermission(
3231 android.Manifest.permission.DEVICE_POWER, null);
3232
3233 final int uid = Binder.getCallingUid();
3234 final long ident = Binder.clearCallingIdentity();
3235 try {
3236 boostScreenBrightnessInternal(eventTime, uid);
3237 } finally {
3238 Binder.restoreCallingIdentity(ident);
3239 }
3240 }
3241
3242 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08003243 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3244 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
3245 != PackageManager.PERMISSION_GRANTED) {
3246 pw.println("Permission Denial: can't dump PowerManager from from pid="
3247 + Binder.getCallingPid()
3248 + ", uid=" + Binder.getCallingUid());
3249 return;
3250 }
3251
3252 final long ident = Binder.clearCallingIdentity();
3253 try {
3254 dumpInternal(pw);
3255 } finally {
3256 Binder.restoreCallingIdentity(ident);
3257 }
3258 }
3259 }
3260
Jeff Brown4ccb8232014-01-16 22:16:42 -08003261 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08003262 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003263 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
3264 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3265 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3266 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08003267 }
Jeff Brown970d4132014-07-19 11:33:47 -07003268 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08003269 }
3270
Jeff Brown6f357d32014-01-15 20:40:55 -08003271 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003272 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003273 // Do nothing.
3274 // Button lights are not currently supported in the new implementation.
Jeff Brown6f357d32014-01-15 20:40:55 -08003275 }
3276
Jeff Brown970d4132014-07-19 11:33:47 -07003277 @Override
3278 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
3279 switch (screenState) {
3280 case Display.STATE_UNKNOWN:
3281 case Display.STATE_OFF:
3282 case Display.STATE_DOZE:
3283 case Display.STATE_DOZE_SUSPEND:
3284 case Display.STATE_ON:
3285 break;
3286 default:
3287 screenState = Display.STATE_UNKNOWN;
3288 break;
3289 }
3290 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3291 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3292 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
3293 }
3294 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
3295 }
3296
Jeff Brown6f357d32014-01-15 20:40:55 -08003297 @Override
3298 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07003299 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08003300 }
3301
3302 @Override
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003303 public boolean getLowPowerModeEnabled() {
3304 synchronized (mLock) {
3305 return mLowPowerModeEnabled;
3306 }
3307 }
3308
3309 @Override
3310 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
3311 synchronized (mLock) {
3312 mLowPowerModeListeners.add(listener);
3313 }
3314 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316}