blob: c79a6d64121e2a2e05e2708dc4af1ee837dc42cf [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 Brownc38c9be2012-10-04 13:16:19 -070091 // Message: Sent when the screen on blocker is released.
92 private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 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 Brownc38c9be2012-10-04 13:16:19 -0700114 // Dirty bit: screen on blocker state became held or unheld
115 private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10;
Jeff Brownec6aa592012-10-17 20:30:25 -0700116 // Dirty bit: dock state changed
117 private static final int DIRTY_DOCK_STATE = 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Jeff Brown27736f52014-05-20 17:17:10 -0700150 // Default timeout in milliseconds. This is only used until the settings
151 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700152 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brownff532542012-10-02 21:18:04 -0700153
Jeff Brown0a571122014-08-21 21:50:43 -0700154 // Power hints defined in hardware/libhardware/include/hardware/power.h.
155 private static final int POWER_HINT_INTERACTION = 2;
156 private static final int POWER_HINT_LOW_POWER = 5;
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700157
Jeff Brownb880d882014-02-10 19:47:07 -0800158 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700159 private final ServiceThread mHandlerThread;
160 private final PowerManagerHandler mHandler;
161
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700163 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800164 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700165 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700166 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700167 private WindowManagerPolicy mPolicy;
168 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800169 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700170 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800171 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700173
Jeff Brown96307042012-07-27 15:51:34 -0700174 private final Object mLock = new Object();
175
176 // A bitfield that indicates what parts of the power state have
177 // changed and need to be recalculated.
178 private int mDirty;
179
180 // Indicates whether the device is awake or asleep or somewhere in between.
181 // This is distinct from the screen power state, which is managed separately.
182 private int mWakefulness;
183
Jeff Brown26875502014-01-30 21:47:47 -0800184 // True if the sandman has just been summoned for the first time since entering the
185 // dreaming or dozing state. Indicates whether a new dream should begin.
186 private boolean mSandmanSummoned;
187
Jeff Brown96307042012-07-27 15:51:34 -0700188 // True if MSG_SANDMAN has been scheduled.
189 private boolean mSandmanScheduled;
190
191 // Table of all suspend blockers.
192 // There should only be a few of these.
193 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
194
195 // Table of all wake locks acquired by applications.
196 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
197
198 // A bitfield that summarizes the state of all active wakelocks.
199 private int mWakeLockSummary;
200
Jeff Brown037c33e2014-04-09 00:31:55 -0700201 // True if the device is in an interactive state.
202 private boolean mInteractive;
203 private boolean mInteractiveChanging;
204
Jeff Brown96307042012-07-27 15:51:34 -0700205 // If true, instructs the display controller to wait for the proximity sensor to
206 // go negative before turning the screen on.
207 private boolean mRequestWaitForNegativeProximity;
208
209 // Timestamp of the last time the device was awoken or put to sleep.
210 private long mLastWakeTime;
211 private long mLastSleepTime;
212
Jeff Brown96307042012-07-27 15:51:34 -0700213 // Timestamp of the last call to user activity.
214 private long mLastUserActivityTime;
215 private long mLastUserActivityTimeNoChangeLights;
216
Jeff Brown0a571122014-08-21 21:50:43 -0700217 // Timestamp of last interactive power hint.
218 private long mLastInteractivePowerHintTime;
219
Jeff Brown96307042012-07-27 15:51:34 -0700220 // A bitfield that summarizes the effect of the user activity timer.
221 // A zero value indicates that the user activity timer has expired.
222 private int mUserActivitySummary;
223
224 // The desired display power state. The actual state may lag behind the
225 // requested because it is updated asynchronously by the display power controller.
226 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
227
Jeff Brown96307042012-07-27 15:51:34 -0700228 // True if the display power state has been fully applied, which means the display
229 // is actually on or actually off or whatever was requested.
230 private boolean mDisplayReady;
231
Jeff Brown27f7a862012-12-12 15:43:31 -0800232 // The suspend blocker used to keep the CPU alive when an application has acquired
233 // a wake lock.
234 private final SuspendBlocker mWakeLockSuspendBlocker;
235
236 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700237 private boolean mHoldingWakeLockSuspendBlocker;
238
Jeff Brown27f7a862012-12-12 15:43:31 -0800239 // The suspend blocker used to keep the CPU alive when the display is on, the
240 // display is getting ready or there is user activity (in which case the display
241 // must be on).
242 private final SuspendBlocker mDisplaySuspendBlocker;
243
244 // True if the display suspend blocker has been acquired.
245 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700246
Jeff Brownc38c9be2012-10-04 13:16:19 -0700247 // The screen on blocker used to keep the screen from turning on while the lock
248 // screen is coming up.
249 private final ScreenOnBlockerImpl mScreenOnBlocker;
250
Jeff Brown96307042012-07-27 15:51:34 -0700251 // True if systemReady() has been called.
252 private boolean mSystemReady;
253
254 // True if boot completed occurred. We keep the screen on until this happens.
255 private boolean mBootCompleted;
256
Jeff Brown26875502014-01-30 21:47:47 -0800257 // True if auto-suspend mode is enabled.
258 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700259 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800260
261 // True if interactive mode is enabled.
262 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700263 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800264
Jeff Brown96307042012-07-27 15:51:34 -0700265 // True if the device is plugged into a power source.
266 private boolean mIsPowered;
267
Jeff Brownf3fb8952012-10-02 20:57:05 -0700268 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
269 private int mPlugType;
270
Jeff Brown016ff142012-10-15 16:47:22 -0700271 // The current battery level percentage.
272 private int mBatteryLevel;
273
274 // The battery level percentage at the time the dream started.
275 // This is used to terminate a dream and go to sleep if the battery is
276 // draining faster than it is charging and the user activity timeout has expired.
277 private int mBatteryLevelWhenDreamStarted;
278
Jeff Brownec6aa592012-10-17 20:30:25 -0700279 // The current dock state.
280 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
281
Jeff Brown26875502014-01-30 21:47:47 -0800282 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700283 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800284
285 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700286 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800287
Jeff Brown96307042012-07-27 15:51:34 -0700288 // True if the device should wake up when plugged or unplugged.
289 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
290
Jeff Brownec083212013-09-11 20:45:25 -0700291 // True if the device should suspend when the screen is off due to proximity.
292 private boolean mSuspendWhenScreenOffDueToProximityConfig;
293
Jeff Brown96307042012-07-27 15:51:34 -0700294 // True if dreams are supported on this device.
295 private boolean mDreamsSupportedConfig;
296
John Spurlocked108f32012-10-18 16:49:24 -0400297 // Default value for dreams enabled
298 private boolean mDreamsEnabledByDefaultConfig;
299
300 // Default value for dreams activate-on-sleep
301 private boolean mDreamsActivatedOnSleepByDefaultConfig;
302
303 // Default value for dreams activate-on-dock
304 private boolean mDreamsActivatedOnDockByDefaultConfig;
305
Jeff Brown26875502014-01-30 21:47:47 -0800306 // True if dreams can run while not plugged in.
307 private boolean mDreamsEnabledOnBatteryConfig;
308
309 // Minimum battery level to allow dreaming when powered.
310 // Use -1 to disable this safety feature.
311 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
312
313 // Minimum battery level to allow dreaming when not powered.
314 // Use -1 to disable this safety feature.
315 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
316
317 // If the battery level drops by this percentage and the user activity timeout
318 // has expired, then assume the device is receiving insufficient current to charge
319 // effectively and terminate the dream. Use -1 to disable this safety feature.
320 private int mDreamsBatteryLevelDrainCutoffConfig;
321
Jeff Brown96307042012-07-27 15:51:34 -0700322 // True if dreams are enabled by the user.
323 private boolean mDreamsEnabledSetting;
324
John Spurlock1a868b72012-08-22 09:56:51 -0400325 // True if dreams should be activated on sleep.
326 private boolean mDreamsActivateOnSleepSetting;
327
Jeff Brownec6aa592012-10-17 20:30:25 -0700328 // True if dreams should be activated on dock.
329 private boolean mDreamsActivateOnDockSetting;
330
Jeff Brown2175e9c2014-09-12 16:11:07 -0700331 // True if doze should not be started until after the screen off transition.
332 private boolean mDozeAfterScreenOffConfig;
333
Jeff Brown27736f52014-05-20 17:17:10 -0700334 // The minimum screen off timeout, in milliseconds.
335 private int mMinimumScreenOffTimeoutConfig;
336
337 // The screen dim duration, in milliseconds.
338 // This is subtracted from the end of the screen off timeout so the
339 // minimum screen off timeout should be longer than this.
340 private int mMaximumScreenDimDurationConfig;
341
342 // The maximum screen dim time expressed as a ratio relative to the screen
343 // off timeout. If the screen off timeout is very short then we want the
344 // dim timeout to also be quite short so that most of the time is spent on.
345 // Otherwise the user won't get much screen on time before dimming occurs.
346 private float mMaximumScreenDimRatioConfig;
347
Jeff Brown96307042012-07-27 15:51:34 -0700348 // The screen off timeout setting value in milliseconds.
349 private int mScreenOffTimeoutSetting;
350
351 // The maximum allowable screen off timeout according to the device
352 // administration policy. Overrides other settings.
353 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
354
355 // The stay on while plugged in setting.
356 // A bitfield of battery conditions under which to make the screen stay on.
357 private int mStayOnWhilePluggedInSetting;
358
359 // True if the device should stay on.
360 private boolean mStayOn;
361
Jeff Brown93cbbb22012-10-04 13:18:36 -0700362 // True if the proximity sensor reads a positive result.
363 private boolean mProximityPositive;
364
Jeff Brown96307042012-07-27 15:51:34 -0700365 // Screen brightness setting limits.
366 private int mScreenBrightnessSettingMinimum;
367 private int mScreenBrightnessSettingMaximum;
368 private int mScreenBrightnessSettingDefault;
369
370 // The screen brightness setting, from 0 to 255.
371 // Use -1 if no value has been set.
372 private int mScreenBrightnessSetting;
373
Jeff Brown330560f2012-08-21 22:10:57 -0700374 // The screen auto-brightness adjustment setting, from -1 to 1.
375 // Use 0 if there is no adjustment.
376 private float mScreenAutoBrightnessAdjustmentSetting;
377
Jeff Brown96307042012-07-27 15:51:34 -0700378 // The screen brightness mode.
379 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
380 private int mScreenBrightnessModeSetting;
381
382 // The screen brightness setting override from the window manager
383 // to allow the current foreground activity to override the brightness.
384 // Use -1 to disable.
385 private int mScreenBrightnessOverrideFromWindowManager = -1;
386
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700387 // The user activity timeout override from the window manager
388 // to allow the current foreground activity to override the user activity timeout.
389 // Use -1 to disable.
390 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
391
Jeff Brown96307042012-07-27 15:51:34 -0700392 // The screen brightness setting override from the settings application
393 // to temporarily adjust the brightness until next updated,
394 // Use -1 to disable.
395 private int mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396
Jeff Brown330560f2012-08-21 22:10:57 -0700397 // The screen brightness adjustment setting override from the settings
398 // application to temporarily adjust the auto-brightness adjustment factor
399 // until next updated, in the range -1..1.
400 // Use NaN to disable.
401 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
402
Jeff Brown970d4132014-07-19 11:33:47 -0700403 // The screen state to use while dozing.
404 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
405
406 // The screen brightness to use while dozing.
407 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
408
Jeff Brown9ba8d782012-10-01 16:38:23 -0700409 // Time when we last logged a warning about calling userActivity() without permission.
410 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
411
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700412 // If true, the device is in low power mode.
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700413 private boolean mLowPowerModeEnabled;
414
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700415 // Current state of the low power mode setting.
416 private boolean mLowPowerModeSetting;
417
Dianne Hackborn14272302014-06-10 23:13:02 -0700418 // Current state of whether the settings are allowing auto low power mode.
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400419 private boolean mAutoLowPowerModeConfigured;
Dianne Hackborn14272302014-06-10 23:13:02 -0700420
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400421 // The user turned off low power mode below the trigger level
John Spurlock1bb480a2014-08-02 17:12:43 -0400422 private boolean mAutoLowPowerModeSnoozing;
423
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700424 // True if the battery level is currently considered low.
425 private boolean mBatteryLevelLow;
426
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700427 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners
428 = new ArrayList<PowerManagerInternal.LowPowerModeListener>();
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700429
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700430 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431
Jeff Brown96307042012-07-27 15:51:34 -0700432 private static native void nativeAcquireSuspendBlocker(String name);
433 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700434 private static native void nativeSetInteractive(boolean enable);
435 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700436 private static native void nativeSendPowerHint(int hintId, int data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437
Jeff Brownb880d882014-02-10 19:47:07 -0800438 public PowerManagerService(Context context) {
439 super(context);
440 mContext = context;
Jeff Brown2c43c332014-06-12 22:38:59 -0700441 mHandlerThread = new ServiceThread(TAG,
442 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
443 mHandlerThread.start();
444 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
445
Jeff Brown96307042012-07-27 15:51:34 -0700446 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800447 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
448 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
449 mDisplaySuspendBlocker.acquire();
450 mHoldingDisplaySuspendBlocker = true;
Jeff Brown037c33e2014-04-09 00:31:55 -0700451 mHalAutoSuspendModeEnabled = false;
452 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800453
Jeff Brownc38c9be2012-10-04 13:16:19 -0700454 mScreenOnBlocker = new ScreenOnBlockerImpl();
Jeff Brown96307042012-07-27 15:51:34 -0700455 mWakefulness = WAKEFULNESS_AWAKE;
Jeff Brown037c33e2014-04-09 00:31:55 -0700456 mInteractive = true;
Jeff Brown7304c342012-05-11 18:42:42 -0700457
Jeff Brown037c33e2014-04-09 00:31:55 -0700458 nativeInit();
459 nativeSetAutoSuspend(false);
460 nativeSetInteractive(true);
461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
463
Jeff Brown6f357d32014-01-15 20:40:55 -0800464 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800465 public void onStart() {
466 publishBinderService(Context.POWER_SERVICE, new BinderService());
467 publishLocalService(PowerManagerInternal.class, new LocalService());
Jeff Brown9e316a12012-10-08 19:17:06 -0700468
469 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800470 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700471 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800472
Jeff Brown6d2a9492014-08-07 19:06:49 -0700473 @Override
474 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700475 synchronized (mLock) {
476 if (phase == PHASE_BOOT_COMPLETED) {
477 final long now = SystemClock.uptimeMillis();
478 mBootCompleted = true;
479 mDirty |= DIRTY_BOOT_COMPLETED;
480 userActivityNoUpdateLocked(
481 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
482 updatePowerStateLocked();
483 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700484 }
485 }
486
Jeff Brown21392762014-06-13 19:00:36 -0700487 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700488 synchronized (mLock) {
489 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700490 mAppOps = appOps;
491 mDreamManager = getLocalService(DreamManagerInternal.class);
492 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
493 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700494 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495
Adam Lesinski182f73f2013-12-05 16:48:06 -0800496 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700497 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
498 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
499 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700501 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800502
Jeff Brownc38c9be2012-10-04 13:16:19 -0700503 // The notifier runs on the system server's main looper so as not to interfere
504 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700505 mBatteryStats = BatteryStatsService.getService();
Jeff Brownc38c9be2012-10-04 13:16:19 -0700506 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700507 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brownc38c9be2012-10-04 13:16:19 -0700508 mScreenOnBlocker, mPolicy);
509
Jeff Brown3b971592013-01-09 18:46:37 -0800510 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700511 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
512 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700513 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700514
515 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800516 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400517
Jeff Brown131206b2014-04-08 17:27:14 -0700518 // Initialize display power management.
519 mDisplayManagerInternal.initPowerManagement(
520 mDisplayPowerCallbacks, mHandler, sensorManager);
521
Jeff Brown96307042012-07-27 15:51:34 -0700522 // Register for broadcasts from other components of the system.
523 IntentFilter filter = new IntentFilter();
524 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700525 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Jeff Brownd4935962012-09-25 13:27:20 -0700526 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700527
Jeff Brown96307042012-07-27 15:51:34 -0700528 filter = new IntentFilter();
Dianne Hackbornbe87e2f2012-09-28 16:31:34 -0700529 filter.addAction(Intent.ACTION_DREAMING_STARTED);
530 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
Jeff Brownd4935962012-09-25 13:27:20 -0700531 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
532
533 filter = new IntentFilter();
534 filter.addAction(Intent.ACTION_USER_SWITCHED);
535 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
John Spurlockf4f6b4c2012-08-25 12:08:03 -0400536
Jeff Brownec6aa592012-10-17 20:30:25 -0700537 filter = new IntentFilter();
538 filter.addAction(Intent.ACTION_DOCK_EVENT);
539 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
540
Jeff Brown96307042012-07-27 15:51:34 -0700541 // Register for settings changes.
542 final ContentResolver resolver = mContext.getContentResolver();
543 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700544 Settings.Secure.SCREENSAVER_ENABLED),
545 false, mSettingsObserver, UserHandle.USER_ALL);
John Spurlock1a868b72012-08-22 09:56:51 -0400546 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700547 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
548 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brownec6aa592012-10-17 20:30:25 -0700549 resolver.registerContentObserver(Settings.Secure.getUriFor(
550 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
551 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700552 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700553 Settings.System.SCREEN_OFF_TIMEOUT),
554 false, mSettingsObserver, UserHandle.USER_ALL);
Christopher Tatead735322012-09-07 14:19:43 -0700555 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700556 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
557 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700558 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700559 Settings.System.SCREEN_BRIGHTNESS),
560 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700561 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700562 Settings.System.SCREEN_BRIGHTNESS_MODE),
563 false, mSettingsObserver, UserHandle.USER_ALL);
Adrian Roos6dee6052014-05-14 19:44:18 +0200564 resolver.registerContentObserver(Settings.System.getUriFor(
565 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
566 false, mSettingsObserver, UserHandle.USER_ALL);
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700567 resolver.registerContentObserver(Settings.Global.getUriFor(
568 Settings.Global.LOW_POWER_MODE),
569 false, mSettingsObserver, UserHandle.USER_ALL);
Dianne Hackborn14272302014-06-10 23:13:02 -0700570 resolver.registerContentObserver(Settings.Global.getUriFor(
571 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
572 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700573 // Go.
574 readConfigurationLocked();
575 updateSettingsLocked();
576 mDirty |= DIRTY_BATTERY_STATE;
577 updatePowerStateLocked();
578 }
579 }
580
581 private void readConfigurationLocked() {
582 final Resources resources = mContext.getResources();
583
Jeff Brown037c33e2014-04-09 00:31:55 -0700584 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800585 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700586 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800587 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700588 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700589 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Jeff Brownec083212013-09-11 20:45:25 -0700590 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
591 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700592 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400593 com.android.internal.R.bool.config_dreamsSupported);
594 mDreamsEnabledByDefaultConfig = resources.getBoolean(
595 com.android.internal.R.bool.config_dreamsEnabledByDefault);
596 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
597 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
598 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
599 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800600 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
601 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
602 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
603 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
604 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
605 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
606 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
607 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Jeff Brown2175e9c2014-09-12 16:11:07 -0700608 mDozeAfterScreenOffConfig = resources.getBoolean(
609 com.android.internal.R.bool.config_dozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -0700610 mMinimumScreenOffTimeoutConfig = resources.getInteger(
611 com.android.internal.R.integer.config_minimumScreenOffTimeout);
612 mMaximumScreenDimDurationConfig = resources.getInteger(
613 com.android.internal.R.integer.config_maximumScreenDimDuration);
614 mMaximumScreenDimRatioConfig = resources.getFraction(
615 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
617
Jeff Brown96307042012-07-27 15:51:34 -0700618 private void updateSettingsLocked() {
619 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700620
Jeff Brownd4935962012-09-25 13:27:20 -0700621 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400622 Settings.Secure.SCREENSAVER_ENABLED,
623 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700624 UserHandle.USER_CURRENT) != 0);
625 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400626 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
627 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700628 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700629 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400630 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
631 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700632 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700633 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
634 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
635 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700636 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700637 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Jeff Brown7304c342012-05-11 18:42:42 -0700638
Jeff Brown96307042012-07-27 15:51:34 -0700639 final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700640 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
641 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
642 UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700643 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
644 mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
Jeff Brown96307042012-07-27 15:51:34 -0700646
Jeff Brown330560f2012-08-21 22:10:57 -0700647 final float oldScreenAutoBrightnessAdjustmentSetting =
648 mScreenAutoBrightnessAdjustmentSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700649 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
650 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
651 UserHandle.USER_CURRENT);
Jeff Brown330560f2012-08-21 22:10:57 -0700652 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
Jeff Brown5d03a532012-08-22 13:22:02 -0700653 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
Jeff Brown330560f2012-08-21 22:10:57 -0700654 }
655
Jeff Brownd4935962012-09-25 13:27:20 -0700656 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700657 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700658 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700659
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700660 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver,
Ruchi Kandoi15aedf52014-05-09 19:57:51 -0700661 Settings.Global.LOW_POWER_MODE, 0) != 0;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400662 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver,
John Spurlock1bb480a2014-08-02 17:12:43 -0400663 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0;
Dianne Hackborn14272302014-06-10 23:13:02 -0700664 if (lowPowerModeEnabled != mLowPowerModeSetting
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400665 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) {
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700666 mLowPowerModeSetting = lowPowerModeEnabled;
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400667 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured;
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700668 updateLowPowerModeLocked();
669 }
670
671 mDirty |= DIRTY_SETTINGS;
672 }
673
674 void updateLowPowerModeLocked() {
John Spurlock1bb480a2014-08-02 17:12:43 -0400675 if (mIsPowered && mLowPowerModeSetting) {
676 if (DEBUG_SPEW) {
677 Slog.d(TAG, "updateLowPowerModeLocked: powered, turning setting off");
678 }
679 // Turn setting off if powered
680 Settings.Global.putInt(mContext.getContentResolver(),
681 Settings.Global.LOW_POWER_MODE, 0);
682 mLowPowerModeSetting = false;
John Spurlock1bb480a2014-08-02 17:12:43 -0400683 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -0400684 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured
685 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow;
686 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled;
687
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700688 if (mLowPowerModeEnabled != lowPowerModeEnabled) {
689 mLowPowerModeEnabled = lowPowerModeEnabled;
Jeff Brown0a571122014-08-21 21:50:43 -0700690 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700691 BackgroundThread.getHandler().post(new Runnable() {
692 @Override
693 public void run() {
John Spurlock1bb480a2014-08-02 17:12:43 -0400694 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING)
695 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled)
696 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
697 mContext.sendBroadcast(intent);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700698 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners;
699 synchronized (mLock) {
700 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>(
701 mLowPowerModeListeners);
702 }
703 for (int i=0; i<listeners.size(); i++) {
704 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled);
705 }
John Spurlock1bb480a2014-08-02 17:12:43 -0400706 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700707 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
708 mContext.sendBroadcast(intent);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700709 }
710 });
Ruchi Kandoi62b8a492014-04-17 18:01:40 -0700711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713
Jeff Brown96307042012-07-27 15:51:34 -0700714 private void handleSettingsChangedLocked() {
715 updateSettingsLocked();
716 updatePowerStateLocked();
717 }
718
Dianne Hackborn713df152013-05-17 11:27:57 -0700719 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800720 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700721 synchronized (mLock) {
722 if (DEBUG_SPEW) {
723 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
724 + ", flags=0x" + Integer.toHexString(flags)
725 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727
Jeff Brown96307042012-07-27 15:51:34 -0700728 WakeLock wakeLock;
729 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700730 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -0700731 if (index >= 0) {
732 wakeLock = mWakeLocks.get(index);
733 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
734 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800735 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
736 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800737 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700739 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 } else {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800741 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700742 try {
743 lock.linkToDeath(wakeLock, 0);
744 } catch (RemoteException ex) {
745 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
Jeff Brown96307042012-07-27 15:51:34 -0700747 mWakeLocks.add(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700748 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750
Jeff Brownc12035c2014-08-13 18:52:25 -0700751 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -0700752 mDirty |= DIRTY_WAKE_LOCKS;
753 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700754 if (notifyAcquire) {
755 // This needs to be done last so we are sure we have acquired the
756 // kernel wake lock. Otherwise we have a race where the system may
757 // go to sleep between the time we start the accounting in battery
758 // stats and when we actually get around to telling the kernel to
759 // stay awake.
760 notifyWakeLockAcquiredLocked(wakeLock);
761 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700762 }
763 }
764
Jeff Brownec083212013-09-11 20:45:25 -0700765 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -0800766 private static boolean isScreenLock(final WakeLock wakeLock) {
767 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
768 case PowerManager.FULL_WAKE_LOCK:
769 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
770 case PowerManager.SCREEN_DIM_WAKE_LOCK:
771 return true;
772 }
773 return false;
774 }
775
Jeff Brownc12035c2014-08-13 18:52:25 -0700776 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -0700777 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
778 && isScreenLock(wakeLock)) {
Jeff Brownc12035c2014-08-13 18:52:25 -0700779 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781 }
782
Jeff Brown96307042012-07-27 15:51:34 -0700783 private void releaseWakeLockInternal(IBinder lock, int flags) {
784 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -0700785 int index = findWakeLockIndexLocked(lock);
786 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800787 if (DEBUG_SPEW) {
788 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
789 + " [not found], flags=0x" + Integer.toHexString(flags));
790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 return;
792 }
Mike Lockwood3333fa42009-10-26 14:50:42 -0400793
Jeff Brown96307042012-07-27 15:51:34 -0700794 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800795 if (DEBUG_SPEW) {
796 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
797 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
798 }
799
Michael Wright1208e272014-09-08 19:57:50 -0700800 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -0700801 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 }
803
Jeff Brown3edf5272014-08-14 19:25:14 -0700804 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
805 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
807 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700808
Jeff Brown96307042012-07-27 15:51:34 -0700809 private void handleWakeLockDeath(WakeLock wakeLock) {
810 synchronized (mLock) {
811 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800812 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
813 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -0700814 }
815
816 int index = mWakeLocks.indexOf(wakeLock);
817 if (index < 0) {
818 return;
819 }
820
Jeff Brown3edf5272014-08-14 19:25:14 -0700821 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700822 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800824
Jeff Brown3edf5272014-08-14 19:25:14 -0700825 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
826 mWakeLocks.remove(index);
827 notifyWakeLockReleasedLocked(wakeLock);
828
829 applyWakeLockFlagsOnReleaseLocked(wakeLock);
830 mDirty |= DIRTY_WAKE_LOCKS;
831 updatePowerStateLocked();
832 }
833
Jeff Brown96307042012-07-27 15:51:34 -0700834 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700835 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
836 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700837 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
838 PowerManager.USER_ACTIVITY_EVENT_OTHER,
839 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
840 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
Dianne Hackbornd953c532014-08-16 18:17:38 -0700844 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
845 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -0700846 synchronized (mLock) {
847 int index = findWakeLockIndexLocked(lock);
848 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800849 if (DEBUG_SPEW) {
850 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
851 + " [not found], ws=" + ws);
852 }
Dianne Hackbornd953c532014-08-16 18:17:38 -0700853 throw new IllegalArgumentException("Wake lock not active: " + lock
854 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -0700855 }
856
857 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800858 if (DEBUG_SPEW) {
859 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
860 + " [" + wakeLock.mTag + "], ws=" + ws);
861 }
862
Jeff Brown96307042012-07-27 15:51:34 -0700863 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800864 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
865 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -0700866 ws, historyTag);
867 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -0700868 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -0700869 }
870 }
871 }
872
873 private int findWakeLockIndexLocked(IBinder lock) {
874 final int count = mWakeLocks.size();
875 for (int i = 0; i < count; i++) {
876 if (mWakeLocks.get(i).mLock == lock) {
877 return i;
878 }
879 }
880 return -1;
881 }
882
883 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
884 if (mSystemReady) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700885 wakeLock.mNotifiedAcquired = true;
886 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800887 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
888 wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -0700889 }
890 }
891
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800892 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
893 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
894 if (mSystemReady && wakeLock.mNotifiedAcquired) {
895 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
896 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
897 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
898 }
899 }
900
Jeff Brown96307042012-07-27 15:51:34 -0700901 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700902 if (mSystemReady && wakeLock.mNotifiedAcquired) {
903 wakeLock.mNotifiedAcquired = false;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700904 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
905 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
906 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -0700907 }
908 }
909
Jeff Brownec083212013-09-11 20:45:25 -0700910 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700911 private boolean isWakeLockLevelSupportedInternal(int level) {
912 synchronized (mLock) {
913 switch (level) {
914 case PowerManager.PARTIAL_WAKE_LOCK:
915 case PowerManager.SCREEN_DIM_WAKE_LOCK:
916 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
917 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -0800918 case PowerManager.DOZE_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700919 return true;
Jeff Brown96307042012-07-27 15:51:34 -0700920
921 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -0700922 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -0700923
924 default:
925 return false;
926 }
927 }
928 }
929
Jeff Brown96307042012-07-27 15:51:34 -0700930 // Called from native code.
931 private void userActivityFromNative(long eventTime, int event, int flags) {
932 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
933 }
934
935 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
936 synchronized (mLock) {
937 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
938 updatePowerStateLocked();
939 }
940 }
941 }
942
943 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
944 if (DEBUG_SPEW) {
945 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
946 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
947 + ", uid=" + uid);
948 }
949
950 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -0800951 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -0700952 return false;
953 }
954
Jeff Brown3edf5272014-08-14 19:25:14 -0700955 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
956 try {
Jeff Brown0a571122014-08-21 21:50:43 -0700957 if (eventTime > mLastInteractivePowerHintTime) {
958 powerHintInternal(POWER_HINT_INTERACTION, 0);
959 mLastInteractivePowerHintTime = eventTime;
960 }
961
Jeff Brown3edf5272014-08-14 19:25:14 -0700962 mNotifier.onUserActivity(event, uid);
Jeff Brown96307042012-07-27 15:51:34 -0700963
Jeff Brown0a571122014-08-21 21:50:43 -0700964 if (mWakefulness == WAKEFULNESS_ASLEEP
965 || mWakefulness == WAKEFULNESS_DOZING
966 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
967 return false;
968 }
969
Jeff Brown3edf5272014-08-14 19:25:14 -0700970 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
971 if (eventTime > mLastUserActivityTimeNoChangeLights
972 && eventTime > mLastUserActivityTime) {
973 mLastUserActivityTimeNoChangeLights = eventTime;
974 mDirty |= DIRTY_USER_ACTIVITY;
975 return true;
976 }
977 } else {
978 if (eventTime > mLastUserActivityTime) {
979 mLastUserActivityTime = eventTime;
980 mDirty |= DIRTY_USER_ACTIVITY;
981 return true;
982 }
Jeff Brown96307042012-07-27 15:51:34 -0700983 }
Jeff Brown3edf5272014-08-14 19:25:14 -0700984 } finally {
985 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700986 }
987 return false;
988 }
989
Jeff Brownc12035c2014-08-13 18:52:25 -0700990 private void wakeUpInternal(long eventTime, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -0700991 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -0700992 if (wakeUpNoUpdateLocked(eventTime, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -0700993 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700994 }
995 }
Jeff Brown96307042012-07-27 15:51:34 -0700996 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700997
Jeff Brownc12035c2014-08-13 18:52:25 -0700998 private boolean wakeUpNoUpdateLocked(long eventTime, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -0700999 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001000 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Joe Onorato60607a92010-10-23 14:49:30 -07001001 }
Jeff Brown96307042012-07-27 15:51:34 -07001002
1003 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1004 || !mBootCompleted || !mSystemReady) {
1005 return false;
1006 }
1007
Jeff Brown3edf5272014-08-14 19:25:14 -07001008 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1009 try {
1010 switch (mWakefulness) {
1011 case WAKEFULNESS_ASLEEP:
1012 Slog.i(TAG, "Waking up from sleep (uid " + uid +")...");
1013 break;
1014 case WAKEFULNESS_DREAMING:
1015 Slog.i(TAG, "Waking up from dream (uid " + uid +")...");
1016 break;
1017 case WAKEFULNESS_DOZING:
1018 Slog.i(TAG, "Waking up from dozing (uid " + uid +")...");
1019 break;
1020 }
1021
1022 mLastWakeTime = eventTime;
1023 mDirty |= DIRTY_WAKEFULNESS;
1024 mWakefulness = WAKEFULNESS_AWAKE;
1025 setInteractiveStateLocked(true, 0);
1026
1027 userActivityNoUpdateLocked(
1028 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
1029 } finally {
1030 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001031 }
Jeff Brown96307042012-07-27 15:51:34 -07001032 return true;
1033 }
1034
Jeff Brownc12035c2014-08-13 18:52:25 -07001035 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001036 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001037 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001038 updatePowerStateLocked();
1039 }
1040 }
1041 }
1042
Jeff Brown26875502014-01-30 21:47:47 -08001043 // This method is called goToSleep for historical reasons but we actually start
1044 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -07001045 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001046 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001047 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001048 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001049 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001050 }
1051
Jeff Brown26875502014-01-30 21:47:47 -08001052 if (eventTime < mLastWakeTime
1053 || mWakefulness == WAKEFULNESS_ASLEEP
1054 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001055 || !mBootCompleted || !mSystemReady) {
1056 return false;
1057 }
1058
Jeff Brown3edf5272014-08-14 19:25:14 -07001059 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1060 try {
1061 switch (reason) {
1062 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1063 Slog.i(TAG, "Going to sleep due to device administration policy "
1064 + "(uid " + uid +")...");
1065 break;
1066 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1067 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1068 break;
1069 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1070 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1071 break;
1072 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1073 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1074 break;
1075 case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1076 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1077 break;
1078 default:
1079 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1080 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
Jeff Brown96307042012-07-27 15:51:34 -07001081 break;
1082 }
Jeff Brown6d8fd272014-05-20 21:24:38 -07001083
Jeff Brown3edf5272014-08-14 19:25:14 -07001084 mLastSleepTime = eventTime;
1085 mDirty |= DIRTY_WAKEFULNESS;
1086 mWakefulness = WAKEFULNESS_DOZING;
1087 mSandmanSummoned = true;
1088 setInteractiveStateLocked(false, reason);
1089
1090 // Report the number of wake locks that will be cleared by going to sleep.
1091 int numWakeLocksCleared = 0;
1092 final int numWakeLocks = mWakeLocks.size();
1093 for (int i = 0; i < numWakeLocks; i++) {
1094 final WakeLock wakeLock = mWakeLocks.get(i);
1095 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1096 case PowerManager.FULL_WAKE_LOCK:
1097 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1098 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1099 numWakeLocksCleared += 1;
1100 break;
1101 }
1102 }
1103 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
1104
1105 // Skip dozing if requested.
1106 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1107 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1108 }
1109 } finally {
1110 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001111 }
Jeff Brown96307042012-07-27 15:51:34 -07001112 return true;
1113 }
1114
Jeff Brownc12035c2014-08-13 18:52:25 -07001115 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001116 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001117 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001118 updatePowerStateLocked();
1119 }
1120 }
1121 }
1122
Jeff Brownc12035c2014-08-13 18:52:25 -07001123 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001124 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001125 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001126 }
1127
1128 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1129 || !mBootCompleted || !mSystemReady) {
1130 return false;
1131 }
1132
Jeff Brown3edf5272014-08-14 19:25:14 -07001133 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1134 try {
1135 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001136
Jeff Brown3edf5272014-08-14 19:25:14 -07001137 mDirty |= DIRTY_WAKEFULNESS;
1138 mWakefulness = WAKEFULNESS_DREAMING;
1139 mSandmanSummoned = true;
1140 setInteractiveStateLocked(true, 0);
1141 } finally {
1142 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1143 }
Jeff Brown26875502014-01-30 21:47:47 -08001144 return true;
1145 }
1146
1147 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001148 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001149 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001150 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1151 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001152 }
1153
1154 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1155 || !mBootCompleted || !mSystemReady) {
1156 return false;
1157 }
1158
Jeff Brown3edf5272014-08-14 19:25:14 -07001159 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1160 try {
1161 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001162
Jeff Brown3edf5272014-08-14 19:25:14 -07001163 mDirty |= DIRTY_WAKEFULNESS;
1164 mWakefulness = WAKEFULNESS_ASLEEP;
1165 setInteractiveStateLocked(false, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1166 } finally {
1167 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1168 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001169 return true;
1170 }
1171
Jeff Brown037c33e2014-04-09 00:31:55 -07001172 private void setInteractiveStateLocked(boolean interactive, int reason) {
1173 if (mInteractive != interactive) {
1174 finishInteractiveStateChangeLocked();
1175
1176 mInteractive = interactive;
1177 mInteractiveChanging = true;
1178 mNotifier.onInteractiveStateChangeStarted(interactive, reason);
1179 }
1180 }
1181
1182 private void finishInteractiveStateChangeLocked() {
1183 if (mInteractiveChanging) {
1184 mNotifier.onInteractiveStateChangeFinished(mInteractive);
1185 mInteractiveChanging = false;
1186 }
1187 }
1188
Jeff Brown96307042012-07-27 15:51:34 -07001189 /**
1190 * Updates the global power state based on dirty bits recorded in mDirty.
1191 *
1192 * This is the main function that performs power state transitions.
1193 * We centralize them here so that we can recompute the power state completely
1194 * each time something important changes, and ensure that we do it the same
1195 * way each time. The point is to gather all of the transition logic here.
1196 */
1197 private void updatePowerStateLocked() {
1198 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001199 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001201 if (!Thread.holdsLock(mLock)) {
1202 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001204
Jeff Brown3edf5272014-08-14 19:25:14 -07001205 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1206 try {
1207 // Phase 0: Basic state updates.
1208 updateIsPoweredLocked(mDirty);
1209 updateStayOnLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210
Jeff Brown3edf5272014-08-14 19:25:14 -07001211 // Phase 1: Update wakefulness.
1212 // Loop because the wake lock and user activity computations are influenced
1213 // by changes in wakefulness.
1214 final long now = SystemClock.uptimeMillis();
1215 int dirtyPhase2 = 0;
1216 for (;;) {
1217 int dirtyPhase1 = mDirty;
1218 dirtyPhase2 |= dirtyPhase1;
1219 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001220
Jeff Brown3edf5272014-08-14 19:25:14 -07001221 updateWakeLockSummaryLocked(dirtyPhase1);
1222 updateUserActivitySummaryLocked(now, dirtyPhase1);
1223 if (!updateWakefulnessLocked(dirtyPhase1)) {
1224 break;
1225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001227
Jeff Brown2175e9c2014-09-12 16:11:07 -07001228 // Phase 2: Update display power state.
1229 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
Jeff Brown3edf5272014-08-14 19:25:14 -07001230
Jeff Brown2175e9c2014-09-12 16:11:07 -07001231 // Phase 3: Update dream state (depends on display ready signal).
1232 updateDreamLocked(dirtyPhase2, displayBecameReady);
1233
1234 // Phase 4: Send notifications, if needed.
Jeff Brown3edf5272014-08-14 19:25:14 -07001235 if (mDisplayReady) {
1236 finishInteractiveStateChangeLocked();
1237 }
1238
Jeff Brown2175e9c2014-09-12 16:11:07 -07001239 // Phase 5: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001240 // Because we might release the last suspend blocker here, we need to make sure
1241 // we finished everything else first!
1242 updateSuspendBlockerLocked();
1243 } finally {
1244 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
Jeff Brown96307042012-07-27 15:51:34 -07001246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001247
Jim Miller92e66dd2012-02-21 18:57:12 -08001248 /**
Jeff Brown96307042012-07-27 15:51:34 -07001249 * Updates the value of mIsPowered.
1250 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001251 */
Jeff Brown96307042012-07-27 15:51:34 -07001252 private void updateIsPoweredLocked(int dirty) {
1253 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001254 final boolean wasPowered = mIsPowered;
1255 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001256 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001257 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1258 mPlugType = mBatteryManagerInternal.getPlugType();
1259 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1260 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001261
Jeff Brown26875502014-01-30 21:47:47 -08001262 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001263 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001264 + ", mIsPowered=" + mIsPowered
1265 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001266 + ", mPlugType=" + mPlugType
1267 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001268 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001269
Jeff Brownf3fb8952012-10-02 20:57:05 -07001270 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001271 mDirty |= DIRTY_IS_POWERED;
1272
Jeff Brown3b971592013-01-09 18:46:37 -08001273 // Update wireless dock detection state.
1274 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1275 mIsPowered, mPlugType, mBatteryLevel);
1276
Jeff Brown96307042012-07-27 15:51:34 -07001277 // Treat plugging and unplugging the devices as a user activity.
1278 // Users find it disconcerting when they plug or unplug the device
1279 // and it shuts off right away.
1280 // Some devices also wake the device when plugged or unplugged because
1281 // they don't have a charging LED.
1282 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001283 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1284 dockedOnWirelessCharger)) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001285 wakeUpNoUpdateLocked(now, Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001286 }
1287 userActivityNoUpdateLocked(
1288 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001289
1290 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001291 // it can provide feedback to the user.
1292 if (dockedOnWirelessCharger) {
Jeff Brown84e27562012-12-07 13:56:34 -08001293 mNotifier.onWirelessChargingStarted();
1294 }
Jeff Brown96307042012-07-27 15:51:34 -07001295 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001296
Dianne Hackborn14272302014-06-10 23:13:02 -07001297 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) {
John Spurlock1bb480a2014-08-02 17:12:43 -04001298 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) {
1299 if (DEBUG_SPEW) {
1300 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze");
1301 }
1302 mAutoLowPowerModeSnoozing = false;
1303 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001304 updateLowPowerModeLocked();
1305 }
Jeff Brown96307042012-07-27 15:51:34 -07001306 }
1307 }
1308
Jeff Brown3b971592013-01-09 18:46:37 -08001309 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1310 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001311 // Don't wake when powered unless configured to do so.
1312 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1313 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001314 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001315
Jeff Brown3b971592013-01-09 18:46:37 -08001316 // Don't wake when undocked from wireless charger.
1317 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001318 if (wasPowered && !mIsPowered
1319 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1320 return false;
1321 }
Jeff Brown3b971592013-01-09 18:46:37 -08001322
1323 // Don't wake when docked on wireless charger unless we are certain of it.
1324 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001325 if (!wasPowered && mIsPowered
1326 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001327 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001328 return false;
1329 }
1330
1331 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001332 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001333 return false;
1334 }
1335
1336 // Otherwise wake up!
1337 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001338 }
1339
Jeff Brown96307042012-07-27 15:51:34 -07001340 /**
1341 * Updates the value of mStayOn.
1342 * Sets DIRTY_STAY_ON if a change occurred.
1343 */
1344 private void updateStayOnLocked(int dirty) {
1345 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001346 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001347 if (mStayOnWhilePluggedInSetting != 0
1348 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001349 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001350 } else {
1351 mStayOn = false;
1352 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001353
1354 if (mStayOn != wasStayOn) {
1355 mDirty |= DIRTY_STAY_ON;
1356 }
Jeff Brown96307042012-07-27 15:51:34 -07001357 }
1358 }
1359
1360 /**
1361 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1362 * Note that most wake-locks are ignored when the system is asleep.
1363 *
1364 * This function must have no other side-effects.
1365 */
Jeff Brownec083212013-09-11 20:45:25 -07001366 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001367 private void updateWakeLockSummaryLocked(int dirty) {
1368 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1369 mWakeLockSummary = 0;
1370
1371 final int numWakeLocks = mWakeLocks.size();
1372 for (int i = 0; i < numWakeLocks; i++) {
1373 final WakeLock wakeLock = mWakeLocks.get(i);
1374 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1375 case PowerManager.PARTIAL_WAKE_LOCK:
1376 mWakeLockSummary |= WAKE_LOCK_CPU;
1377 break;
1378 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001379 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001380 break;
1381 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001382 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001383 break;
1384 case PowerManager.SCREEN_DIM_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001385 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001386 break;
1387 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001388 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001389 break;
Jeff Brown26875502014-01-30 21:47:47 -08001390 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brown037c33e2014-04-09 00:31:55 -07001391 mWakeLockSummary |= WAKE_LOCK_DOZE;
Jeff Brown26875502014-01-30 21:47:47 -08001392 break;
Jeff Brown96307042012-07-27 15:51:34 -07001393 }
1394 }
1395
Jeff Brown037c33e2014-04-09 00:31:55 -07001396 // Cancel wake locks that make no sense based on the current state.
1397 if (mWakefulness != WAKEFULNESS_DOZING) {
1398 mWakeLockSummary &= ~WAKE_LOCK_DOZE;
1399 }
1400 if (mWakefulness == WAKEFULNESS_ASLEEP
1401 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1402 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1403 | WAKE_LOCK_BUTTON_BRIGHT);
1404 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1405 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1406 }
1407 }
1408
1409 // Infer implied wake locks where necessary based on the current state.
1410 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1411 if (mWakefulness == WAKEFULNESS_AWAKE) {
1412 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1413 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1414 mWakeLockSummary |= WAKE_LOCK_CPU;
1415 }
1416 }
1417
Jeff Brown96307042012-07-27 15:51:34 -07001418 if (DEBUG_SPEW) {
1419 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1420 + wakefulnessToString(mWakefulness)
1421 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1422 }
1423 }
1424 }
1425
1426 /**
1427 * Updates the value of mUserActivitySummary to summarize the user requested
1428 * state of the system such as whether the screen should be bright or dim.
1429 * Note that user activity is ignored when the system is asleep.
1430 *
1431 * This function must have no other side-effects.
1432 */
1433 private void updateUserActivitySummaryLocked(long now, int dirty) {
1434 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07001435 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
1436 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001437 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1438
1439 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001440 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07001441 || mWakefulness == WAKEFULNESS_DREAMING
1442 || mWakefulness == WAKEFULNESS_DOZING) {
Jeff Brown96307042012-07-27 15:51:34 -07001443 final int screenOffTimeout = getScreenOffTimeoutLocked();
Jeff Brownff532542012-10-02 21:18:04 -07001444 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07001445
1446 mUserActivitySummary = 0;
1447 if (mLastUserActivityTime >= mLastWakeTime) {
1448 nextTimeout = mLastUserActivityTime
1449 + screenOffTimeout - screenDimDuration;
1450 if (now < nextTimeout) {
1451 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
1452 } else {
1453 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1454 if (now < nextTimeout) {
1455 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
1456 }
1457 }
1458 }
1459 if (mUserActivitySummary == 0
1460 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1461 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07001462 if (now < nextTimeout) {
1463 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) {
1464 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
1465 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
1466 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
1467 }
Jeff Brown96307042012-07-27 15:51:34 -07001468 }
1469 }
1470 if (mUserActivitySummary != 0) {
1471 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1472 msg.setAsynchronous(true);
1473 mHandler.sendMessageAtTime(msg, nextTimeout);
1474 }
1475 } else {
1476 mUserActivitySummary = 0;
1477 }
1478
1479 if (DEBUG_SPEW) {
1480 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1481 + wakefulnessToString(mWakefulness)
1482 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1483 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1484 }
1485 }
1486 }
1487
1488 /**
1489 * Called when a user activity timeout has occurred.
1490 * Simply indicates that something about user activity has changed so that the new
1491 * state can be recomputed when the power state is updated.
1492 *
1493 * This function must have no other side-effects besides setting the dirty
1494 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
1495 */
1496 private void handleUserActivityTimeout() { // runs on handler thread
1497 synchronized (mLock) {
1498 if (DEBUG_SPEW) {
1499 Slog.d(TAG, "handleUserActivityTimeout");
1500 }
1501
1502 mDirty |= DIRTY_USER_ACTIVITY;
1503 updatePowerStateLocked();
1504 }
1505 }
1506
1507 private int getScreenOffTimeoutLocked() {
1508 int timeout = mScreenOffTimeoutSetting;
1509 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1510 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1511 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001512 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1513 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1514 }
Jeff Brown27736f52014-05-20 17:17:10 -07001515 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07001516 }
1517
Jeff Brownff532542012-10-02 21:18:04 -07001518 private int getScreenDimDurationLocked(int screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07001519 return Math.min(mMaximumScreenDimDurationConfig,
1520 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07001521 }
1522
1523 /**
1524 * Updates the wakefulness of the device.
1525 *
Jeff Brown26875502014-01-30 21:47:47 -08001526 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07001527 * based on the current wake locks and user activity state. It may modify mDirty
1528 * if the wakefulness changes.
1529 *
1530 * Returns true if the wakefulness changed and we need to restart power state calculation.
1531 */
1532 private boolean updateWakefulnessLocked(int dirty) {
1533 boolean changed = false;
1534 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07001535 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1536 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001537 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1538 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001539 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07001540 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001541 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07001542 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001543 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001544 } else {
1545 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07001546 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07001547 }
Jeff Brown96307042012-07-27 15:51:34 -07001548 }
1549 }
1550 return changed;
1551 }
1552
Jeff Brown645832d2012-10-03 14:57:03 -07001553 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07001554 * Returns true if the device should automatically nap and start dreaming when the user
1555 * activity timeout has expired and it's bedtime.
1556 */
1557 private boolean shouldNapAtBedTimeLocked() {
1558 return mDreamsActivateOnSleepSetting
1559 || (mDreamsActivateOnDockSetting
1560 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1561 }
1562
1563 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001564 * Returns true if the device should go to sleep now.
1565 * Also used when exiting a dream to determine whether we should go back
1566 * to being fully awake or else go to sleep for good.
1567 */
Jeff Brown96307042012-07-27 15:51:34 -07001568 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001569 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07001570 }
1571
1572 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07001573 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07001574 * or the stay on while powered setting. We also keep the phone awake when
1575 * the proximity sensor returns a positive result so that the device does not
1576 * lock while in a phone call. This function only controls whether the device
1577 * will go to sleep or dream which is independent of whether it will be allowed
1578 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07001579 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07001580 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001581 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07001582 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07001583 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07001584 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1585 | USER_ACTIVITY_SCREEN_DIM)) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07001586 }
1587
1588 /**
1589 * Determines whether to post a message to the sandman to update the dream state.
1590 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07001591 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001592 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07001593 | DIRTY_USER_ACTIVITY
1594 | DIRTY_WAKE_LOCKS
1595 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001596 | DIRTY_SETTINGS
1597 | DIRTY_IS_POWERED
1598 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07001599 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07001600 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
1601 if (mDisplayReady) {
1602 scheduleSandmanLocked();
1603 }
Jeff Brown96307042012-07-27 15:51:34 -07001604 }
1605 }
1606
1607 private void scheduleSandmanLocked() {
1608 if (!mSandmanScheduled) {
1609 mSandmanScheduled = true;
1610 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1611 msg.setAsynchronous(true);
1612 mHandler.sendMessage(msg);
1613 }
1614 }
1615
1616 /**
Jeff Brown26875502014-01-30 21:47:47 -08001617 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07001618 *
1619 * We do this asynchronously because we must call out of the power manager to start
1620 * the dream and we don't want to hold our lock while doing so. There is a risk that
1621 * the device will wake or go to sleep in the meantime so we have to handle that case.
1622 */
1623 private void handleSandman() { // runs on handler thread
1624 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08001625 final boolean startDreaming;
1626 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07001627 synchronized (mLock) {
1628 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08001629 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07001630 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown26875502014-01-30 21:47:47 -08001631 startDreaming = ((wakefulness == WAKEFULNESS_DREAMING && canDreamLocked())
1632 || wakefulness == WAKEFULNESS_DOZING);
1633 mSandmanSummoned = false;
1634 } else {
1635 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001636 }
1637 }
1638
Jeff Brown96307042012-07-27 15:51:34 -07001639 // Start dreaming if needed.
1640 // We only control the dream on the handler thread, so we don't need to worry about
1641 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08001642 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07001643 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08001644 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07001645 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07001646 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08001647 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07001648 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001649 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08001650 } else {
1651 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001652 }
1653
1654 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07001655 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08001656 // Remember the initial battery level when the dream started.
1657 if (startDreaming && isDreaming) {
1658 mBatteryLevelWhenDreamStarted = mBatteryLevel;
1659 if (wakefulness == WAKEFULNESS_DOZING) {
1660 Slog.i(TAG, "Dozing...");
1661 } else {
1662 Slog.i(TAG, "Dreaming...");
1663 }
1664 }
1665
1666 // If preconditions changed, wait for the next iteration to determine
1667 // whether the dream should continue (or be restarted).
1668 if (mSandmanSummoned || mWakefulness != wakefulness) {
1669 return; // wait for next cycle
1670 }
1671
1672 // Determine whether the dream should continue.
1673 if (wakefulness == WAKEFULNESS_DREAMING) {
1674 if (isDreaming && canDreamLocked()) {
1675 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07001676 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08001677 - mDreamsBatteryLevelDrainCutoffConfig
1678 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07001679 // If the user activity timeout expired and the battery appears
1680 // to be draining faster than it is charging then stop dreaming
1681 // and go to sleep.
1682 Slog.i(TAG, "Stopping dream because the battery appears to "
1683 + "be draining faster than it is charging. "
1684 + "Battery level when dream started: "
1685 + mBatteryLevelWhenDreamStarted + "%. "
1686 + "Battery level now: " + mBatteryLevel + "%.");
1687 } else {
Jeff Brown26875502014-01-30 21:47:47 -08001688 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07001689 }
Jeff Brown96307042012-07-27 15:51:34 -07001690 }
Jeff Brown26875502014-01-30 21:47:47 -08001691
1692 // Dream has ended or will be stopped. Update the power state.
1693 if (isItBedTimeYetLocked()) {
1694 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07001695 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001696 updatePowerStateLocked();
1697 } else {
Jeff Brownc12035c2014-08-13 18:52:25 -07001698 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001699 updatePowerStateLocked();
1700 }
1701 } else if (wakefulness == WAKEFULNESS_DOZING) {
1702 if (isDreaming) {
1703 return; // continue dozing
1704 }
1705
1706 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07001707 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08001708 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001709 }
Jeff Brown96307042012-07-27 15:51:34 -07001710 }
1711
Jeff Brown26875502014-01-30 21:47:47 -08001712 // Stop dream.
1713 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07001714 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07001715 }
1716 }
1717
1718 /**
Jeff Brown26875502014-01-30 21:47:47 -08001719 * Returns true if the device is allowed to dream in its current state.
1720 * This function is not called when dozing.
Jeff Brown96307042012-07-27 15:51:34 -07001721 */
1722 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08001723 if (mWakefulness != WAKEFULNESS_DREAMING
1724 || !mDreamsSupportedConfig
1725 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07001726 || !mDisplayPowerRequest.isBrightOrDim()
Jeff Brown26875502014-01-30 21:47:47 -08001727 || !mBootCompleted) {
1728 return false;
1729 }
1730 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08001731 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08001732 return false;
1733 }
1734 if (!mIsPowered
1735 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
1736 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
1737 return false;
1738 }
1739 if (mIsPowered
1740 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
1741 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
1742 return false;
Jeff Brown96307042012-07-27 15:51:34 -07001743 }
1744 }
Jeff Brown26875502014-01-30 21:47:47 -08001745 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001746 }
1747
Jeff Brownc38c9be2012-10-04 13:16:19 -07001748 private void handleScreenOnBlockerReleased() {
1749 synchronized (mLock) {
1750 mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
1751 updatePowerStateLocked();
1752 }
1753 }
1754
Jeff Brown96307042012-07-27 15:51:34 -07001755 /**
1756 * Updates the display power state asynchronously.
1757 * When the update is finished, mDisplayReady will be set to true. The display
1758 * controller posts a message to tell us when the actual display power state
1759 * has been updated so we come back here to double-check and finish up.
1760 *
1761 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07001762 *
1763 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07001764 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07001765 private boolean updateDisplayPowerStateLocked(int dirty) {
1766 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07001767 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1768 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Jeff Brownc38c9be2012-10-04 13:16:19 -07001769 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07001770 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001771
1772 int screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001773 float screenAutoBrightnessAdjustment = 0.0f;
Jeff Brown96307042012-07-27 15:51:34 -07001774 boolean autoBrightness = (mScreenBrightnessModeSetting ==
1775 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1776 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1777 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1778 autoBrightness = false;
1779 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1780 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1781 } else if (isValidBrightness(mScreenBrightnessSetting)) {
Jeff Brown330560f2012-08-21 22:10:57 -07001782 screenBrightness = mScreenBrightnessSetting;
Jeff Brown96307042012-07-27 15:51:34 -07001783 }
1784 if (autoBrightness) {
1785 screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001786 if (isValidAutoBrightnessAdjustment(
1787 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1788 screenAutoBrightnessAdjustment =
1789 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1790 } else if (isValidAutoBrightnessAdjustment(
1791 mScreenAutoBrightnessAdjustmentSetting)) {
1792 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1793 }
Jeff Brown96307042012-07-27 15:51:34 -07001794 }
1795 screenBrightness = Math.max(Math.min(screenBrightness,
1796 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
Jeff Brown330560f2012-08-21 22:10:57 -07001797 screenAutoBrightnessAdjustment = Math.max(Math.min(
1798 screenAutoBrightnessAdjustment, 1.0f), -1.0f);
Jeff Brown96307042012-07-27 15:51:34 -07001799 mDisplayPowerRequest.screenBrightness = screenBrightness;
Jeff Brown330560f2012-08-21 22:10:57 -07001800 mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1801 screenAutoBrightnessAdjustment;
Jeff Brown96307042012-07-27 15:51:34 -07001802 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
1803
1804 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
1805
Jeff Brownc38c9be2012-10-04 13:16:19 -07001806 mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
1807
Ruchi Kandoif974cc82014-05-01 11:25:10 -07001808 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled;
1809
Jeff Brown970d4132014-07-19 11:33:47 -07001810 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
1811 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
1812 mDisplayPowerRequest.dozeScreenBrightness =
1813 mDozeScreenBrightnessOverrideFromDreamManager;
1814 } else {
1815 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
1816 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
1817 }
1818
Jeff Brown131206b2014-04-08 17:27:14 -07001819 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown96307042012-07-27 15:51:34 -07001820 mRequestWaitForNegativeProximity);
1821 mRequestWaitForNegativeProximity = false;
1822
1823 if (DEBUG_SPEW) {
Jeff Brownc38c9be2012-10-04 13:16:19 -07001824 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07001825 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07001826 + ", mWakefulness=" + mWakefulness
1827 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1828 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1829 + ", mBootCompleted=" + mBootCompleted);
1830 }
1831 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07001832 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07001833 }
1834
1835 private static boolean isValidBrightness(int value) {
1836 return value >= 0 && value <= 255;
1837 }
1838
Jeff Brown330560f2012-08-21 22:10:57 -07001839 private static boolean isValidAutoBrightnessAdjustment(float value) {
Jeff Brown5d03a532012-08-22 13:22:02 -07001840 // Handles NaN by always returning false.
1841 return value >= -1.0f && value <= 1.0f;
Jeff Brown330560f2012-08-21 22:10:57 -07001842 }
1843
Jeff Brown970d4132014-07-19 11:33:47 -07001844 private int getDesiredScreenPolicyLocked() {
Jeff Brown96307042012-07-27 15:51:34 -07001845 if (mWakefulness == WAKEFULNESS_ASLEEP) {
Jeff Brown970d4132014-07-19 11:33:47 -07001846 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001847 }
1848
Jeff Brown2175e9c2014-09-12 16:11:07 -07001849 if (mWakefulness == WAKEFULNESS_DOZING) {
1850 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1851 return DisplayPowerRequest.POLICY_DOZE;
1852 }
1853 if (mDozeAfterScreenOffConfig) {
1854 return DisplayPowerRequest.POLICY_OFF;
1855 }
1856 // Fall through and preserve the current screen policy if not configured to
1857 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08001858 }
1859
Jeff Brown96307042012-07-27 15:51:34 -07001860 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1861 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1862 || !mBootCompleted) {
Jeff Brown970d4132014-07-19 11:33:47 -07001863 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001864 }
1865
Jeff Brown970d4132014-07-19 11:33:47 -07001866 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001867 }
1868
Jeff Brown131206b2014-04-08 17:27:14 -07001869 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
1870 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07001871 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07001872
Jeff Brown96307042012-07-27 15:51:34 -07001873 @Override
1874 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001875 synchronized (mLock) {
1876 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1877 updatePowerStateLocked();
1878 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001879 }
1880
1881 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07001882 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001883 synchronized (mLock) {
1884 mProximityPositive = true;
1885 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1886 updatePowerStateLocked();
1887 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001888 }
1889
1890 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001891 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001892 synchronized (mLock) {
1893 mProximityPositive = false;
1894 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1895 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1896 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1897 updatePowerStateLocked();
1898 }
Jeff Brown96307042012-07-27 15:51:34 -07001899 }
Jeff Brown131206b2014-04-08 17:27:14 -07001900
1901 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07001902 public void onDisplayStateChange(int state) {
1903 // This method is only needed to support legacy display blanking behavior
1904 // where the display's power state is coupled to suspend or to the power HAL.
1905 // The order of operations matters here.
1906 synchronized (mLock) {
1907 if (mDisplayState != state) {
1908 mDisplayState = state;
1909 if (state == Display.STATE_OFF) {
1910 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
1911 setHalInteractiveModeLocked(false);
1912 }
1913 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1914 setHalAutoSuspendModeLocked(true);
1915 }
1916 } else {
1917 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1918 setHalAutoSuspendModeLocked(false);
1919 }
1920 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
1921 setHalInteractiveModeLocked(true);
1922 }
1923 }
1924 }
1925 }
1926 }
1927
1928 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07001929 public void acquireSuspendBlocker() {
1930 mDisplaySuspendBlocker.acquire();
1931 }
1932
1933 @Override
1934 public void releaseSuspendBlocker() {
1935 mDisplaySuspendBlocker.release();
1936 }
1937
1938 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07001939 public String toString() {
1940 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07001941 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07001942 }
1943 }
Jeff Brown96307042012-07-27 15:51:34 -07001944 };
Jim Miller92e66dd2012-02-21 18:57:12 -08001945
Jeff Brown96307042012-07-27 15:51:34 -07001946 private boolean shouldUseProximitySensorLocked() {
1947 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
1948 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001949
Jeff Brown96307042012-07-27 15:51:34 -07001950 /**
1951 * Updates the suspend blocker that keeps the CPU alive.
1952 *
1953 * This function must have no other side-effects.
1954 */
1955 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07001956 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08001957 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
1958 final boolean autoSuspend = !needDisplaySuspendBlocker;
1959
1960 // Disable auto-suspend if needed.
1961 if (!autoSuspend) {
Jeff Brown037c33e2014-04-09 00:31:55 -07001962 if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1963 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08001964 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001965 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
1966 setHalInteractiveModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08001967 }
1968 }
Jeff Brown27f7a862012-12-12 15:43:31 -08001969
1970 // First acquire suspend blockers if needed.
1971 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
1972 mWakeLockSuspendBlocker.acquire();
1973 mHoldingWakeLockSuspendBlocker = true;
1974 }
1975 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
1976 mDisplaySuspendBlocker.acquire();
1977 mHoldingDisplaySuspendBlocker = true;
1978 }
1979
1980 // Then release suspend blockers if needed.
1981 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
1982 mWakeLockSuspendBlocker.release();
1983 mHoldingWakeLockSuspendBlocker = false;
1984 }
1985 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
1986 mDisplaySuspendBlocker.release();
1987 mHoldingDisplaySuspendBlocker = false;
1988 }
Jeff Brown26875502014-01-30 21:47:47 -08001989
1990 // Enable auto-suspend if needed.
1991 if (autoSuspend) {
Jeff Brown037c33e2014-04-09 00:31:55 -07001992 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
1993 setHalInteractiveModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08001994 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001995 if (mDecoupleHalAutoSuspendModeFromDisplayConfig) {
1996 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08001997 }
1998 }
Jeff Brown96307042012-07-27 15:51:34 -07001999 }
2000
Jeff Brownec083212013-09-11 20:45:25 -07002001 /**
2002 * Return true if we must keep a suspend blocker active on behalf of the display.
2003 * We do so if the screen is on or is in transition between states.
2004 */
Jeff Brown26875502014-01-30 21:47:47 -08002005 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002006 if (!mDisplayReady) {
2007 return true;
2008 }
Jeff Brown970d4132014-07-19 11:33:47 -07002009 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002010 // If we asked for the screen to be on but it is off due to the proximity
2011 // sensor then we may suspend but only if the configuration allows it.
2012 // On some hardware it may not be safe to suspend because the proximity
2013 // sensor may not be correctly configured as a wake-up source.
2014 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2015 || !mSuspendWhenScreenOffDueToProximityConfig) {
2016 return true;
2017 }
2018 }
Jeff Brown26875502014-01-30 21:47:47 -08002019 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002020 return false;
2021 }
2022
Jeff Brown037c33e2014-04-09 00:31:55 -07002023 private void setHalAutoSuspendModeLocked(boolean enable) {
2024 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002025 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002026 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002027 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002028 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002029 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2030 try {
2031 nativeSetAutoSuspend(enable);
2032 } finally {
2033 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2034 }
Jeff Brown26875502014-01-30 21:47:47 -08002035 }
2036 }
2037
Jeff Brown037c33e2014-04-09 00:31:55 -07002038 private void setHalInteractiveModeLocked(boolean enable) {
2039 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002040 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002041 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002042 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002043 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002044 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2045 try {
2046 nativeSetInteractive(enable);
2047 } finally {
2048 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2049 }
Jeff Brown26875502014-01-30 21:47:47 -08002050 }
2051 }
2052
Jeff Brown037c33e2014-04-09 00:31:55 -07002053 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002054 synchronized (mLock) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002055 return mInteractive;
Mike Lockwoodb2865412010-02-02 22:40:33 -05002056 }
2057 }
2058
Dianne Hackborneb94fa72014-06-03 17:48:12 -07002059 private boolean isLowPowerModeInternal() {
2060 synchronized (mLock) {
2061 return mLowPowerModeEnabled;
2062 }
2063 }
2064
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002065 private boolean setLowPowerModeInternal(boolean mode) {
2066 synchronized (mLock) {
2067 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered);
2068 if (mIsPowered) {
2069 return false;
2070 }
2071 Settings.Global.putInt(mContext.getContentResolver(),
2072 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0);
2073 mLowPowerModeSetting = mode;
2074
2075 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) {
2076 if (mode && mAutoLowPowerModeSnoozing) {
2077 if (DEBUG_SPEW) {
2078 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze");
2079 }
2080 mAutoLowPowerModeSnoozing = false;
2081 } else if (!mode && !mAutoLowPowerModeSnoozing) {
2082 if (DEBUG_SPEW) {
2083 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode");
2084 }
2085 mAutoLowPowerModeSnoozing = true;
2086 }
2087 }
2088
2089 updateLowPowerModeLocked();
2090 return true;
2091 }
2092 }
2093
Jeff Brown96307042012-07-27 15:51:34 -07002094 private void handleBatteryStateChangedLocked() {
2095 mDirty |= DIRTY_BATTERY_STATE;
2096 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002097 }
2098
Jeff Brownab887a02012-10-15 16:00:40 -07002099 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002100 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002101 if (mHandler == null || !mSystemReady) {
Jeff Brownab887a02012-10-15 16:00:40 -07002102 throw new IllegalStateException("Too early to call shutdown() or reboot()");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002103 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002104
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002105 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002106 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002107 public void run() {
2108 synchronized (this) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002109 if (shutdown) {
2110 ShutdownThread.shutdown(mContext, confirm);
2111 } else {
2112 ShutdownThread.reboot(mContext, reason, confirm);
2113 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002114 }
San Mehat1e512792010-01-07 10:40:29 -08002115 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002116 };
Jeff Brown96307042012-07-27 15:51:34 -07002117
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002118 // ShutdownThread must run on a looper capable of displaying the UI.
Jeff Brown96307042012-07-27 15:51:34 -07002119 Message msg = Message.obtain(mHandler, runnable);
2120 msg.setAsynchronous(true);
2121 mHandler.sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002122
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002123 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002124 if (wait) {
2125 synchronized (runnable) {
2126 while (true) {
2127 try {
2128 runnable.wait();
2129 } catch (InterruptedException e) {
2130 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002131 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002132 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002133 }
2134 }
2135
Jeff Brown96307042012-07-27 15:51:34 -07002136 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002137 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002138 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002139 public void run() {
2140 throw new RuntimeException(message);
2141 }
Dan Egnor60d87622009-12-16 16:32:58 -08002142 };
2143 try {
2144 t.start();
2145 t.join();
2146 } catch (InterruptedException e) {
2147 Log.wtf(TAG, e);
2148 }
2149 }
2150
Jeff Brown96307042012-07-27 15:51:34 -07002151 private void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002152 Settings.Global.putInt(mContext.getContentResolver(),
2153 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155
Jeff Brown96307042012-07-27 15:51:34 -07002156 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
2157 synchronized (mLock) {
2158 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2159 mDirty |= DIRTY_SETTINGS;
2160 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
2162 }
2163
Jeff Brown96307042012-07-27 15:51:34 -07002164 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
2165 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
2166 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002168
Jeff Brown96307042012-07-27 15:51:34 -07002169 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002170 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07002171 synchronized (mLock) {
2172 if (!mSystemReady) {
2173 return;
2174 }
2175 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002176 }
Jeff Brown96307042012-07-27 15:51:34 -07002177
2178 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002179 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07002180 }
2181
Jeff Brown96307042012-07-27 15:51:34 -07002182 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
2183 synchronized (mLock) {
2184 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
2185 mScreenBrightnessOverrideFromWindowManager = brightness;
2186 mDirty |= DIRTY_SETTINGS;
2187 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002188 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002189 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002190 }
2191
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002192 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
2193 synchronized (mLock) {
2194 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
2195 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
2196 mDirty |= DIRTY_SETTINGS;
2197 updatePowerStateLocked();
2198 }
2199 }
2200 }
2201
Jeff Brown96307042012-07-27 15:51:34 -07002202 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
2203 synchronized (mLock) {
2204 if (mTemporaryScreenBrightnessSettingOverride != brightness) {
2205 mTemporaryScreenBrightnessSettingOverride = brightness;
2206 mDirty |= DIRTY_SETTINGS;
2207 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002208 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002209 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002210 }
2211
Jeff Brown330560f2012-08-21 22:10:57 -07002212 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
2213 synchronized (mLock) {
2214 // Note: This condition handles NaN because NaN is not equal to any other
2215 // value, including itself.
2216 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
2217 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
2218 mDirty |= DIRTY_SETTINGS;
2219 updatePowerStateLocked();
2220 }
2221 }
Jeff Brown96307042012-07-27 15:51:34 -07002222 }
2223
Jeff Brown970d4132014-07-19 11:33:47 -07002224 private void setDozeOverrideFromDreamManagerInternal(
2225 int screenState, int screenBrightness) {
2226 synchronized (mLock) {
2227 if (mDozeScreenStateOverrideFromDreamManager != screenState
2228 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
2229 mDozeScreenStateOverrideFromDreamManager = screenState;
2230 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
2231 mDirty |= DIRTY_SETTINGS;
2232 updatePowerStateLocked();
2233 }
2234 }
2235 }
2236
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07002237 private void powerHintInternal(int hintId, int data) {
2238 nativeSendPowerHint(hintId, data);
2239 }
2240
Jeff Brown96307042012-07-27 15:51:34 -07002241 /**
2242 * Low-level function turn the device off immediately, without trying
2243 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
2244 */
2245 public static void lowLevelShutdown() {
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002246 SystemProperties.set("sys.powerctl", "shutdown");
Jeff Brown96307042012-07-27 15:51:34 -07002247 }
2248
2249 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08002250 * Low-level function to reboot the device. On success, this
2251 * function doesn't return. If more than 20 seconds passes from
2252 * the time a reboot is requested (120 seconds for reboot to
2253 * recovery), this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07002254 *
2255 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07002256 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002257 public static void lowLevelReboot(String reason) {
2258 if (reason == null) {
2259 reason = "";
2260 }
Doug Zongker3b0218b2014-01-14 12:29:06 -08002261 long duration;
2262 if (reason.equals(PowerManager.REBOOT_RECOVERY)) {
2263 // If we are rebooting to go into recovery, instead of
2264 // setting sys.powerctl directly we'll start the
2265 // pre-recovery service which will do some preparation for
2266 // recovery and then reboot for us.
2267 //
2268 // This preparation can take more than 20 seconds if
2269 // there's a very large update package, so lengthen the
2270 // timeout.
2271 SystemProperties.set("ctl.start", "pre-recovery");
2272 duration = 120 * 1000L;
2273 } else {
2274 SystemProperties.set("sys.powerctl", "reboot," + reason);
2275 duration = 20 * 1000L;
2276 }
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002277 try {
Doug Zongker3b0218b2014-01-14 12:29:06 -08002278 Thread.sleep(duration);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002279 } catch (InterruptedException e) {
2280 Thread.currentThread().interrupt();
2281 }
Jeff Brown96307042012-07-27 15:51:34 -07002282 }
2283
2284 @Override // Watchdog.Monitor implementation
2285 public void monitor() {
2286 // Grab and release lock for watchdog monitor to detect deadlocks.
2287 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002288 }
Jeff Brown96307042012-07-27 15:51:34 -07002289 }
2290
Jeff Brown6f357d32014-01-15 20:40:55 -08002291 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07002292 pw.println("POWER MANAGER (dumpsys power)\n");
2293
Jeff Brown3b971592013-01-09 18:46:37 -08002294 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07002295 synchronized (mLock) {
2296 pw.println("Power Manager State:");
2297 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
2298 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness));
Jeff Brown037c33e2014-04-09 00:31:55 -07002299 pw.println(" mInteractive=" + mInteractive);
Jeff Brown96307042012-07-27 15:51:34 -07002300 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07002301 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07002302 pw.println(" mBatteryLevel=" + mBatteryLevel);
2303 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07002304 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07002305 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07002306 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07002307 pw.println(" mBootCompleted=" + mBootCompleted);
2308 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07002309 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
2310 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07002311 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2312 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2313 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2314 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08002315 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07002316 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled);
2317 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07002318 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2319 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Jeff Brown96307042012-07-27 15:51:34 -07002320 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2321 pw.println(" mLastUserActivityTimeNoChangeLights="
2322 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07002323 pw.println(" mLastInteractivePowerHintTime="
2324 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Brown96307042012-07-27 15:51:34 -07002325 pw.println(" mDisplayReady=" + mDisplayReady);
2326 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08002327 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07002328
2329 pw.println();
2330 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07002331 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
2332 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
2333 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
2334 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002335 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
2336 + mWakeUpWhenPluggedOrUnpluggedConfig);
2337 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
2338 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002339 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002340 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2341 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
2342 + mDreamsActivatedOnSleepByDefaultConfig);
2343 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
2344 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08002345 pw.println(" mDreamsEnabledOnBatteryConfig="
2346 + mDreamsEnabledOnBatteryConfig);
2347 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
2348 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2349 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2350 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2351 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
2352 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002353 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04002354 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07002355 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown2175e9c2014-09-12 16:11:07 -07002356 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig);
Dianne Hackborn14272302014-06-10 23:13:02 -07002357 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002358 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured);
John Spurlock1bb480a2014-08-02 17:12:43 -04002359 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing);
Jeff Brown27736f52014-05-20 17:17:10 -07002360 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
2361 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
2362 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002363 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
2364 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
2365 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2366 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2367 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2368 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
Jeff Brown330560f2012-08-21 22:10:57 -07002369 pw.println(" mScreenAutoBrightnessAdjustmentSetting="
2370 + mScreenAutoBrightnessAdjustmentSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002371 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2372 pw.println(" mScreenBrightnessOverrideFromWindowManager="
2373 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002374 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
2375 + mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown96307042012-07-27 15:51:34 -07002376 pw.println(" mTemporaryScreenBrightnessSettingOverride="
2377 + mTemporaryScreenBrightnessSettingOverride);
Jeff Brown330560f2012-08-21 22:10:57 -07002378 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2379 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
Jeff Brown970d4132014-07-19 11:33:47 -07002380 pw.println(" mDozeScreenStateOverrideFromDreamManager="
2381 + mDozeScreenStateOverrideFromDreamManager);
2382 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
2383 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07002384 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2385 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2386 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
2387
Jeff Brownff532542012-10-02 21:18:04 -07002388 final int screenOffTimeout = getScreenOffTimeoutLocked();
2389 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2390 pw.println();
2391 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
2392 pw.println("Screen dim duration: " + screenDimDuration + " ms");
2393
Jeff Brown96307042012-07-27 15:51:34 -07002394 pw.println();
2395 pw.println("Wake Locks: size=" + mWakeLocks.size());
2396 for (WakeLock wl : mWakeLocks) {
2397 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04002398 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002399
Jeff Brown96307042012-07-27 15:51:34 -07002400 pw.println();
2401 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
2402 for (SuspendBlocker sb : mSuspendBlockers) {
2403 pw.println(" " + sb);
2404 }
2405
Jeff Brownc38c9be2012-10-04 13:16:19 -07002406 pw.println();
2407 pw.println("Screen On Blocker: " + mScreenOnBlocker);
2408
Jeff Brown9e316a12012-10-08 19:17:06 -07002409 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07002410 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07002411
Jeff Brown3b971592013-01-09 18:46:37 -08002412 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07002413 }
2414
Jeff Brown3b971592013-01-09 18:46:37 -08002415 if (wcd != null) {
2416 wcd.dump(pw);
2417 }
Jeff Brown96307042012-07-27 15:51:34 -07002418 }
2419
2420 private SuspendBlocker createSuspendBlockerLocked(String name) {
2421 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
2422 mSuspendBlockers.add(suspendBlocker);
2423 return suspendBlocker;
2424 }
2425
2426 private static String wakefulnessToString(int wakefulness) {
2427 switch (wakefulness) {
2428 case WAKEFULNESS_ASLEEP:
2429 return "Asleep";
2430 case WAKEFULNESS_AWAKE:
2431 return "Awake";
2432 case WAKEFULNESS_DREAMING:
2433 return "Dreaming";
Jeff Brown26875502014-01-30 21:47:47 -08002434 case WAKEFULNESS_DOZING:
2435 return "Dozing";
Jeff Brown96307042012-07-27 15:51:34 -07002436 default:
2437 return Integer.toString(wakefulness);
2438 }
2439 }
2440
2441 private static WorkSource copyWorkSource(WorkSource workSource) {
2442 return workSource != null ? new WorkSource(workSource) : null;
2443 }
2444
2445 private final class BatteryReceiver extends BroadcastReceiver {
2446 @Override
2447 public void onReceive(Context context, Intent intent) {
2448 synchronized (mLock) {
2449 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002450 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002451 }
2452 }
2453
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002454 private final class DreamReceiver extends BroadcastReceiver {
2455 @Override
2456 public void onReceive(Context context, Intent intent) {
2457 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002458 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002459 }
2460 }
2461 }
2462
Jeff Brownd4935962012-09-25 13:27:20 -07002463 private final class UserSwitchedReceiver extends BroadcastReceiver {
2464 @Override
2465 public void onReceive(Context context, Intent intent) {
2466 synchronized (mLock) {
2467 handleSettingsChangedLocked();
2468 }
2469 }
2470 }
2471
Jeff Brownec6aa592012-10-17 20:30:25 -07002472 private final class DockReceiver extends BroadcastReceiver {
2473 @Override
2474 public void onReceive(Context context, Intent intent) {
2475 synchronized (mLock) {
2476 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2477 Intent.EXTRA_DOCK_STATE_UNDOCKED);
2478 if (mDockState != dockState) {
2479 mDockState = dockState;
2480 mDirty |= DIRTY_DOCK_STATE;
2481 updatePowerStateLocked();
2482 }
2483 }
2484 }
2485 }
2486
Jeff Brown96307042012-07-27 15:51:34 -07002487 private final class SettingsObserver extends ContentObserver {
2488 public SettingsObserver(Handler handler) {
2489 super(handler);
2490 }
2491
2492 @Override
2493 public void onChange(boolean selfChange, Uri uri) {
2494 synchronized (mLock) {
2495 handleSettingsChangedLocked();
2496 }
2497 }
2498 }
2499
Jeff Brown96307042012-07-27 15:51:34 -07002500 /**
2501 * Handler for asynchronous operations performed by the power manager.
2502 */
2503 private final class PowerManagerHandler extends Handler {
2504 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07002505 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07002506 }
2507
2508 @Override
2509 public void handleMessage(Message msg) {
2510 switch (msg.what) {
2511 case MSG_USER_ACTIVITY_TIMEOUT:
2512 handleUserActivityTimeout();
2513 break;
2514 case MSG_SANDMAN:
2515 handleSandman();
2516 break;
Jeff Brownc38c9be2012-10-04 13:16:19 -07002517 case MSG_SCREEN_ON_BLOCKER_RELEASED:
2518 handleScreenOnBlockerReleased();
2519 break;
Jeff Brown96307042012-07-27 15:51:34 -07002520 }
2521 }
2522 }
2523
2524 /**
2525 * Represents a wake lock that has been acquired by an application.
2526 */
2527 private final class WakeLock implements IBinder.DeathRecipient {
2528 public final IBinder mLock;
2529 public int mFlags;
2530 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002531 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07002532 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002533 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002534 public final int mOwnerUid;
2535 public final int mOwnerPid;
2536 public boolean mNotifiedAcquired;
Jeff Brown96307042012-07-27 15:51:34 -07002537
Dianne Hackborn713df152013-05-17 11:27:57 -07002538 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002539 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Jeff Brown96307042012-07-27 15:51:34 -07002540 mLock = lock;
2541 mFlags = flags;
2542 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002543 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07002544 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002545 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07002546 mOwnerUid = ownerUid;
2547 mOwnerPid = ownerPid;
2548 }
2549
2550 @Override
2551 public void binderDied() {
2552 PowerManagerService.this.handleWakeLockDeath(this);
2553 }
2554
2555 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2556 int ownerUid, int ownerPid) {
2557 return mFlags == flags
2558 && mTag.equals(tag)
2559 && hasSameWorkSource(workSource)
2560 && mOwnerUid == ownerUid
2561 && mOwnerPid == ownerPid;
2562 }
2563
Dianne Hackborn713df152013-05-17 11:27:57 -07002564 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002565 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07002566 if (!mPackageName.equals(packageName)) {
2567 throw new IllegalStateException("Existing wake lock package name changed: "
2568 + mPackageName + " to " + packageName);
2569 }
2570 if (mOwnerUid != ownerUid) {
2571 throw new IllegalStateException("Existing wake lock uid changed: "
2572 + mOwnerUid + " to " + ownerUid);
2573 }
2574 if (mOwnerPid != ownerPid) {
2575 throw new IllegalStateException("Existing wake lock pid changed: "
2576 + mOwnerPid + " to " + ownerPid);
2577 }
Jeff Brown96307042012-07-27 15:51:34 -07002578 mFlags = flags;
2579 mTag = tag;
2580 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002581 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07002582 }
2583
2584 public boolean hasSameWorkSource(WorkSource workSource) {
2585 return Objects.equal(mWorkSource, workSource);
2586 }
2587
2588 public void updateWorkSource(WorkSource workSource) {
2589 mWorkSource = copyWorkSource(workSource);
2590 }
2591
2592 @Override
2593 public String toString() {
2594 return getLockLevelString()
2595 + " '" + mTag + "'" + getLockFlagsString()
2596 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2597 }
2598
Jeff Brown26875502014-01-30 21:47:47 -08002599 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07002600 private String getLockLevelString() {
2601 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2602 case PowerManager.FULL_WAKE_LOCK:
2603 return "FULL_WAKE_LOCK ";
2604 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2605 return "SCREEN_BRIGHT_WAKE_LOCK ";
2606 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2607 return "SCREEN_DIM_WAKE_LOCK ";
2608 case PowerManager.PARTIAL_WAKE_LOCK:
2609 return "PARTIAL_WAKE_LOCK ";
2610 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2611 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08002612 case PowerManager.DOZE_WAKE_LOCK:
2613 return "DOZE_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07002614 default:
2615 return "??? ";
2616 }
2617 }
2618
2619 private String getLockFlagsString() {
2620 String result = "";
2621 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2622 result += " ACQUIRE_CAUSES_WAKEUP";
2623 }
2624 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2625 result += " ON_AFTER_RELEASE";
2626 }
2627 return result;
2628 }
2629 }
2630
2631 private final class SuspendBlockerImpl implements SuspendBlocker {
2632 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07002633 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07002634 private int mReferenceCount;
2635
2636 public SuspendBlockerImpl(String name) {
2637 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07002638 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07002639 }
2640
2641 @Override
2642 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002643 try {
Jeff Brown96307042012-07-27 15:51:34 -07002644 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07002645 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07002646 + "\" was finalized without being released!");
2647 mReferenceCount = 0;
2648 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07002649 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002650 }
2651 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07002652 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002653 }
2654 }
2655
Craig Mautner75fc9de2012-06-18 16:53:27 -07002656 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002657 public void acquire() {
2658 synchronized (this) {
2659 mReferenceCount += 1;
2660 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002661 if (DEBUG_SPEW) {
2662 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2663 }
Jeff Brown3edf5272014-08-14 19:25:14 -07002664 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07002665 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07002666 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002667 }
2668 }
2669
Craig Mautner75fc9de2012-06-18 16:53:27 -07002670 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002671 public void release() {
2672 synchronized (this) {
2673 mReferenceCount -= 1;
2674 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002675 if (DEBUG_SPEW) {
2676 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2677 }
Jeff Brown96307042012-07-27 15:51:34 -07002678 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07002679 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07002680 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07002681 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07002682 + "\" was released without being acquired!", new Throwable());
2683 mReferenceCount = 0;
2684 }
2685 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002686 }
Jeff Brown96307042012-07-27 15:51:34 -07002687
2688 @Override
2689 public String toString() {
2690 synchronized (this) {
2691 return mName + ": ref count=" + mReferenceCount;
2692 }
2693 }
2694 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002695
2696 private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
Jeff Brown3edf5272014-08-14 19:25:14 -07002697 private static final String TRACE_NAME = "ScreenOnBlocker";
2698
Jeff Brownc38c9be2012-10-04 13:16:19 -07002699 private int mNestCount;
2700
2701 public boolean isHeld() {
2702 synchronized (this) {
2703 return mNestCount != 0;
2704 }
2705 }
2706
2707 @Override
2708 public void acquire() {
2709 synchronized (this) {
2710 mNestCount += 1;
Jeff Brown3edf5272014-08-14 19:25:14 -07002711 if (DEBUG || true) {
Jeff Brownc38c9be2012-10-04 13:16:19 -07002712 Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
2713 }
Jeff Brown3edf5272014-08-14 19:25:14 -07002714 if (mNestCount == 1) {
2715 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_NAME, 0);
2716 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002717 }
2718 }
2719
2720 @Override
2721 public void release() {
2722 synchronized (this) {
2723 mNestCount -= 1;
Jeff Brown3edf5272014-08-14 19:25:14 -07002724 if (mNestCount == 0) {
2725 if (DEBUG || true) {
2726 Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
2727 }
2728 mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
2729 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_NAME, 0);
2730 } else if (mNestCount < 0) {
2731 Slog.wtf(TAG, "Screen on blocker was released without being acquired!",
Jeff Brownc38c9be2012-10-04 13:16:19 -07002732 new Throwable());
2733 mNestCount = 0;
2734 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002735 }
2736 }
2737
2738 @Override
2739 public String toString() {
2740 synchronized (this) {
2741 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
2742 }
2743 }
Jeff Brown9e316a12012-10-08 19:17:06 -07002744 }
2745
Jeff Brown6f357d32014-01-15 20:40:55 -08002746 private final class BinderService extends IPowerManager.Stub {
2747 @Override // Binder call
2748 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2749 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07002750 if (uid < 0) {
2751 uid = Binder.getCallingUid();
2752 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002753 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08002754 }
2755
2756 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002757 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07002758 if (!mSystemReady) {
2759 // Service not ready yet, so who the heck cares about power hints, bah.
2760 return;
2761 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002762 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07002763 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07002764 }
2765
2766 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08002767 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002768 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002769 if (lock == null) {
2770 throw new IllegalArgumentException("lock must not be null");
2771 }
2772 if (packageName == null) {
2773 throw new IllegalArgumentException("packageName must not be null");
2774 }
2775 PowerManager.validateWakeLockParameters(flags, tag);
2776
2777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07002778 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
2779 mContext.enforceCallingOrSelfPermission(
2780 android.Manifest.permission.DEVICE_POWER, null);
2781 }
Jeff Brown6f357d32014-01-15 20:40:55 -08002782 if (ws != null && ws.size() != 0) {
2783 mContext.enforceCallingOrSelfPermission(
2784 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2785 } else {
2786 ws = null;
2787 }
2788
2789 final int uid = Binder.getCallingUid();
2790 final int pid = Binder.getCallingPid();
2791 final long ident = Binder.clearCallingIdentity();
2792 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08002793 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002794 } finally {
2795 Binder.restoreCallingIdentity(ident);
2796 }
2797 }
2798
2799 @Override // Binder call
2800 public void releaseWakeLock(IBinder lock, int flags) {
2801 if (lock == null) {
2802 throw new IllegalArgumentException("lock must not be null");
2803 }
2804
2805 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2806
2807 final long ident = Binder.clearCallingIdentity();
2808 try {
2809 releaseWakeLockInternal(lock, flags);
2810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814
2815 @Override // Binder call
2816 public void updateWakeLockUids(IBinder lock, int[] uids) {
2817 WorkSource ws = null;
2818
2819 if (uids != null) {
2820 ws = new WorkSource();
2821 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2822 // one at a time?
2823 for (int i = 0; i < uids.length; i++) {
2824 ws.add(uids[i]);
2825 }
2826 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07002827 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08002828 }
2829
2830 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07002831 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002832 if (lock == null) {
2833 throw new IllegalArgumentException("lock must not be null");
2834 }
2835
2836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2837 if (ws != null && ws.size() != 0) {
2838 mContext.enforceCallingOrSelfPermission(
2839 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2840 } else {
2841 ws = null;
2842 }
2843
Dianne Hackbornd953c532014-08-16 18:17:38 -07002844 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002845 final long ident = Binder.clearCallingIdentity();
2846 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07002847 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002848 } finally {
2849 Binder.restoreCallingIdentity(ident);
2850 }
2851 }
2852
2853 @Override // Binder call
2854 public boolean isWakeLockLevelSupported(int level) {
2855 final long ident = Binder.clearCallingIdentity();
2856 try {
2857 return isWakeLockLevelSupportedInternal(level);
2858 } finally {
2859 Binder.restoreCallingIdentity(ident);
2860 }
2861 }
2862
2863 @Override // Binder call
2864 public void userActivity(long eventTime, int event, int flags) {
2865 final long now = SystemClock.uptimeMillis();
2866 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07002867 != PackageManager.PERMISSION_GRANTED
2868 && mContext.checkCallingOrSelfPermission(
2869 android.Manifest.permission.USER_ACTIVITY)
2870 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002871 // Once upon a time applications could call userActivity().
2872 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
2873 // request instead of throwing a SecurityException so we don't break old apps.
2874 synchronized (mLock) {
2875 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2876 mLastWarningAboutUserActivityPermission = now;
2877 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07002878 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
2879 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08002880 + " pid=" + Binder.getCallingPid()
2881 + " uid=" + Binder.getCallingUid());
2882 }
2883 }
2884 return;
2885 }
2886
2887 if (eventTime > SystemClock.uptimeMillis()) {
2888 throw new IllegalArgumentException("event time must not be in the future");
2889 }
2890
2891 final int uid = Binder.getCallingUid();
2892 final long ident = Binder.clearCallingIdentity();
2893 try {
2894 userActivityInternal(eventTime, event, flags, uid);
2895 } finally {
2896 Binder.restoreCallingIdentity(ident);
2897 }
2898 }
2899
2900 @Override // Binder call
2901 public void wakeUp(long eventTime) {
2902 if (eventTime > SystemClock.uptimeMillis()) {
2903 throw new IllegalArgumentException("event time must not be in the future");
2904 }
2905
2906 mContext.enforceCallingOrSelfPermission(
2907 android.Manifest.permission.DEVICE_POWER, null);
2908
Jeff Brownc12035c2014-08-13 18:52:25 -07002909 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002910 final long ident = Binder.clearCallingIdentity();
2911 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07002912 wakeUpInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002913 } finally {
2914 Binder.restoreCallingIdentity(ident);
2915 }
2916 }
2917
2918 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07002919 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08002920 if (eventTime > SystemClock.uptimeMillis()) {
2921 throw new IllegalArgumentException("event time must not be in the future");
2922 }
2923
2924 mContext.enforceCallingOrSelfPermission(
2925 android.Manifest.permission.DEVICE_POWER, null);
2926
Jeff Brownc12035c2014-08-13 18:52:25 -07002927 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002928 final long ident = Binder.clearCallingIdentity();
2929 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07002930 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002931 } finally {
2932 Binder.restoreCallingIdentity(ident);
2933 }
2934 }
2935
2936 @Override // Binder call
2937 public void nap(long eventTime) {
2938 if (eventTime > SystemClock.uptimeMillis()) {
2939 throw new IllegalArgumentException("event time must not be in the future");
2940 }
2941
2942 mContext.enforceCallingOrSelfPermission(
2943 android.Manifest.permission.DEVICE_POWER, null);
2944
Jeff Brownc12035c2014-08-13 18:52:25 -07002945 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08002946 final long ident = Binder.clearCallingIdentity();
2947 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07002948 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08002949 } finally {
2950 Binder.restoreCallingIdentity(ident);
2951 }
2952 }
2953
2954 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07002955 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08002956 final long ident = Binder.clearCallingIdentity();
2957 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002958 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08002959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
2962 }
2963
Dianne Hackborneb94fa72014-06-03 17:48:12 -07002964 @Override // Binder call
2965 public boolean isPowerSaveMode() {
2966 final long ident = Binder.clearCallingIdentity();
2967 try {
2968 return isLowPowerModeInternal();
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002974 @Override // Binder call
2975 public boolean setPowerSaveMode(boolean mode) {
2976 mContext.enforceCallingOrSelfPermission(
2977 android.Manifest.permission.DEVICE_POWER, null);
2978 final long ident = Binder.clearCallingIdentity();
2979 try {
2980 return setLowPowerModeInternal(mode);
2981 } finally {
2982 Binder.restoreCallingIdentity(ident);
2983 }
2984 }
2985
Jeff Brown6f357d32014-01-15 20:40:55 -08002986 /**
2987 * Reboots the device.
2988 *
2989 * @param confirm If true, shows a reboot confirmation dialog.
2990 * @param reason The reason for the reboot, or null if none.
2991 * @param wait If true, this call waits for the reboot to complete and does not return.
2992 */
2993 @Override // Binder call
2994 public void reboot(boolean confirm, String reason, boolean wait) {
2995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Doug Zongker3b0218b2014-01-14 12:29:06 -08002996 if (PowerManager.REBOOT_RECOVERY.equals(reason)) {
2997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
2998 }
Jeff Brown6f357d32014-01-15 20:40:55 -08002999
3000 final long ident = Binder.clearCallingIdentity();
3001 try {
3002 shutdownOrRebootInternal(false, confirm, reason, wait);
3003 } finally {
3004 Binder.restoreCallingIdentity(ident);
3005 }
3006 }
3007
3008 /**
3009 * Shuts down the device.
3010 *
3011 * @param confirm If true, shows a shutdown confirmation dialog.
3012 * @param wait If true, this call waits for the shutdown to complete and does not return.
3013 */
3014 @Override // Binder call
3015 public void shutdown(boolean confirm, boolean wait) {
3016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3017
3018 final long ident = Binder.clearCallingIdentity();
3019 try {
3020 shutdownOrRebootInternal(true, confirm, null, wait);
3021 } finally {
3022 Binder.restoreCallingIdentity(ident);
3023 }
3024 }
3025
3026 /**
3027 * Crash the runtime (causing a complete restart of the Android framework).
3028 * Requires REBOOT permission. Mostly for testing. Should not return.
3029 */
3030 @Override // Binder call
3031 public void crash(String message) {
3032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
3033
3034 final long ident = Binder.clearCallingIdentity();
3035 try {
3036 crashInternal(message);
3037 } finally {
3038 Binder.restoreCallingIdentity(ident);
3039 }
3040 }
3041
3042 /**
3043 * Set the setting that determines whether the device stays on when plugged in.
3044 * The argument is a bit string, with each bit specifying a power source that,
3045 * when the device is connected to that source, causes the device to stay on.
3046 * See {@link android.os.BatteryManager} for the list of power sources that
3047 * can be specified. Current values include
3048 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
3049 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
3050 *
3051 * Used by "adb shell svc power stayon ..."
3052 *
3053 * @param val an {@code int} containing the bits that specify which power sources
3054 * should cause the device to stay on.
3055 */
3056 @Override // Binder call
3057 public void setStayOnSetting(int val) {
3058 mContext.enforceCallingOrSelfPermission(
3059 android.Manifest.permission.WRITE_SETTINGS, null);
3060
3061 final long ident = Binder.clearCallingIdentity();
3062 try {
3063 setStayOnSettingInternal(val);
3064 } finally {
3065 Binder.restoreCallingIdentity(ident);
3066 }
3067 }
3068
3069 /**
3070 * Used by device administration to set the maximum screen off timeout.
3071 *
3072 * This method must only be called by the device administration policy manager.
3073 */
3074 @Override // Binder call
3075 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
3076 final long ident = Binder.clearCallingIdentity();
3077 try {
3078 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
3079 } finally {
3080 Binder.restoreCallingIdentity(ident);
3081 }
3082 }
3083
3084 /**
3085 * Used by the settings application and brightness control widgets to
3086 * temporarily override the current screen brightness setting so that the
3087 * user can observe the effect of an intended settings change without applying
3088 * it immediately.
3089 *
3090 * The override will be canceled when the setting value is next updated.
3091 *
3092 * @param brightness The overridden brightness.
3093 *
3094 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
3095 */
3096 @Override // Binder call
3097 public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
3098 mContext.enforceCallingOrSelfPermission(
3099 android.Manifest.permission.DEVICE_POWER, null);
3100
3101 final long ident = Binder.clearCallingIdentity();
3102 try {
3103 setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
3104 } finally {
3105 Binder.restoreCallingIdentity(ident);
3106 }
3107 }
3108
3109 /**
3110 * Used by the settings application and brightness control widgets to
3111 * temporarily override the current screen auto-brightness adjustment setting so that the
3112 * user can observe the effect of an intended settings change without applying
3113 * it immediately.
3114 *
3115 * The override will be canceled when the setting value is next updated.
3116 *
3117 * @param adj The overridden brightness, or Float.NaN to disable the override.
3118 *
Jeff Brown131206b2014-04-08 17:27:14 -07003119 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
Jeff Brown6f357d32014-01-15 20:40:55 -08003120 */
3121 @Override // Binder call
3122 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
3123 mContext.enforceCallingOrSelfPermission(
3124 android.Manifest.permission.DEVICE_POWER, null);
3125
3126 final long ident = Binder.clearCallingIdentity();
3127 try {
3128 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
3129 } finally {
3130 Binder.restoreCallingIdentity(ident);
3131 }
3132 }
3133
3134 /**
3135 * Used by the phone application to make the attention LED flash when ringing.
3136 */
3137 @Override // Binder call
3138 public void setAttentionLight(boolean on, int color) {
3139 mContext.enforceCallingOrSelfPermission(
3140 android.Manifest.permission.DEVICE_POWER, null);
3141
3142 final long ident = Binder.clearCallingIdentity();
3143 try {
3144 setAttentionLightInternal(on, color);
3145 } finally {
3146 Binder.restoreCallingIdentity(ident);
3147 }
3148 }
3149
3150 @Override // Binder call
3151 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3152 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
3153 != PackageManager.PERMISSION_GRANTED) {
3154 pw.println("Permission Denial: can't dump PowerManager from from pid="
3155 + Binder.getCallingPid()
3156 + ", uid=" + Binder.getCallingUid());
3157 return;
3158 }
3159
3160 final long ident = Binder.clearCallingIdentity();
3161 try {
3162 dumpInternal(pw);
3163 } finally {
3164 Binder.restoreCallingIdentity(ident);
3165 }
3166 }
3167 }
3168
Jeff Brown4ccb8232014-01-16 22:16:42 -08003169 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08003170 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003171 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
3172 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3173 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3174 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08003175 }
Jeff Brown970d4132014-07-19 11:33:47 -07003176 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08003177 }
3178
Jeff Brown6f357d32014-01-15 20:40:55 -08003179 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07003180 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) {
Jeff Brown6f357d32014-01-15 20:40:55 -08003181 // Do nothing.
3182 // Button lights are not currently supported in the new implementation.
Jeff Brown6f357d32014-01-15 20:40:55 -08003183 }
3184
Jeff Brown970d4132014-07-19 11:33:47 -07003185 @Override
3186 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
3187 switch (screenState) {
3188 case Display.STATE_UNKNOWN:
3189 case Display.STATE_OFF:
3190 case Display.STATE_DOZE:
3191 case Display.STATE_DOZE_SUSPEND:
3192 case Display.STATE_ON:
3193 break;
3194 default:
3195 screenState = Display.STATE_UNKNOWN;
3196 break;
3197 }
3198 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
3199 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
3200 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
3201 }
3202 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
3203 }
3204
Jeff Brown6f357d32014-01-15 20:40:55 -08003205 @Override
3206 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07003207 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08003208 }
3209
3210 @Override
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003211 public boolean getLowPowerModeEnabled() {
3212 synchronized (mLock) {
3213 return mLowPowerModeEnabled;
3214 }
3215 }
3216
3217 @Override
3218 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
3219 synchronized (mLock) {
3220 mLowPowerModeListeners.add(listener);
3221 }
3222 }
Jeff Brown6f357d32014-01-15 20:40:55 -08003223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224}