blob: 6b2ca4ca6de54659c60904daa9d90b6fb3c14b80 [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;
Jeff Brown4f8ecd82012-06-18 18:29:13 -070021import com.android.server.BatteryService;
22import com.android.server.EventLogTags;
Jeff Brown567f7ca2014-01-30 23:38:03 -080023import com.android.server.LocalServices;
Jeff Brown6f357d32014-01-15 20:40:55 -080024import com.android.server.ServiceThread;
Adam Lesinski182f73f2013-12-05 16:48:06 -080025import com.android.server.lights.Light;
26import com.android.server.lights.LightsManager;
Jeff Brown4f8ecd82012-06-18 18:29:13 -070027import com.android.server.Watchdog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028
Jeff Brown96307042012-07-27 15:51:34 -070029import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.ContentResolver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070036import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080037import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080038import android.hardware.SensorManager;
39import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080040import android.hardware.display.DisplayManagerInternal;
Jeff Brownad9ef192014-04-08 17:26:30 -070041import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Jeff Brown96307042012-07-27 15:51:34 -070042import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070043import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Binder;
45import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.IBinder;
47import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070048import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080049import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.PowerManager;
Jeff Brown6f357d32014-01-15 20:40:55 -080051import android.os.PowerManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Process;
53import android.os.RemoteException;
54import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070055import android.os.SystemProperties;
Jeff Brown20767b22012-10-09 18:57:07 -070056import android.os.SystemService;
Jeff Brownd4935962012-09-25 13:27:20 -070057import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070058import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.provider.Settings;
Jeff Brown567f7ca2014-01-30 23:38:03 -080060import android.service.dreams.DreamManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.util.EventLog;
62import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080063import android.util.Slog;
Jeff Brown96307042012-07-27 15:51:34 -070064import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.view.WindowManagerPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67import java.io.FileDescriptor;
68import java.io.PrintWriter;
69import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
Jeff Brown96307042012-07-27 15:51:34 -070071import libcore.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Jeff Brown96307042012-07-27 15:51:34 -070073/**
74 * The power manager service is responsible for coordinating power management
75 * functions on the device.
76 */
Jeff Brown6f357d32014-01-15 20:40:55 -080077public final class PowerManagerService extends com.android.server.SystemService
Jeff Brown96307042012-07-27 15:51:34 -070078 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Jeff Brown88c997a2012-06-22 13:57:45 -070081 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -070082 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -070083
Jeff Brown96307042012-07-27 15:51:34 -070084 // Message: Sent when a user activity timeout occurs to update the power state.
85 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -080086 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -070087 private static final int MSG_SANDMAN = 2;
Jeff Brownc38c9be2012-10-04 13:16:19 -070088 // Message: Sent when the screen on blocker is released.
89 private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3;
Jeff Brown20767b22012-10-09 18:57:07 -070090 // Message: Sent to poll whether the boot animation has terminated.
91 private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4;
Jeff Brown7304c342012-05-11 18:42:42 -070092
Jeff Brown96307042012-07-27 15:51:34 -070093 // Dirty bit: mWakeLocks changed
94 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
95 // Dirty bit: mWakefulness changed
96 private static final int DIRTY_WAKEFULNESS = 1 << 1;
97 // Dirty bit: user activity was poked or may have timed out
98 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
99 // Dirty bit: actual display power state was updated asynchronously
100 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
101 // Dirty bit: mBootCompleted changed
102 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
103 // Dirty bit: settings changed
104 private static final int DIRTY_SETTINGS = 1 << 5;
105 // Dirty bit: mIsPowered changed
106 private static final int DIRTY_IS_POWERED = 1 << 6;
107 // Dirty bit: mStayOn changed
108 private static final int DIRTY_STAY_ON = 1 << 7;
109 // Dirty bit: battery state changed
110 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700111 // Dirty bit: proximity state changed
112 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownc38c9be2012-10-04 13:16:19 -0700113 // Dirty bit: screen on blocker state became held or unheld
114 private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10;
Jeff Brownec6aa592012-10-17 20:30:25 -0700115 // Dirty bit: dock state changed
116 private static final int DIRTY_DOCK_STATE = 1 << 11;
Jeff Brown7304c342012-05-11 18:42:42 -0700117
Jeff Brown96307042012-07-27 15:51:34 -0700118 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp().
119 // The screen should be off or in the process of being turned off by the display controller.
Jeff Brown26875502014-01-30 21:47:47 -0800120 // The device typically passes through the dozing state first.
Jeff Brown96307042012-07-27 15:51:34 -0700121 private static final int WAKEFULNESS_ASLEEP = 0;
122 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep().
Jeff Brown26875502014-01-30 21:47:47 -0800123 // When the user activity timeout expires, the device may start dreaming or go to sleep.
Jeff Brown96307042012-07-27 15:51:34 -0700124 private static final int WAKEFULNESS_AWAKE = 1;
Jeff Brown96307042012-07-27 15:51:34 -0700125 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(),
126 // which ends the dream. The device goes to sleep when goToSleep() is called, when
127 // the dream ends or when unplugged.
128 // User activity may brighten the screen but does not end the dream.
Jeff Brown26875502014-01-30 21:47:47 -0800129 private static final int WAKEFULNESS_DREAMING = 2;
130 // Wakefulness: The device is dozing. It is almost asleep but is allowing a special
131 // low-power "doze" dream to run which keeps the display on but lets the application
132 // processor be suspended. It can be awoken by a call to wakeUp() which ends the dream.
133 // The device fully goes to sleep if the dream cannot be started or ends on its own.
134 private static final int WAKEFULNESS_DOZING = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Jeff Brown96307042012-07-27 15:51:34 -0700136 // Summarizes the state of all active wakelocks.
137 private static final int WAKE_LOCK_CPU = 1 << 0;
138 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
139 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
140 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
141 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700142 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800143 private static final int WAKE_LOCK_DOZE = 1 << 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Jeff Brown96307042012-07-27 15:51:34 -0700145 // Summarizes the user activity state.
146 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
147 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Jeff Brown96307042012-07-27 15:51:34 -0700149 // Default and minimum screen off timeout in milliseconds.
150 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
151 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700152
Jeff Brownff532542012-10-02 21:18:04 -0700153 // The screen dim duration, in milliseconds.
Jeff Brown96307042012-07-27 15:51:34 -0700154 // This is subtracted from the end of the screen off timeout so the
155 // minimum screen off timeout should be longer than this.
156 private static final int SCREEN_DIM_DURATION = 7 * 1000;
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800157
Jeff Brownff532542012-10-02 21:18:04 -0700158 // The maximum screen dim time expressed as a ratio relative to the screen
159 // off timeout. If the screen off timeout is very short then we want the
160 // dim timeout to also be quite short so that most of the time is spent on.
161 // Otherwise the user won't get much screen on time before dimming occurs.
162 private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f;
163
Jeff Brown20767b22012-10-09 18:57:07 -0700164 // The name of the boot animation service in init.rc.
165 private static final String BOOT_ANIMATION_SERVICE = "bootanim";
166
167 // Poll interval in milliseconds for watching boot animation finished.
168 private static final int BOOT_ANIMATION_POLL_INTERVAL = 200;
169
Jeff Brownb880d882014-02-10 19:47:07 -0800170 private final Context mContext;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800171 private LightsManager mLightsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private BatteryService mBatteryService;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800173 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700174 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700175 private IAppOpsService mAppOps;
Jeff Brown6f357d32014-01-15 20:40:55 -0800176 private ServiceThread mHandlerThread;
Jeff Brown96307042012-07-27 15:51:34 -0700177 private PowerManagerHandler mHandler;
178 private WindowManagerPolicy mPolicy;
179 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800180 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700181 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800182 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800183 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700184
Jeff Brown96307042012-07-27 15:51:34 -0700185 private final Object mLock = new Object();
186
187 // A bitfield that indicates what parts of the power state have
188 // changed and need to be recalculated.
189 private int mDirty;
190
191 // Indicates whether the device is awake or asleep or somewhere in between.
192 // This is distinct from the screen power state, which is managed separately.
193 private int mWakefulness;
194
Jeff Brown26875502014-01-30 21:47:47 -0800195 // True if the sandman has just been summoned for the first time since entering the
196 // dreaming or dozing state. Indicates whether a new dream should begin.
197 private boolean mSandmanSummoned;
198
Jeff Brown96307042012-07-27 15:51:34 -0700199 // True if MSG_SANDMAN has been scheduled.
200 private boolean mSandmanScheduled;
201
202 // Table of all suspend blockers.
203 // There should only be a few of these.
204 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
205
206 // Table of all wake locks acquired by applications.
207 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
208
209 // A bitfield that summarizes the state of all active wakelocks.
210 private int mWakeLockSummary;
211
212 // If true, instructs the display controller to wait for the proximity sensor to
213 // go negative before turning the screen on.
214 private boolean mRequestWaitForNegativeProximity;
215
216 // Timestamp of the last time the device was awoken or put to sleep.
217 private long mLastWakeTime;
218 private long mLastSleepTime;
219
220 // True if we need to send a wake up or go to sleep finished notification
221 // when the display is ready.
222 private boolean mSendWakeUpFinishedNotificationWhenReady;
223 private boolean mSendGoToSleepFinishedNotificationWhenReady;
224
225 // Timestamp of the last call to user activity.
226 private long mLastUserActivityTime;
227 private long mLastUserActivityTimeNoChangeLights;
228
229 // A bitfield that summarizes the effect of the user activity timer.
230 // A zero value indicates that the user activity timer has expired.
231 private int mUserActivitySummary;
232
233 // The desired display power state. The actual state may lag behind the
234 // requested because it is updated asynchronously by the display power controller.
235 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
236
Jeff Brown96307042012-07-27 15:51:34 -0700237 // True if the display power state has been fully applied, which means the display
238 // is actually on or actually off or whatever was requested.
239 private boolean mDisplayReady;
240
Jeff Brown27f7a862012-12-12 15:43:31 -0800241 // The suspend blocker used to keep the CPU alive when an application has acquired
242 // a wake lock.
243 private final SuspendBlocker mWakeLockSuspendBlocker;
244
245 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700246 private boolean mHoldingWakeLockSuspendBlocker;
247
Jeff Brown27f7a862012-12-12 15:43:31 -0800248 // The suspend blocker used to keep the CPU alive when the display is on, the
249 // display is getting ready or there is user activity (in which case the display
250 // must be on).
251 private final SuspendBlocker mDisplaySuspendBlocker;
252
253 // True if the display suspend blocker has been acquired.
254 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700255
Jeff Brownc38c9be2012-10-04 13:16:19 -0700256 // The screen on blocker used to keep the screen from turning on while the lock
257 // screen is coming up.
258 private final ScreenOnBlockerImpl mScreenOnBlocker;
259
Jeff Brown96307042012-07-27 15:51:34 -0700260 // True if systemReady() has been called.
261 private boolean mSystemReady;
262
263 // True if boot completed occurred. We keep the screen on until this happens.
264 private boolean mBootCompleted;
265
Jeff Brown26875502014-01-30 21:47:47 -0800266 // True if auto-suspend mode is enabled.
267 // Refer to autosuspend.h.
268 private boolean mAutoSuspendModeEnabled;
269
270 // True if interactive mode is enabled.
271 // Refer to power.h.
272 private boolean mInteractiveModeEnabled;
273
Jeff Brown96307042012-07-27 15:51:34 -0700274 // True if the device is plugged into a power source.
275 private boolean mIsPowered;
276
Jeff Brownf3fb8952012-10-02 20:57:05 -0700277 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
278 private int mPlugType;
279
Jeff Brown016ff142012-10-15 16:47:22 -0700280 // The current battery level percentage.
281 private int mBatteryLevel;
282
283 // The battery level percentage at the time the dream started.
284 // This is used to terminate a dream and go to sleep if the battery is
285 // draining faster than it is charging and the user activity timeout has expired.
286 private int mBatteryLevelWhenDreamStarted;
287
Jeff Brownec6aa592012-10-17 20:30:25 -0700288 // The current dock state.
289 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
290
Jeff Brown26875502014-01-30 21:47:47 -0800291 // True to decouple auto-suspend mode from the display state.
292 private boolean mDecoupleAutoSuspendModeFromDisplayConfig;
293
294 // True to decouple interactive mode from the display state.
295 private boolean mDecoupleInteractiveModeFromDisplayConfig;
296
Jeff Brown96307042012-07-27 15:51:34 -0700297 // True if the device should wake up when plugged or unplugged.
298 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
299
Jeff Brownec083212013-09-11 20:45:25 -0700300 // True if the device should suspend when the screen is off due to proximity.
301 private boolean mSuspendWhenScreenOffDueToProximityConfig;
302
Jeff Brown96307042012-07-27 15:51:34 -0700303 // True if dreams are supported on this device.
304 private boolean mDreamsSupportedConfig;
305
John Spurlocked108f32012-10-18 16:49:24 -0400306 // Default value for dreams enabled
307 private boolean mDreamsEnabledByDefaultConfig;
308
309 // Default value for dreams activate-on-sleep
310 private boolean mDreamsActivatedOnSleepByDefaultConfig;
311
312 // Default value for dreams activate-on-dock
313 private boolean mDreamsActivatedOnDockByDefaultConfig;
314
Jeff Brown26875502014-01-30 21:47:47 -0800315 // True if dreams can run while not plugged in.
316 private boolean mDreamsEnabledOnBatteryConfig;
317
318 // Minimum battery level to allow dreaming when powered.
319 // Use -1 to disable this safety feature.
320 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
321
322 // Minimum battery level to allow dreaming when not powered.
323 // Use -1 to disable this safety feature.
324 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
325
326 // If the battery level drops by this percentage and the user activity timeout
327 // has expired, then assume the device is receiving insufficient current to charge
328 // effectively and terminate the dream. Use -1 to disable this safety feature.
329 private int mDreamsBatteryLevelDrainCutoffConfig;
330
Jeff Brown96307042012-07-27 15:51:34 -0700331 // True if dreams are enabled by the user.
332 private boolean mDreamsEnabledSetting;
333
John Spurlock1a868b72012-08-22 09:56:51 -0400334 // True if dreams should be activated on sleep.
335 private boolean mDreamsActivateOnSleepSetting;
336
Jeff Brownec6aa592012-10-17 20:30:25 -0700337 // True if dreams should be activated on dock.
338 private boolean mDreamsActivateOnDockSetting;
339
Jeff Brown96307042012-07-27 15:51:34 -0700340 // The screen off timeout setting value in milliseconds.
341 private int mScreenOffTimeoutSetting;
342
343 // The maximum allowable screen off timeout according to the device
344 // administration policy. Overrides other settings.
345 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
346
347 // The stay on while plugged in setting.
348 // A bitfield of battery conditions under which to make the screen stay on.
349 private int mStayOnWhilePluggedInSetting;
350
351 // True if the device should stay on.
352 private boolean mStayOn;
353
Jeff Brown93cbbb22012-10-04 13:18:36 -0700354 // True if the proximity sensor reads a positive result.
355 private boolean mProximityPositive;
356
Jeff Brown96307042012-07-27 15:51:34 -0700357 // Screen brightness setting limits.
358 private int mScreenBrightnessSettingMinimum;
359 private int mScreenBrightnessSettingMaximum;
360 private int mScreenBrightnessSettingDefault;
361
362 // The screen brightness setting, from 0 to 255.
363 // Use -1 if no value has been set.
364 private int mScreenBrightnessSetting;
365
Jeff Brown330560f2012-08-21 22:10:57 -0700366 // The screen auto-brightness adjustment setting, from -1 to 1.
367 // Use 0 if there is no adjustment.
368 private float mScreenAutoBrightnessAdjustmentSetting;
369
Jeff Brown96307042012-07-27 15:51:34 -0700370 // The screen brightness mode.
371 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
372 private int mScreenBrightnessModeSetting;
373
374 // The screen brightness setting override from the window manager
375 // to allow the current foreground activity to override the brightness.
376 // Use -1 to disable.
377 private int mScreenBrightnessOverrideFromWindowManager = -1;
378
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700379 // The user activity timeout override from the window manager
380 // to allow the current foreground activity to override the user activity timeout.
381 // Use -1 to disable.
382 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
383
Jeff Brown96307042012-07-27 15:51:34 -0700384 // The screen brightness setting override from the settings application
385 // to temporarily adjust the brightness until next updated,
386 // Use -1 to disable.
387 private int mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388
Jeff Brown330560f2012-08-21 22:10:57 -0700389 // The screen brightness adjustment setting override from the settings
390 // application to temporarily adjust the auto-brightness adjustment factor
391 // until next updated, in the range -1..1.
392 // Use NaN to disable.
393 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
394
Jeff Brown9ba8d782012-10-01 16:38:23 -0700395 // Time when we last logged a warning about calling userActivity() without permission.
396 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
397
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700398 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399
Jeff Brown96307042012-07-27 15:51:34 -0700400 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright);
401 private static native void nativeAcquireSuspendBlocker(String name);
402 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700403 private static native void nativeSetInteractive(boolean enable);
404 private static native void nativeSetAutoSuspend(boolean enable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405
Jeff Brownb880d882014-02-10 19:47:07 -0800406 public PowerManagerService(Context context) {
407 super(context);
408 mContext = context;
Jeff Brown96307042012-07-27 15:51:34 -0700409 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800410 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
411 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
412 mDisplaySuspendBlocker.acquire();
413 mHoldingDisplaySuspendBlocker = true;
414
Jeff Brownc38c9be2012-10-04 13:16:19 -0700415 mScreenOnBlocker = new ScreenOnBlockerImpl();
Jeff Brown96307042012-07-27 15:51:34 -0700416 mWakefulness = WAKEFULNESS_AWAKE;
417 }
Jeff Brown7304c342012-05-11 18:42:42 -0700418
419 nativeInit();
Jeff Brownf75724b2012-08-25 13:34:32 -0700420 nativeSetPowerState(true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 }
422
Jeff Brown6f357d32014-01-15 20:40:55 -0800423 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800424 public void onStart() {
425 publishBinderService(Context.POWER_SERVICE, new BinderService());
426 publishLocalService(PowerManagerInternal.class, new LocalService());
427 }
428
Jeff Brown96307042012-07-27 15:51:34 -0700429 /**
430 * Initialize the power manager.
431 * Must be called before any other functions within the power manager are called.
432 */
Jeff Brown6f357d32014-01-15 20:40:55 -0800433 public void init(LightsManager ls,
Adam Lesinski182f73f2013-12-05 16:48:06 -0800434 BatteryService bs, IBatteryStats bss,
Jeff Brown4ccb8232014-01-16 22:16:42 -0800435 IAppOpsService appOps) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800436 mLightsManager = ls;
Jeff Brown9e316a12012-10-08 19:17:06 -0700437 mBatteryService = bs;
438 mBatteryStats = bss;
Dianne Hackborn713df152013-05-17 11:27:57 -0700439 mAppOps = appOps;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800440 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
441 mHandlerThread = new ServiceThread(TAG,
442 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
Jeff Brown9e316a12012-10-08 19:17:06 -0700443 mHandlerThread.start();
444 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
445
446 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800447 Watchdog.getInstance().addThread(mHandler);
Jeff Brown9e316a12012-10-08 19:17:06 -0700448
Jeff Brownf75724b2012-08-25 13:34:32 -0700449 // Forcibly turn the screen on at boot so that it is in a known power state.
450 // We do this in init() rather than in the constructor because setting the
451 // screen state requires a call into surface flinger which then needs to call back
452 // into the activity manager to check permissions. Unfortunately the
453 // activity manager is not running when the constructor is called, so we
454 // have to defer setting the screen state until this point.
Jeff Brownad9ef192014-04-08 17:26:30 -0700455 mDisplayPowerCallbacks.unblankAllDisplays();
Jeff Brown96307042012-07-27 15:51:34 -0700456 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800457
Jeff Brown6f357d32014-01-15 20:40:55 -0800458 void setPolicy(WindowManagerPolicy policy) {
Jeff Brown96307042012-07-27 15:51:34 -0700459 synchronized (mLock) {
460 mPolicy = policy;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800463
Jeff Brown567f7ca2014-01-30 23:38:03 -0800464 public void systemReady() {
Jeff Brown96307042012-07-27 15:51:34 -0700465 synchronized (mLock) {
466 mSystemReady = true;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800467 mDreamManager = LocalServices.getService(DreamManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468
Adam Lesinski182f73f2013-12-05 16:48:06 -0800469 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700470 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
471 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
472 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700474 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800475
Jeff Brownc38c9be2012-10-04 13:16:19 -0700476 // The notifier runs on the system server's main looper so as not to interfere
477 // with the animations and other critical functions of the power manager.
478 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700479 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brownc38c9be2012-10-04 13:16:19 -0700480 mScreenOnBlocker, mPolicy);
481
Jeff Brown3b971592013-01-09 18:46:37 -0800482 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700483 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
484 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700485 mSettingsObserver = new SettingsObserver(mHandler);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800486 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400487
Jeff Brownad9ef192014-04-08 17:26:30 -0700488 // Initialize display power management.
489 mDisplayManagerInternal.initPowerManagement(
490 mDisplayPowerCallbacks, mHandler, sensorManager);
491
Jeff Brown96307042012-07-27 15:51:34 -0700492 // Register for broadcasts from other components of the system.
493 IntentFilter filter = new IntentFilter();
494 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Jeff Brownd4935962012-09-25 13:27:20 -0700495 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700496
Jeff Brown96307042012-07-27 15:51:34 -0700497 filter = new IntentFilter();
498 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
Jeff Brownd4935962012-09-25 13:27:20 -0700499 mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700500
501 filter = new IntentFilter();
Dianne Hackbornbe87e2f2012-09-28 16:31:34 -0700502 filter.addAction(Intent.ACTION_DREAMING_STARTED);
503 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
Jeff Brownd4935962012-09-25 13:27:20 -0700504 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
505
506 filter = new IntentFilter();
507 filter.addAction(Intent.ACTION_USER_SWITCHED);
508 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
John Spurlockf4f6b4c2012-08-25 12:08:03 -0400509
Jeff Brownec6aa592012-10-17 20:30:25 -0700510 filter = new IntentFilter();
511 filter.addAction(Intent.ACTION_DOCK_EVENT);
512 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
513
Jeff Brown96307042012-07-27 15:51:34 -0700514 // Register for settings changes.
515 final ContentResolver resolver = mContext.getContentResolver();
516 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700517 Settings.Secure.SCREENSAVER_ENABLED),
518 false, mSettingsObserver, UserHandle.USER_ALL);
John Spurlock1a868b72012-08-22 09:56:51 -0400519 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700520 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
521 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brownec6aa592012-10-17 20:30:25 -0700522 resolver.registerContentObserver(Settings.Secure.getUriFor(
523 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
524 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700525 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700526 Settings.System.SCREEN_OFF_TIMEOUT),
527 false, mSettingsObserver, UserHandle.USER_ALL);
Christopher Tatead735322012-09-07 14:19:43 -0700528 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700529 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
530 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700531 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700532 Settings.System.SCREEN_BRIGHTNESS),
533 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700534 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700535 Settings.System.SCREEN_BRIGHTNESS_MODE),
536 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700537
538 // Go.
539 readConfigurationLocked();
540 updateSettingsLocked();
541 mDirty |= DIRTY_BATTERY_STATE;
542 updatePowerStateLocked();
543 }
544 }
545
546 private void readConfigurationLocked() {
547 final Resources resources = mContext.getResources();
548
Jeff Brown26875502014-01-30 21:47:47 -0800549 mDecoupleAutoSuspendModeFromDisplayConfig = resources.getBoolean(
550 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
551 mDecoupleInteractiveModeFromDisplayConfig = resources.getBoolean(
552 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700553 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700554 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Jeff Brownec083212013-09-11 20:45:25 -0700555 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
556 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700557 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400558 com.android.internal.R.bool.config_dreamsSupported);
559 mDreamsEnabledByDefaultConfig = resources.getBoolean(
560 com.android.internal.R.bool.config_dreamsEnabledByDefault);
561 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
562 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
563 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
564 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800565 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
566 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
567 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
568 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
569 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
570 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
571 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
572 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574
Jeff Brown96307042012-07-27 15:51:34 -0700575 private void updateSettingsLocked() {
576 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700577
Jeff Brownd4935962012-09-25 13:27:20 -0700578 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400579 Settings.Secure.SCREENSAVER_ENABLED,
580 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700581 UserHandle.USER_CURRENT) != 0);
582 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400583 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
584 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700585 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700586 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400587 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
588 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700589 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700590 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
591 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
592 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700593 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700594 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Jeff Brown7304c342012-05-11 18:42:42 -0700595
Jeff Brown96307042012-07-27 15:51:34 -0700596 final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700597 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
598 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
599 UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700600 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
601 mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 }
Jeff Brown96307042012-07-27 15:51:34 -0700603
Jeff Brown330560f2012-08-21 22:10:57 -0700604 final float oldScreenAutoBrightnessAdjustmentSetting =
605 mScreenAutoBrightnessAdjustmentSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700606 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
607 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
608 UserHandle.USER_CURRENT);
Jeff Brown330560f2012-08-21 22:10:57 -0700609 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
Jeff Brown5d03a532012-08-22 13:22:02 -0700610 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
Jeff Brown330560f2012-08-21 22:10:57 -0700611 }
612
Jeff Brownd4935962012-09-25 13:27:20 -0700613 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700614 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700615 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700616
617 mDirty |= DIRTY_SETTINGS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
619
Jeff Brown96307042012-07-27 15:51:34 -0700620 private void handleSettingsChangedLocked() {
621 updateSettingsLocked();
622 updatePowerStateLocked();
623 }
624
Dianne Hackborn713df152013-05-17 11:27:57 -0700625 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
626 WorkSource ws, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700627 synchronized (mLock) {
628 if (DEBUG_SPEW) {
629 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
630 + ", flags=0x" + Integer.toHexString(flags)
631 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633
Jeff Brown96307042012-07-27 15:51:34 -0700634 WakeLock wakeLock;
635 int index = findWakeLockIndexLocked(lock);
636 if (index >= 0) {
637 wakeLock = mWakeLocks.get(index);
638 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
639 // Update existing wake lock. This shouldn't happen but is harmless.
640 notifyWakeLockReleasedLocked(wakeLock);
Dianne Hackborn713df152013-05-17 11:27:57 -0700641 wakeLock.updateProperties(flags, tag, packageName, ws, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700642 notifyWakeLockAcquiredLocked(wakeLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 } else {
Dianne Hackborn713df152013-05-17 11:27:57 -0700645 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700646 try {
647 lock.linkToDeath(wakeLock, 0);
648 } catch (RemoteException ex) {
649 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
Jeff Brown96307042012-07-27 15:51:34 -0700651 notifyWakeLockAcquiredLocked(wakeLock);
652 mWakeLocks.add(wakeLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654
Jeff Brown96307042012-07-27 15:51:34 -0700655 applyWakeLockFlagsOnAcquireLocked(wakeLock);
656 mDirty |= DIRTY_WAKE_LOCKS;
657 updatePowerStateLocked();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700658 }
659 }
660
Jeff Brownec083212013-09-11 20:45:25 -0700661 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -0800662 private static boolean isScreenLock(final WakeLock wakeLock) {
663 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
664 case PowerManager.FULL_WAKE_LOCK:
665 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
666 case PowerManager.SCREEN_DIM_WAKE_LOCK:
667 return true;
668 }
669 return false;
670 }
671
Jeff Brown96307042012-07-27 15:51:34 -0700672 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700673 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
674 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700675 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677 }
678
Jeff Brown96307042012-07-27 15:51:34 -0700679 private void releaseWakeLockInternal(IBinder lock, int flags) {
680 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -0700681 int index = findWakeLockIndexLocked(lock);
682 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800683 if (DEBUG_SPEW) {
684 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
685 + " [not found], flags=0x" + Integer.toHexString(flags));
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 return;
688 }
Mike Lockwood3333fa42009-10-26 14:50:42 -0400689
Jeff Brown96307042012-07-27 15:51:34 -0700690 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800691 if (DEBUG_SPEW) {
692 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
693 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
694 }
695
Jeff Brown96307042012-07-27 15:51:34 -0700696 mWakeLocks.remove(index);
697 notifyWakeLockReleasedLocked(wakeLock);
698 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
699
700 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) {
701 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
703
Jeff Brown96307042012-07-27 15:51:34 -0700704 applyWakeLockFlagsOnReleaseLocked(wakeLock);
705 mDirty |= DIRTY_WAKE_LOCKS;
706 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
708 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700709
Jeff Brown96307042012-07-27 15:51:34 -0700710 private void handleWakeLockDeath(WakeLock wakeLock) {
711 synchronized (mLock) {
712 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800713 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
714 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -0700715 }
716
717 int index = mWakeLocks.indexOf(wakeLock);
718 if (index < 0) {
719 return;
720 }
721
722 mWakeLocks.remove(index);
723 notifyWakeLockReleasedLocked(wakeLock);
724
725 applyWakeLockFlagsOnReleaseLocked(wakeLock);
726 mDirty |= DIRTY_WAKE_LOCKS;
727 updatePowerStateLocked();
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700728 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800730
Jeff Brown96307042012-07-27 15:51:34 -0700731 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700732 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
733 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700734 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
735 PowerManager.USER_ACTIVITY_EVENT_OTHER,
736 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
737 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 }
740
Jeff Brown96307042012-07-27 15:51:34 -0700741 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) {
742 synchronized (mLock) {
743 int index = findWakeLockIndexLocked(lock);
744 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800745 if (DEBUG_SPEW) {
746 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
747 + " [not found], ws=" + ws);
748 }
Jeff Brown96307042012-07-27 15:51:34 -0700749 throw new IllegalArgumentException("Wake lock not active");
750 }
751
752 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800753 if (DEBUG_SPEW) {
754 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
755 + " [" + wakeLock.mTag + "], ws=" + ws);
756 }
757
Jeff Brown96307042012-07-27 15:51:34 -0700758 if (!wakeLock.hasSameWorkSource(ws)) {
759 notifyWakeLockReleasedLocked(wakeLock);
760 wakeLock.updateWorkSource(ws);
761 notifyWakeLockAcquiredLocked(wakeLock);
762 }
763 }
764 }
765
766 private int findWakeLockIndexLocked(IBinder lock) {
767 final int count = mWakeLocks.size();
768 for (int i = 0; i < count; i++) {
769 if (mWakeLocks.get(i).mLock == lock) {
770 return i;
771 }
772 }
773 return -1;
774 }
775
776 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
777 if (mSystemReady) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700778 wakeLock.mNotifiedAcquired = true;
779 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Jeff Brown96307042012-07-27 15:51:34 -0700780 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
781 }
782 }
783
784 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700785 if (mSystemReady && wakeLock.mNotifiedAcquired) {
786 wakeLock.mNotifiedAcquired = false;
787 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Jeff Brown96307042012-07-27 15:51:34 -0700788 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
789 }
790 }
791
Jeff Brownec083212013-09-11 20:45:25 -0700792 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700793 private boolean isWakeLockLevelSupportedInternal(int level) {
794 synchronized (mLock) {
795 switch (level) {
796 case PowerManager.PARTIAL_WAKE_LOCK:
797 case PowerManager.SCREEN_DIM_WAKE_LOCK:
798 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
799 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -0800800 case PowerManager.DOZE_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700801 return true;
Jeff Brown96307042012-07-27 15:51:34 -0700802
803 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brownad9ef192014-04-08 17:26:30 -0700804 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -0700805
806 default:
807 return false;
808 }
809 }
810 }
811
Jeff Brown96307042012-07-27 15:51:34 -0700812 // Called from native code.
813 private void userActivityFromNative(long eventTime, int event, int flags) {
814 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
815 }
816
817 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
818 synchronized (mLock) {
819 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
820 updatePowerStateLocked();
821 }
822 }
823 }
824
825 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
826 if (DEBUG_SPEW) {
827 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
828 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
829 + ", uid=" + uid);
830 }
831
832 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -0800833 || mWakefulness == WAKEFULNESS_ASLEEP || mWakefulness == WAKEFULNESS_DOZING
834 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -0700835 return false;
836 }
837
838 mNotifier.onUserActivity(event, uid);
839
840 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
841 if (eventTime > mLastUserActivityTimeNoChangeLights
842 && eventTime > mLastUserActivityTime) {
843 mLastUserActivityTimeNoChangeLights = eventTime;
844 mDirty |= DIRTY_USER_ACTIVITY;
845 return true;
846 }
847 } else {
848 if (eventTime > mLastUserActivityTime) {
849 mLastUserActivityTime = eventTime;
850 mDirty |= DIRTY_USER_ACTIVITY;
851 return true;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700852 }
853 }
854 return false;
855 }
856
Jeff Brown96307042012-07-27 15:51:34 -0700857 // Called from native code.
858 private void wakeUpFromNative(long eventTime) {
859 wakeUpInternal(eventTime);
860 }
861
862 private void wakeUpInternal(long eventTime) {
863 synchronized (mLock) {
864 if (wakeUpNoUpdateLocked(eventTime)) {
865 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700866 }
867 }
Jeff Brown96307042012-07-27 15:51:34 -0700868 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700869
Jeff Brown96307042012-07-27 15:51:34 -0700870 private boolean wakeUpNoUpdateLocked(long eventTime) {
871 if (DEBUG_SPEW) {
872 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime);
Joe Onorato60607a92010-10-23 14:49:30 -0700873 }
Jeff Brown96307042012-07-27 15:51:34 -0700874
875 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
876 || !mBootCompleted || !mSystemReady) {
877 return false;
878 }
879
880 switch (mWakefulness) {
881 case WAKEFULNESS_ASLEEP:
882 Slog.i(TAG, "Waking up from sleep...");
Jeff Brown96307042012-07-27 15:51:34 -0700883 break;
884 case WAKEFULNESS_DREAMING:
885 Slog.i(TAG, "Waking up from dream...");
886 break;
Jeff Brown26875502014-01-30 21:47:47 -0800887 case WAKEFULNESS_DOZING:
888 Slog.i(TAG, "Waking up from dozing...");
Jeff Brown96307042012-07-27 15:51:34 -0700889 break;
890 }
891
Jeff Brown26875502014-01-30 21:47:47 -0800892 if (mWakefulness != WAKEFULNESS_DREAMING) {
893 sendPendingNotificationsLocked();
894 mNotifier.onWakeUpStarted();
895 mSendWakeUpFinishedNotificationWhenReady = true;
896 }
897
Jeff Brown96307042012-07-27 15:51:34 -0700898 mLastWakeTime = eventTime;
899 mWakefulness = WAKEFULNESS_AWAKE;
900 mDirty |= DIRTY_WAKEFULNESS;
901
902 userActivityNoUpdateLocked(
903 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
904 return true;
905 }
906
Jeff Brown96307042012-07-27 15:51:34 -0700907 // Called from native code.
908 private void goToSleepFromNative(long eventTime, int reason) {
909 goToSleepInternal(eventTime, reason);
910 }
911
912 private void goToSleepInternal(long eventTime, int reason) {
913 synchronized (mLock) {
914 if (goToSleepNoUpdateLocked(eventTime, reason)) {
915 updatePowerStateLocked();
916 }
917 }
918 }
919
Jeff Brown26875502014-01-30 21:47:47 -0800920 // This method is called goToSleep for historical reasons but we actually start
921 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -0700922 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700923 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) {
924 if (DEBUG_SPEW) {
925 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason);
926 }
927
Jeff Brown26875502014-01-30 21:47:47 -0800928 if (eventTime < mLastWakeTime
929 || mWakefulness == WAKEFULNESS_ASLEEP
930 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -0700931 || !mBootCompleted || !mSystemReady) {
932 return false;
933 }
934
935 switch (reason) {
936 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
937 Slog.i(TAG, "Going to sleep due to device administration policy...");
938 break;
939 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
940 Slog.i(TAG, "Going to sleep due to screen timeout...");
941 break;
942 default:
943 Slog.i(TAG, "Going to sleep by user request...");
944 reason = PowerManager.GO_TO_SLEEP_REASON_USER;
945 break;
946 }
947
Jeff Brown54308352012-10-04 17:59:58 -0700948 sendPendingNotificationsLocked();
949 mNotifier.onGoToSleepStarted(reason);
950 mSendGoToSleepFinishedNotificationWhenReady = true;
951
Jeff Brown96307042012-07-27 15:51:34 -0700952 mLastSleepTime = eventTime;
953 mDirty |= DIRTY_WAKEFULNESS;
Jeff Brown26875502014-01-30 21:47:47 -0800954 mWakefulness = WAKEFULNESS_DOZING;
955 mSandmanSummoned = true;
Jeff Brown96307042012-07-27 15:51:34 -0700956
957 // Report the number of wake locks that will be cleared by going to sleep.
958 int numWakeLocksCleared = 0;
959 final int numWakeLocks = mWakeLocks.size();
960 for (int i = 0; i < numWakeLocks; i++) {
961 final WakeLock wakeLock = mWakeLocks.get(i);
962 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
963 case PowerManager.FULL_WAKE_LOCK:
964 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
965 case PowerManager.SCREEN_DIM_WAKE_LOCK:
966 numWakeLocksCleared += 1;
967 break;
968 }
969 }
970 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
971 return true;
972 }
973
Jeff Brown62c82e42012-09-26 01:30:41 -0700974 private void napInternal(long eventTime) {
975 synchronized (mLock) {
976 if (napNoUpdateLocked(eventTime)) {
977 updatePowerStateLocked();
978 }
979 }
980 }
981
982 private boolean napNoUpdateLocked(long eventTime) {
983 if (DEBUG_SPEW) {
984 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime);
985 }
986
987 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
988 || !mBootCompleted || !mSystemReady) {
989 return false;
990 }
991
992 Slog.i(TAG, "Nap time...");
993
994 mDirty |= DIRTY_WAKEFULNESS;
Jeff Brown26875502014-01-30 21:47:47 -0800995 mWakefulness = WAKEFULNESS_DREAMING;
996 mSandmanSummoned = true;
997 return true;
998 }
999
1000 // Done dozing, drop everything and go to sleep.
1001 private boolean reallyGoToSleepNoUpdateLocked(long eventTime) {
1002 if (DEBUG_SPEW) {
1003 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime);
1004 }
1005
1006 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1007 || !mBootCompleted || !mSystemReady) {
1008 return false;
1009 }
1010
1011 Slog.i(TAG, "Sleeping...");
1012
1013 mDirty |= DIRTY_WAKEFULNESS;
1014 mWakefulness = WAKEFULNESS_ASLEEP;
Jeff Brown62c82e42012-09-26 01:30:41 -07001015 return true;
1016 }
1017
Jeff Brown96307042012-07-27 15:51:34 -07001018 /**
1019 * Updates the global power state based on dirty bits recorded in mDirty.
1020 *
1021 * This is the main function that performs power state transitions.
1022 * We centralize them here so that we can recompute the power state completely
1023 * each time something important changes, and ensure that we do it the same
1024 * way each time. The point is to gather all of the transition logic here.
1025 */
1026 private void updatePowerStateLocked() {
1027 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001028 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001030 if (!Thread.holdsLock(mLock)) {
1031 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1032 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001033
Jeff Brown96307042012-07-27 15:51:34 -07001034 // Phase 0: Basic state updates.
1035 updateIsPoweredLocked(mDirty);
1036 updateStayOnLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037
Jeff Brown96307042012-07-27 15:51:34 -07001038 // Phase 1: Update wakefulness.
1039 // Loop because the wake lock and user activity computations are influenced
1040 // by changes in wakefulness.
1041 final long now = SystemClock.uptimeMillis();
1042 int dirtyPhase2 = 0;
1043 for (;;) {
1044 int dirtyPhase1 = mDirty;
1045 dirtyPhase2 |= dirtyPhase1;
1046 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001047
Jeff Brown96307042012-07-27 15:51:34 -07001048 updateWakeLockSummaryLocked(dirtyPhase1);
1049 updateUserActivitySummaryLocked(now, dirtyPhase1);
1050 if (!updateWakefulnessLocked(dirtyPhase1)) {
1051 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
1053 }
1054
Jeff Brown96307042012-07-27 15:51:34 -07001055 // Phase 2: Update dreams and display power state.
1056 updateDreamLocked(dirtyPhase2);
1057 updateDisplayPowerStateLocked(dirtyPhase2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058
Jeff Brown96307042012-07-27 15:51:34 -07001059 // Phase 3: Send notifications, if needed.
Jeff Brown54308352012-10-04 17:59:58 -07001060 if (mDisplayReady) {
1061 sendPendingNotificationsLocked();
1062 }
Craig Mautner75fc9de2012-06-18 16:53:27 -07001063
Jeff Brown96307042012-07-27 15:51:34 -07001064 // Phase 4: Update suspend blocker.
1065 // Because we might release the last suspend blocker here, we need to make sure
1066 // we finished everything else first!
1067 updateSuspendBlockerLocked();
1068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001069
Jeff Brown96307042012-07-27 15:51:34 -07001070 private void sendPendingNotificationsLocked() {
Jeff Brown54308352012-10-04 17:59:58 -07001071 if (mSendWakeUpFinishedNotificationWhenReady) {
1072 mSendWakeUpFinishedNotificationWhenReady = false;
1073 mNotifier.onWakeUpFinished();
1074 }
1075 if (mSendGoToSleepFinishedNotificationWhenReady) {
1076 mSendGoToSleepFinishedNotificationWhenReady = false;
1077 mNotifier.onGoToSleepFinished();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080
Jim Miller92e66dd2012-02-21 18:57:12 -08001081 /**
Jeff Brown96307042012-07-27 15:51:34 -07001082 * Updates the value of mIsPowered.
1083 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001084 */
Jeff Brown96307042012-07-27 15:51:34 -07001085 private void updateIsPoweredLocked(int dirty) {
1086 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001087 final boolean wasPowered = mIsPowered;
1088 final int oldPlugType = mPlugType;
Jeff Browna4d82042012-10-02 19:11:19 -07001089 mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
Jeff Brownf3fb8952012-10-02 20:57:05 -07001090 mPlugType = mBatteryService.getPlugType();
Jeff Brown016ff142012-10-15 16:47:22 -07001091 mBatteryLevel = mBatteryService.getBatteryLevel();
Jeff Browna4d82042012-10-02 19:11:19 -07001092
Jeff Brown26875502014-01-30 21:47:47 -08001093 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001094 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001095 + ", mIsPowered=" + mIsPowered
1096 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001097 + ", mPlugType=" + mPlugType
1098 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001099 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001100
Jeff Brownf3fb8952012-10-02 20:57:05 -07001101 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001102 mDirty |= DIRTY_IS_POWERED;
1103
Jeff Brown3b971592013-01-09 18:46:37 -08001104 // Update wireless dock detection state.
1105 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1106 mIsPowered, mPlugType, mBatteryLevel);
1107
Jeff Brown96307042012-07-27 15:51:34 -07001108 // Treat plugging and unplugging the devices as a user activity.
1109 // Users find it disconcerting when they plug or unplug the device
1110 // and it shuts off right away.
1111 // Some devices also wake the device when plugged or unplugged because
1112 // they don't have a charging LED.
1113 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001114 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1115 dockedOnWirelessCharger)) {
Jeff Brown96307042012-07-27 15:51:34 -07001116 wakeUpNoUpdateLocked(now);
1117 }
1118 userActivityNoUpdateLocked(
1119 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001120
1121 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001122 // it can provide feedback to the user.
1123 if (dockedOnWirelessCharger) {
Jeff Brown84e27562012-12-07 13:56:34 -08001124 mNotifier.onWirelessChargingStarted();
1125 }
Jeff Brown96307042012-07-27 15:51:34 -07001126 }
1127 }
1128 }
1129
Jeff Brown3b971592013-01-09 18:46:37 -08001130 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1131 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001132 // Don't wake when powered unless configured to do so.
1133 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1134 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001135 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001136
Jeff Brown3b971592013-01-09 18:46:37 -08001137 // Don't wake when undocked from wireless charger.
1138 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001139 if (wasPowered && !mIsPowered
1140 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1141 return false;
1142 }
Jeff Brown3b971592013-01-09 18:46:37 -08001143
1144 // Don't wake when docked on wireless charger unless we are certain of it.
1145 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001146 if (!wasPowered && mIsPowered
1147 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001148 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001149 return false;
1150 }
1151
1152 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001153 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001154 return false;
1155 }
1156
1157 // Otherwise wake up!
1158 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001159 }
1160
Jeff Brown96307042012-07-27 15:51:34 -07001161 /**
1162 * Updates the value of mStayOn.
1163 * Sets DIRTY_STAY_ON if a change occurred.
1164 */
1165 private void updateStayOnLocked(int dirty) {
1166 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001167 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001168 if (mStayOnWhilePluggedInSetting != 0
1169 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1170 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
1171 } else {
1172 mStayOn = false;
1173 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001174
1175 if (mStayOn != wasStayOn) {
1176 mDirty |= DIRTY_STAY_ON;
1177 }
Jeff Brown96307042012-07-27 15:51:34 -07001178 }
1179 }
1180
1181 /**
1182 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1183 * Note that most wake-locks are ignored when the system is asleep.
1184 *
1185 * This function must have no other side-effects.
1186 */
Jeff Brownec083212013-09-11 20:45:25 -07001187 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001188 private void updateWakeLockSummaryLocked(int dirty) {
1189 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1190 mWakeLockSummary = 0;
1191
1192 final int numWakeLocks = mWakeLocks.size();
1193 for (int i = 0; i < numWakeLocks; i++) {
1194 final WakeLock wakeLock = mWakeLocks.get(i);
1195 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1196 case PowerManager.PARTIAL_WAKE_LOCK:
1197 mWakeLockSummary |= WAKE_LOCK_CPU;
1198 break;
1199 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001200 if (mWakefulness == WAKEFULNESS_AWAKE
1201 || mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown96307042012-07-27 15:51:34 -07001202 mWakeLockSummary |= WAKE_LOCK_CPU
1203 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
Jeff Brown26875502014-01-30 21:47:47 -08001204 }
1205 if (mWakefulness == WAKEFULNESS_AWAKE) {
1206 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
Jeff Brown96307042012-07-27 15:51:34 -07001207 }
1208 break;
1209 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001210 if (mWakefulness == WAKEFULNESS_AWAKE
1211 || mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown96307042012-07-27 15:51:34 -07001212 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT;
Jeff Brown26875502014-01-30 21:47:47 -08001213 }
1214 if (mWakefulness == WAKEFULNESS_AWAKE) {
1215 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
Jeff Brown96307042012-07-27 15:51:34 -07001216 }
1217 break;
1218 case PowerManager.SCREEN_DIM_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001219 if (mWakefulness == WAKEFULNESS_AWAKE
1220 || mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown96307042012-07-27 15:51:34 -07001221 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM;
Jeff Brown26875502014-01-30 21:47:47 -08001222 }
1223 if (mWakefulness == WAKEFULNESS_AWAKE) {
1224 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
Jeff Brown96307042012-07-27 15:51:34 -07001225 }
1226 break;
1227 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001228 if (mWakefulness == WAKEFULNESS_AWAKE
1229 || mWakefulness == WAKEFULNESS_DREAMING
1230 || mWakefulness == WAKEFULNESS_DOZING) {
Jeff Brownec083212013-09-11 20:45:25 -07001231 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001232 }
1233 break;
Jeff Brown26875502014-01-30 21:47:47 -08001234 case PowerManager.DOZE_WAKE_LOCK:
1235 if (mWakefulness == WAKEFULNESS_DOZING) {
1236 mWakeLockSummary |= WAKE_LOCK_DOZE;
1237 }
1238 break;
Jeff Brown96307042012-07-27 15:51:34 -07001239 }
1240 }
1241
1242 if (DEBUG_SPEW) {
1243 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1244 + wakefulnessToString(mWakefulness)
1245 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1246 }
1247 }
1248 }
1249
1250 /**
1251 * Updates the value of mUserActivitySummary to summarize the user requested
1252 * state of the system such as whether the screen should be bright or dim.
1253 * Note that user activity is ignored when the system is asleep.
1254 *
1255 * This function must have no other side-effects.
1256 */
1257 private void updateUserActivitySummaryLocked(long now, int dirty) {
1258 // Update the status of the user activity timeout timer.
1259 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
1260 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1261
1262 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001263 if (mWakefulness == WAKEFULNESS_AWAKE
1264 || mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown96307042012-07-27 15:51:34 -07001265 final int screenOffTimeout = getScreenOffTimeoutLocked();
Jeff Brownff532542012-10-02 21:18:04 -07001266 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07001267
1268 mUserActivitySummary = 0;
1269 if (mLastUserActivityTime >= mLastWakeTime) {
1270 nextTimeout = mLastUserActivityTime
1271 + screenOffTimeout - screenDimDuration;
1272 if (now < nextTimeout) {
1273 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
1274 } else {
1275 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1276 if (now < nextTimeout) {
1277 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
1278 }
1279 }
1280 }
1281 if (mUserActivitySummary == 0
1282 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1283 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
1284 if (now < nextTimeout
Jeff Brown26875502014-01-30 21:47:47 -08001285 && mDisplayPowerRequest.wantScreenOnNormal()) {
Jeff Brown96307042012-07-27 15:51:34 -07001286 mUserActivitySummary = mDisplayPowerRequest.screenState
1287 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ?
1288 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM;
1289 }
1290 }
1291 if (mUserActivitySummary != 0) {
1292 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1293 msg.setAsynchronous(true);
1294 mHandler.sendMessageAtTime(msg, nextTimeout);
1295 }
1296 } else {
1297 mUserActivitySummary = 0;
1298 }
1299
1300 if (DEBUG_SPEW) {
1301 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1302 + wakefulnessToString(mWakefulness)
1303 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1304 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1305 }
1306 }
1307 }
1308
1309 /**
1310 * Called when a user activity timeout has occurred.
1311 * Simply indicates that something about user activity has changed so that the new
1312 * state can be recomputed when the power state is updated.
1313 *
1314 * This function must have no other side-effects besides setting the dirty
1315 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
1316 */
1317 private void handleUserActivityTimeout() { // runs on handler thread
1318 synchronized (mLock) {
1319 if (DEBUG_SPEW) {
1320 Slog.d(TAG, "handleUserActivityTimeout");
1321 }
1322
1323 mDirty |= DIRTY_USER_ACTIVITY;
1324 updatePowerStateLocked();
1325 }
1326 }
1327
1328 private int getScreenOffTimeoutLocked() {
1329 int timeout = mScreenOffTimeoutSetting;
1330 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1331 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1332 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001333 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1334 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1335 }
Jeff Brown96307042012-07-27 15:51:34 -07001336 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT);
1337 }
1338
Jeff Brownff532542012-10-02 21:18:04 -07001339 private int getScreenDimDurationLocked(int screenOffTimeout) {
1340 return Math.min(SCREEN_DIM_DURATION,
1341 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO));
Jeff Brown96307042012-07-27 15:51:34 -07001342 }
1343
1344 /**
1345 * Updates the wakefulness of the device.
1346 *
Jeff Brown26875502014-01-30 21:47:47 -08001347 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07001348 * based on the current wake locks and user activity state. It may modify mDirty
1349 * if the wakefulness changes.
1350 *
1351 * Returns true if the wakefulness changed and we need to restart power state calculation.
1352 */
1353 private boolean updateWakefulnessLocked(int dirty) {
1354 boolean changed = false;
1355 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07001356 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1357 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001358 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1359 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001360 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07001361 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001362 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07001363 if (shouldNapAtBedTimeLocked()) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001364 changed = napNoUpdateLocked(time);
1365 } else {
1366 changed = goToSleepNoUpdateLocked(time,
1367 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1368 }
Jeff Brown96307042012-07-27 15:51:34 -07001369 }
1370 }
1371 return changed;
1372 }
1373
Jeff Brown645832d2012-10-03 14:57:03 -07001374 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07001375 * Returns true if the device should automatically nap and start dreaming when the user
1376 * activity timeout has expired and it's bedtime.
1377 */
1378 private boolean shouldNapAtBedTimeLocked() {
1379 return mDreamsActivateOnSleepSetting
1380 || (mDreamsActivateOnDockSetting
1381 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1382 }
1383
1384 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001385 * Returns true if the device should go to sleep now.
1386 * Also used when exiting a dream to determine whether we should go back
1387 * to being fully awake or else go to sleep for good.
1388 */
Jeff Brown96307042012-07-27 15:51:34 -07001389 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001390 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07001391 }
1392
1393 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07001394 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07001395 * or the stay on while powered setting. We also keep the phone awake when
1396 * the proximity sensor returns a positive result so that the device does not
1397 * lock while in a phone call. This function only controls whether the device
1398 * will go to sleep or dream which is independent of whether it will be allowed
1399 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07001400 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07001401 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001402 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07001403 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07001404 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07001405 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1406 | USER_ACTIVITY_SCREEN_DIM)) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07001407 }
1408
1409 /**
1410 * Determines whether to post a message to the sandman to update the dream state.
1411 */
1412 private void updateDreamLocked(int dirty) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001413 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07001414 | DIRTY_USER_ACTIVITY
1415 | DIRTY_WAKE_LOCKS
1416 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001417 | DIRTY_SETTINGS
1418 | DIRTY_IS_POWERED
1419 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07001420 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown62c82e42012-09-26 01:30:41 -07001421 | DIRTY_BATTERY_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001422 scheduleSandmanLocked();
1423 }
1424 }
1425
1426 private void scheduleSandmanLocked() {
1427 if (!mSandmanScheduled) {
1428 mSandmanScheduled = true;
1429 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1430 msg.setAsynchronous(true);
1431 mHandler.sendMessage(msg);
1432 }
1433 }
1434
1435 /**
Jeff Brown26875502014-01-30 21:47:47 -08001436 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07001437 *
1438 * We do this asynchronously because we must call out of the power manager to start
1439 * the dream and we don't want to hold our lock while doing so. There is a risk that
1440 * the device will wake or go to sleep in the meantime so we have to handle that case.
1441 */
1442 private void handleSandman() { // runs on handler thread
1443 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08001444 final boolean startDreaming;
1445 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07001446 synchronized (mLock) {
1447 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08001448 wakefulness = mWakefulness;
1449 if (mSandmanSummoned) {
1450 startDreaming = ((wakefulness == WAKEFULNESS_DREAMING && canDreamLocked())
1451 || wakefulness == WAKEFULNESS_DOZING);
1452 mSandmanSummoned = false;
1453 } else {
1454 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001455 }
1456 }
1457
Jeff Brown96307042012-07-27 15:51:34 -07001458 // Start dreaming if needed.
1459 // We only control the dream on the handler thread, so we don't need to worry about
1460 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08001461 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07001462 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08001463 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07001464 if (startDreaming) {
Jeff Brown26875502014-01-30 21:47:47 -08001465 mDreamManager.stopDream();
1466 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07001467 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001468 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08001469 } else {
1470 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07001471 }
1472
1473 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07001474 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08001475 // Remember the initial battery level when the dream started.
1476 if (startDreaming && isDreaming) {
1477 mBatteryLevelWhenDreamStarted = mBatteryLevel;
1478 if (wakefulness == WAKEFULNESS_DOZING) {
1479 Slog.i(TAG, "Dozing...");
1480 } else {
1481 Slog.i(TAG, "Dreaming...");
1482 }
1483 }
1484
1485 // If preconditions changed, wait for the next iteration to determine
1486 // whether the dream should continue (or be restarted).
1487 if (mSandmanSummoned || mWakefulness != wakefulness) {
1488 return; // wait for next cycle
1489 }
1490
1491 // Determine whether the dream should continue.
1492 if (wakefulness == WAKEFULNESS_DREAMING) {
1493 if (isDreaming && canDreamLocked()) {
1494 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07001495 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08001496 - mDreamsBatteryLevelDrainCutoffConfig
1497 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07001498 // If the user activity timeout expired and the battery appears
1499 // to be draining faster than it is charging then stop dreaming
1500 // and go to sleep.
1501 Slog.i(TAG, "Stopping dream because the battery appears to "
1502 + "be draining faster than it is charging. "
1503 + "Battery level when dream started: "
1504 + mBatteryLevelWhenDreamStarted + "%. "
1505 + "Battery level now: " + mBatteryLevel + "%.");
1506 } else {
Jeff Brown26875502014-01-30 21:47:47 -08001507 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07001508 }
Jeff Brown96307042012-07-27 15:51:34 -07001509 }
Jeff Brown26875502014-01-30 21:47:47 -08001510
1511 // Dream has ended or will be stopped. Update the power state.
1512 if (isItBedTimeYetLocked()) {
1513 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
1514 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1515 updatePowerStateLocked();
1516 } else {
1517 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
1518 updatePowerStateLocked();
1519 }
1520 } else if (wakefulness == WAKEFULNESS_DOZING) {
1521 if (isDreaming) {
1522 return; // continue dozing
1523 }
1524
1525 // Doze has ended or will be stopped. Update the power state.
1526 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis());
1527 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001528 }
Jeff Brown96307042012-07-27 15:51:34 -07001529 }
1530
Jeff Brown26875502014-01-30 21:47:47 -08001531 // Stop dream.
1532 if (isDreaming) {
1533 mDreamManager.stopDream();
Jeff Brown96307042012-07-27 15:51:34 -07001534 }
1535 }
1536
1537 /**
Jeff Brown26875502014-01-30 21:47:47 -08001538 * Returns true if the device is allowed to dream in its current state.
1539 * This function is not called when dozing.
Jeff Brown96307042012-07-27 15:51:34 -07001540 */
1541 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08001542 if (mWakefulness != WAKEFULNESS_DREAMING
1543 || !mDreamsSupportedConfig
1544 || !mDreamsEnabledSetting
1545 || !mDisplayPowerRequest.wantScreenOnNormal()
1546 || !mBootCompleted) {
1547 return false;
1548 }
1549 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08001550 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08001551 return false;
1552 }
1553 if (!mIsPowered
1554 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
1555 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
1556 return false;
1557 }
1558 if (mIsPowered
1559 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
1560 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
1561 return false;
Jeff Brown96307042012-07-27 15:51:34 -07001562 }
1563 }
Jeff Brown26875502014-01-30 21:47:47 -08001564 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001565 }
1566
Jeff Brownc38c9be2012-10-04 13:16:19 -07001567 private void handleScreenOnBlockerReleased() {
1568 synchronized (mLock) {
1569 mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
1570 updatePowerStateLocked();
1571 }
1572 }
1573
Jeff Brown96307042012-07-27 15:51:34 -07001574 /**
1575 * Updates the display power state asynchronously.
1576 * When the update is finished, mDisplayReady will be set to true. The display
1577 * controller posts a message to tell us when the actual display power state
1578 * has been updated so we come back here to double-check and finish up.
1579 *
1580 * This function recalculates the display power state each time.
1581 */
1582 private void updateDisplayPowerStateLocked(int dirty) {
1583 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1584 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Jeff Brownc38c9be2012-10-04 13:16:19 -07001585 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
Jeff Brown26875502014-01-30 21:47:47 -08001586 final int newScreenState = getDesiredScreenPowerStateLocked();
Jeff Brown4c7e6902014-02-27 21:11:31 -08001587 mDisplayPowerRequest.screenState = newScreenState;
1588 nativeSetPowerState(isScreenOnLocked(),
1589 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT);
Jeff Brown96307042012-07-27 15:51:34 -07001590
1591 int screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001592 float screenAutoBrightnessAdjustment = 0.0f;
Jeff Brown96307042012-07-27 15:51:34 -07001593 boolean autoBrightness = (mScreenBrightnessModeSetting ==
1594 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1595 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1596 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1597 autoBrightness = false;
1598 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1599 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1600 } else if (isValidBrightness(mScreenBrightnessSetting)) {
Jeff Brown330560f2012-08-21 22:10:57 -07001601 screenBrightness = mScreenBrightnessSetting;
Jeff Brown96307042012-07-27 15:51:34 -07001602 }
1603 if (autoBrightness) {
1604 screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001605 if (isValidAutoBrightnessAdjustment(
1606 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1607 screenAutoBrightnessAdjustment =
1608 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1609 } else if (isValidAutoBrightnessAdjustment(
1610 mScreenAutoBrightnessAdjustmentSetting)) {
1611 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1612 }
Jeff Brown96307042012-07-27 15:51:34 -07001613 }
1614 screenBrightness = Math.max(Math.min(screenBrightness,
1615 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
Jeff Brown330560f2012-08-21 22:10:57 -07001616 screenAutoBrightnessAdjustment = Math.max(Math.min(
1617 screenAutoBrightnessAdjustment, 1.0f), -1.0f);
Jeff Brown96307042012-07-27 15:51:34 -07001618 mDisplayPowerRequest.screenBrightness = screenBrightness;
Jeff Brown330560f2012-08-21 22:10:57 -07001619 mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1620 screenAutoBrightnessAdjustment;
Jeff Brown96307042012-07-27 15:51:34 -07001621 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
1622
1623 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
1624
Jeff Brownc38c9be2012-10-04 13:16:19 -07001625 mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
1626
Jeff Brownad9ef192014-04-08 17:26:30 -07001627 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown96307042012-07-27 15:51:34 -07001628 mRequestWaitForNegativeProximity);
1629 mRequestWaitForNegativeProximity = false;
1630
1631 if (DEBUG_SPEW) {
Jeff Brownc38c9be2012-10-04 13:16:19 -07001632 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown96307042012-07-27 15:51:34 -07001633 + ", newScreenState=" + newScreenState
1634 + ", mWakefulness=" + mWakefulness
1635 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1636 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1637 + ", mBootCompleted=" + mBootCompleted);
1638 }
1639 }
1640 }
1641
1642 private static boolean isValidBrightness(int value) {
1643 return value >= 0 && value <= 255;
1644 }
1645
Jeff Brown330560f2012-08-21 22:10:57 -07001646 private static boolean isValidAutoBrightnessAdjustment(float value) {
Jeff Brown5d03a532012-08-22 13:22:02 -07001647 // Handles NaN by always returning false.
1648 return value >= -1.0f && value <= 1.0f;
Jeff Brown330560f2012-08-21 22:10:57 -07001649 }
1650
Jeff Brownc38c9be2012-10-04 13:16:19 -07001651 private int getDesiredScreenPowerStateLocked() {
Jeff Brown96307042012-07-27 15:51:34 -07001652 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1653 return DisplayPowerRequest.SCREEN_STATE_OFF;
1654 }
1655
Jeff Brown26875502014-01-30 21:47:47 -08001656 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1657 return DisplayPowerRequest.SCREEN_STATE_DOZE;
1658 }
1659
Jeff Brown96307042012-07-27 15:51:34 -07001660 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1661 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1662 || !mBootCompleted) {
1663 return DisplayPowerRequest.SCREEN_STATE_BRIGHT;
1664 }
1665
1666 return DisplayPowerRequest.SCREEN_STATE_DIM;
1667 }
1668
Jeff Brownad9ef192014-04-08 17:26:30 -07001669 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
1670 new DisplayManagerInternal.DisplayPowerCallbacks() {
1671 private boolean mBlanked;
1672
Jeff Brown96307042012-07-27 15:51:34 -07001673 @Override
1674 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001675 synchronized (mLock) {
1676 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1677 updatePowerStateLocked();
1678 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001679 }
1680
1681 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07001682 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001683 synchronized (mLock) {
1684 mProximityPositive = true;
1685 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1686 updatePowerStateLocked();
1687 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001688 }
1689
1690 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001691 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001692 synchronized (mLock) {
1693 mProximityPositive = false;
1694 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1695 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1696 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1697 updatePowerStateLocked();
1698 }
Jeff Brown96307042012-07-27 15:51:34 -07001699 }
Jeff Brownad9ef192014-04-08 17:26:30 -07001700
1701 @Override
1702 public void acquireSuspendBlocker() {
1703 mDisplaySuspendBlocker.acquire();
1704 }
1705
1706 @Override
1707 public void releaseSuspendBlocker() {
1708 mDisplaySuspendBlocker.release();
1709 }
1710
1711 @Override
1712 public void blankAllDisplays() {
1713 synchronized (this) {
1714 mBlanked = true;
1715 mDisplayManagerInternal.blankAllDisplaysFromPowerManager();
1716 if (!mDecoupleInteractiveModeFromDisplayConfig) {
1717 setInteractiveModeLocked(false);
1718 }
1719 if (!mDecoupleAutoSuspendModeFromDisplayConfig) {
1720 setAutoSuspendModeLocked(true);
1721 }
1722 }
1723 }
1724
1725 @Override
1726 public void unblankAllDisplays() {
1727 synchronized (this) {
1728 if (!mDecoupleAutoSuspendModeFromDisplayConfig) {
1729 setAutoSuspendModeLocked(false);
1730 }
1731 if (!mDecoupleInteractiveModeFromDisplayConfig) {
1732 setInteractiveModeLocked(true);
1733 }
1734 mDisplayManagerInternal.unblankAllDisplaysFromPowerManager();
1735 mBlanked = false;
1736 }
1737 }
1738
1739 @Override
1740 public String toString() {
1741 synchronized (this) {
1742 return "blanked=" + mBlanked;
1743 }
1744 }
Jeff Brown96307042012-07-27 15:51:34 -07001745 };
Jim Miller92e66dd2012-02-21 18:57:12 -08001746
Jeff Brown96307042012-07-27 15:51:34 -07001747 private boolean shouldUseProximitySensorLocked() {
1748 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
1749 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001750
Jeff Brown96307042012-07-27 15:51:34 -07001751 /**
1752 * Updates the suspend blocker that keeps the CPU alive.
1753 *
1754 * This function must have no other side-effects.
1755 */
1756 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07001757 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08001758 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
1759 final boolean autoSuspend = !needDisplaySuspendBlocker;
1760
1761 // Disable auto-suspend if needed.
1762 if (!autoSuspend) {
1763 if (mDecoupleAutoSuspendModeFromDisplayConfig) {
1764 setAutoSuspendModeLocked(false);
1765 }
1766 if (mDecoupleInteractiveModeFromDisplayConfig) {
1767 setInteractiveModeLocked(true);
1768 }
1769 }
Jeff Brown27f7a862012-12-12 15:43:31 -08001770
1771 // First acquire suspend blockers if needed.
1772 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
1773 mWakeLockSuspendBlocker.acquire();
1774 mHoldingWakeLockSuspendBlocker = true;
1775 }
1776 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
1777 mDisplaySuspendBlocker.acquire();
1778 mHoldingDisplaySuspendBlocker = true;
1779 }
1780
1781 // Then release suspend blockers if needed.
1782 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
1783 mWakeLockSuspendBlocker.release();
1784 mHoldingWakeLockSuspendBlocker = false;
1785 }
1786 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
1787 mDisplaySuspendBlocker.release();
1788 mHoldingDisplaySuspendBlocker = false;
1789 }
Jeff Brown26875502014-01-30 21:47:47 -08001790
1791 // Enable auto-suspend if needed.
1792 if (autoSuspend) {
1793 if (mDecoupleInteractiveModeFromDisplayConfig) {
1794 setInteractiveModeLocked(false);
1795 }
1796 if (mDecoupleAutoSuspendModeFromDisplayConfig) {
1797 setAutoSuspendModeLocked(true);
1798 }
1799 }
Jeff Brown96307042012-07-27 15:51:34 -07001800 }
1801
Jeff Brownec083212013-09-11 20:45:25 -07001802 /**
1803 * Return true if we must keep a suspend blocker active on behalf of the display.
1804 * We do so if the screen is on or is in transition between states.
1805 */
Jeff Brown26875502014-01-30 21:47:47 -08001806 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07001807 if (!mDisplayReady) {
1808 return true;
1809 }
Jeff Brown26875502014-01-30 21:47:47 -08001810 if (mDisplayPowerRequest.wantScreenOnNormal()) {
Jeff Brownec083212013-09-11 20:45:25 -07001811 // If we asked for the screen to be on but it is off due to the proximity
1812 // sensor then we may suspend but only if the configuration allows it.
1813 // On some hardware it may not be safe to suspend because the proximity
1814 // sensor may not be correctly configured as a wake-up source.
1815 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
1816 || !mSuspendWhenScreenOffDueToProximityConfig) {
1817 return true;
1818 }
1819 }
Jeff Brown26875502014-01-30 21:47:47 -08001820 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07001821 return false;
1822 }
1823
Jeff Brown26875502014-01-30 21:47:47 -08001824 private void setAutoSuspendModeLocked(boolean enable) {
1825 if (enable != mAutoSuspendModeEnabled) {
1826 if (DEBUG) {
1827 Slog.d(TAG, "Setting auto-suspend mode to " + enable);
1828 }
1829 mAutoSuspendModeEnabled = enable;
1830 nativeSetAutoSuspend(enable);
1831 }
1832 }
1833
1834 private void setInteractiveModeLocked(boolean enable) {
1835 if (enable != mInteractiveModeEnabled) {
1836 if (DEBUG) {
1837 Slog.d(TAG, "Setting interactive mode to " + enable);
1838 }
1839 mInteractiveModeEnabled = enable;
1840 nativeSetInteractive(enable);
1841 }
1842 }
1843
Jeff Brown96307042012-07-27 15:51:34 -07001844 private boolean isScreenOnInternal() {
1845 synchronized (mLock) {
Jeff Browne39ef092014-03-11 20:56:26 -07001846 // XXX This is a temporary hack to let certain parts of the system pretend the
1847 // screen is still on even when dozing and we would normally want to report
1848 // screen off. Will be removed when the window manager is modified to use
1849 // the true blanking state of the display.
1850 return isScreenOnLocked()
1851 || mWakefulness == WAKEFULNESS_DOZING;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001852 }
1853 }
1854
Jeff Brown4c7e6902014-02-27 21:11:31 -08001855 private boolean isScreenOnLocked() {
1856 return mWakefulness == WAKEFULNESS_AWAKE
1857 || mWakefulness == WAKEFULNESS_DREAMING;
1858 }
1859
Jeff Brown96307042012-07-27 15:51:34 -07001860 private void handleBatteryStateChangedLocked() {
1861 mDirty |= DIRTY_BATTERY_STATE;
1862 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001863 }
1864
Jeff Brown20767b22012-10-09 18:57:07 -07001865 private void startWatchingForBootAnimationFinished() {
1866 mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
1867 }
1868
1869 private void checkIfBootAnimationFinished() {
1870 if (DEBUG) {
1871 Slog.d(TAG, "Check if boot animation finished...");
1872 }
1873
1874 if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
1875 mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
1876 BOOT_ANIMATION_POLL_INTERVAL);
1877 return;
1878 }
1879
1880 synchronized (mLock) {
1881 if (!mBootCompleted) {
1882 Slog.i(TAG, "Boot animation finished.");
1883 handleBootCompletedLocked();
1884 }
1885 }
1886 }
1887
Jeff Brown96307042012-07-27 15:51:34 -07001888 private void handleBootCompletedLocked() {
1889 final long now = SystemClock.uptimeMillis();
1890 mBootCompleted = true;
1891 mDirty |= DIRTY_BOOT_COMPLETED;
1892 userActivityNoUpdateLocked(
1893 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1894 updatePowerStateLocked();
Dianne Hackborn254cb442010-01-27 19:23:59 -08001895 }
1896
Jeff Brownab887a02012-10-15 16:00:40 -07001897 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001898 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07001899 if (mHandler == null || !mSystemReady) {
Jeff Brownab887a02012-10-15 16:00:40 -07001900 throw new IllegalStateException("Too early to call shutdown() or reboot()");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001901 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001902
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001903 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07001904 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001905 public void run() {
1906 synchronized (this) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001907 if (shutdown) {
1908 ShutdownThread.shutdown(mContext, confirm);
1909 } else {
1910 ShutdownThread.reboot(mContext, reason, confirm);
1911 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001912 }
San Mehat1e512792010-01-07 10:40:29 -08001913 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001914 };
Jeff Brown96307042012-07-27 15:51:34 -07001915
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001916 // ShutdownThread must run on a looper capable of displaying the UI.
Jeff Brown96307042012-07-27 15:51:34 -07001917 Message msg = Message.obtain(mHandler, runnable);
1918 msg.setAsynchronous(true);
1919 mHandler.sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001920
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001921 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001922 if (wait) {
1923 synchronized (runnable) {
1924 while (true) {
1925 try {
1926 runnable.wait();
1927 } catch (InterruptedException e) {
1928 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001929 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001930 }
Doug Zongker50a21f42009-11-19 12:49:53 -08001931 }
1932 }
1933
Jeff Brown96307042012-07-27 15:51:34 -07001934 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08001935 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07001936 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001937 public void run() {
1938 throw new RuntimeException(message);
1939 }
Dan Egnor60d87622009-12-16 16:32:58 -08001940 };
1941 try {
1942 t.start();
1943 t.join();
1944 } catch (InterruptedException e) {
1945 Log.wtf(TAG, e);
1946 }
1947 }
1948
Jeff Brown96307042012-07-27 15:51:34 -07001949 private void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07001950 Settings.Global.putInt(mContext.getContentResolver(),
1951 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
1953
Jeff Brown96307042012-07-27 15:51:34 -07001954 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
1955 synchronized (mLock) {
1956 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
1957 mDirty |= DIRTY_SETTINGS;
1958 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
1960 }
1961
Jeff Brown96307042012-07-27 15:51:34 -07001962 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
1963 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
1964 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001966
Jeff Brown96307042012-07-27 15:51:34 -07001967 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001968 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07001969 synchronized (mLock) {
1970 if (!mSystemReady) {
1971 return;
1972 }
1973 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001974 }
Jeff Brown96307042012-07-27 15:51:34 -07001975
1976 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001977 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07001978 }
1979
Jeff Brown96307042012-07-27 15:51:34 -07001980 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
1981 synchronized (mLock) {
1982 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
1983 mScreenBrightnessOverrideFromWindowManager = brightness;
1984 mDirty |= DIRTY_SETTINGS;
1985 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05001986 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04001987 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07001988 }
1989
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001990 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
1991 synchronized (mLock) {
1992 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
1993 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
1994 mDirty |= DIRTY_SETTINGS;
1995 updatePowerStateLocked();
1996 }
1997 }
1998 }
1999
Jeff Brown96307042012-07-27 15:51:34 -07002000 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
2001 synchronized (mLock) {
2002 if (mTemporaryScreenBrightnessSettingOverride != brightness) {
2003 mTemporaryScreenBrightnessSettingOverride = brightness;
2004 mDirty |= DIRTY_SETTINGS;
2005 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002006 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002007 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002008 }
2009
Jeff Brown330560f2012-08-21 22:10:57 -07002010 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
2011 synchronized (mLock) {
2012 // Note: This condition handles NaN because NaN is not equal to any other
2013 // value, including itself.
2014 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
2015 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
2016 mDirty |= DIRTY_SETTINGS;
2017 updatePowerStateLocked();
2018 }
2019 }
Jeff Brown96307042012-07-27 15:51:34 -07002020 }
2021
2022 /**
2023 * Low-level function turn the device off immediately, without trying
2024 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
2025 */
2026 public static void lowLevelShutdown() {
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002027 SystemProperties.set("sys.powerctl", "shutdown");
Jeff Brown96307042012-07-27 15:51:34 -07002028 }
2029
2030 /**
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002031 * Low-level function to reboot the device. On success, this function
2032 * doesn't return. If more than 5 seconds passes from the time,
2033 * a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07002034 *
2035 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07002036 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07002037 public static void lowLevelReboot(String reason) {
2038 if (reason == null) {
2039 reason = "";
2040 }
2041 SystemProperties.set("sys.powerctl", "reboot," + reason);
2042 try {
2043 Thread.sleep(20000);
2044 } catch (InterruptedException e) {
2045 Thread.currentThread().interrupt();
2046 }
Jeff Brown96307042012-07-27 15:51:34 -07002047 }
2048
2049 @Override // Watchdog.Monitor implementation
2050 public void monitor() {
2051 // Grab and release lock for watchdog monitor to detect deadlocks.
2052 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002053 }
Jeff Brown96307042012-07-27 15:51:34 -07002054 }
2055
Jeff Brown6f357d32014-01-15 20:40:55 -08002056 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07002057 pw.println("POWER MANAGER (dumpsys power)\n");
2058
Jeff Brown3b971592013-01-09 18:46:37 -08002059 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07002060 synchronized (mLock) {
2061 pw.println("Power Manager State:");
2062 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
2063 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness));
2064 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07002065 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07002066 pw.println(" mBatteryLevel=" + mBatteryLevel);
2067 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07002068 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07002069 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07002070 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07002071 pw.println(" mBootCompleted=" + mBootCompleted);
2072 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown26875502014-01-30 21:47:47 -08002073 pw.println(" mAutoSuspendModeEnabled=" + mAutoSuspendModeEnabled);
2074 pw.println(" mInteactiveModeEnabled=" + mInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07002075 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2076 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
2077 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
2078 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08002079 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Jeff Brown96307042012-07-27 15:51:34 -07002080 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
2081 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
2082 pw.println(" mSendWakeUpFinishedNotificationWhenReady="
2083 + mSendWakeUpFinishedNotificationWhenReady);
2084 pw.println(" mSendGoToSleepFinishedNotificationWhenReady="
2085 + mSendGoToSleepFinishedNotificationWhenReady);
2086 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
2087 pw.println(" mLastUserActivityTimeNoChangeLights="
2088 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
2089 pw.println(" mDisplayReady=" + mDisplayReady);
2090 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08002091 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07002092
2093 pw.println();
2094 pw.println("Settings and Configuration:");
Jeff Brown26875502014-01-30 21:47:47 -08002095 pw.println(" mDecoupleAutoSuspendModeFromDisplayConfig="
2096 + mDecoupleAutoSuspendModeFromDisplayConfig);
2097 pw.println(" mDecoupleInteractiveModeFromDisplayConfig="
2098 + mDecoupleInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002099 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
2100 + mWakeUpWhenPluggedOrUnpluggedConfig);
2101 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
2102 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002103 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07002104 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
2105 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
2106 + mDreamsActivatedOnSleepByDefaultConfig);
2107 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
2108 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08002109 pw.println(" mDreamsEnabledOnBatteryConfig="
2110 + mDreamsEnabledOnBatteryConfig);
2111 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
2112 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
2113 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
2114 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
2115 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
2116 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002117 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04002118 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07002119 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002120 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
2121 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
2122 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
2123 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
2124 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
2125 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
Jeff Brown330560f2012-08-21 22:10:57 -07002126 pw.println(" mScreenAutoBrightnessAdjustmentSetting="
2127 + mScreenAutoBrightnessAdjustmentSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002128 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
2129 pw.println(" mScreenBrightnessOverrideFromWindowManager="
2130 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002131 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
2132 + mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown96307042012-07-27 15:51:34 -07002133 pw.println(" mTemporaryScreenBrightnessSettingOverride="
2134 + mTemporaryScreenBrightnessSettingOverride);
Jeff Brown330560f2012-08-21 22:10:57 -07002135 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
2136 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
Jeff Brown96307042012-07-27 15:51:34 -07002137 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
2138 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
2139 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
2140
Jeff Brownff532542012-10-02 21:18:04 -07002141 final int screenOffTimeout = getScreenOffTimeoutLocked();
2142 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
2143 pw.println();
2144 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
2145 pw.println("Screen dim duration: " + screenDimDuration + " ms");
2146
Jeff Brown96307042012-07-27 15:51:34 -07002147 pw.println();
2148 pw.println("Wake Locks: size=" + mWakeLocks.size());
2149 for (WakeLock wl : mWakeLocks) {
2150 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04002151 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002152
Jeff Brown96307042012-07-27 15:51:34 -07002153 pw.println();
2154 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
2155 for (SuspendBlocker sb : mSuspendBlockers) {
2156 pw.println(" " + sb);
2157 }
2158
Jeff Brownc38c9be2012-10-04 13:16:19 -07002159 pw.println();
2160 pw.println("Screen On Blocker: " + mScreenOnBlocker);
2161
Jeff Brown9e316a12012-10-08 19:17:06 -07002162 pw.println();
Jeff Brownad9ef192014-04-08 17:26:30 -07002163 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07002164
Jeff Brown3b971592013-01-09 18:46:37 -08002165 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07002166 }
2167
Jeff Brown3b971592013-01-09 18:46:37 -08002168 if (wcd != null) {
2169 wcd.dump(pw);
2170 }
Jeff Brown96307042012-07-27 15:51:34 -07002171 }
2172
2173 private SuspendBlocker createSuspendBlockerLocked(String name) {
2174 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
2175 mSuspendBlockers.add(suspendBlocker);
2176 return suspendBlocker;
2177 }
2178
2179 private static String wakefulnessToString(int wakefulness) {
2180 switch (wakefulness) {
2181 case WAKEFULNESS_ASLEEP:
2182 return "Asleep";
2183 case WAKEFULNESS_AWAKE:
2184 return "Awake";
2185 case WAKEFULNESS_DREAMING:
2186 return "Dreaming";
Jeff Brown26875502014-01-30 21:47:47 -08002187 case WAKEFULNESS_DOZING:
2188 return "Dozing";
Jeff Brown96307042012-07-27 15:51:34 -07002189 default:
2190 return Integer.toString(wakefulness);
2191 }
2192 }
2193
2194 private static WorkSource copyWorkSource(WorkSource workSource) {
2195 return workSource != null ? new WorkSource(workSource) : null;
2196 }
2197
2198 private final class BatteryReceiver extends BroadcastReceiver {
2199 @Override
2200 public void onReceive(Context context, Intent intent) {
2201 synchronized (mLock) {
2202 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002203 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002204 }
2205 }
2206
Jeff Brown96307042012-07-27 15:51:34 -07002207 private final class BootCompletedReceiver extends BroadcastReceiver {
2208 @Override
2209 public void onReceive(Context context, Intent intent) {
Jeff Brown20767b22012-10-09 18:57:07 -07002210 // This is our early signal that the system thinks it has finished booting.
2211 // However, the boot animation may still be running for a few more seconds
2212 // since it is ultimately in charge of when it terminates.
2213 // Defer transitioning into the boot completed state until the animation exits.
2214 // We do this so that the screen does not start to dim prematurely before
2215 // the user has actually had a chance to interact with the device.
2216 startWatchingForBootAnimationFinished();
Joe Onoratod28f7532010-11-06 12:56:53 -07002217 }
Jeff Brown96307042012-07-27 15:51:34 -07002218 }
2219
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002220 private final class DreamReceiver extends BroadcastReceiver {
2221 @Override
2222 public void onReceive(Context context, Intent intent) {
2223 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002224 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002225 }
2226 }
2227 }
2228
Jeff Brownd4935962012-09-25 13:27:20 -07002229 private final class UserSwitchedReceiver extends BroadcastReceiver {
2230 @Override
2231 public void onReceive(Context context, Intent intent) {
2232 synchronized (mLock) {
2233 handleSettingsChangedLocked();
2234 }
2235 }
2236 }
2237
Jeff Brownec6aa592012-10-17 20:30:25 -07002238 private final class DockReceiver extends BroadcastReceiver {
2239 @Override
2240 public void onReceive(Context context, Intent intent) {
2241 synchronized (mLock) {
2242 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2243 Intent.EXTRA_DOCK_STATE_UNDOCKED);
2244 if (mDockState != dockState) {
2245 mDockState = dockState;
2246 mDirty |= DIRTY_DOCK_STATE;
2247 updatePowerStateLocked();
2248 }
2249 }
2250 }
2251 }
2252
Jeff Brown96307042012-07-27 15:51:34 -07002253 private final class SettingsObserver extends ContentObserver {
2254 public SettingsObserver(Handler handler) {
2255 super(handler);
2256 }
2257
2258 @Override
2259 public void onChange(boolean selfChange, Uri uri) {
2260 synchronized (mLock) {
2261 handleSettingsChangedLocked();
2262 }
2263 }
2264 }
2265
Jeff Brown96307042012-07-27 15:51:34 -07002266 /**
2267 * Handler for asynchronous operations performed by the power manager.
2268 */
2269 private final class PowerManagerHandler extends Handler {
2270 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07002271 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07002272 }
2273
2274 @Override
2275 public void handleMessage(Message msg) {
2276 switch (msg.what) {
2277 case MSG_USER_ACTIVITY_TIMEOUT:
2278 handleUserActivityTimeout();
2279 break;
2280 case MSG_SANDMAN:
2281 handleSandman();
2282 break;
Jeff Brownc38c9be2012-10-04 13:16:19 -07002283 case MSG_SCREEN_ON_BLOCKER_RELEASED:
2284 handleScreenOnBlockerReleased();
2285 break;
Jeff Brown20767b22012-10-09 18:57:07 -07002286 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
2287 checkIfBootAnimationFinished();
2288 break;
Jeff Brown96307042012-07-27 15:51:34 -07002289 }
2290 }
2291 }
2292
2293 /**
2294 * Represents a wake lock that has been acquired by an application.
2295 */
2296 private final class WakeLock implements IBinder.DeathRecipient {
2297 public final IBinder mLock;
2298 public int mFlags;
2299 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002300 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07002301 public WorkSource mWorkSource;
Dianne Hackborn713df152013-05-17 11:27:57 -07002302 public final int mOwnerUid;
2303 public final int mOwnerPid;
2304 public boolean mNotifiedAcquired;
Jeff Brown96307042012-07-27 15:51:34 -07002305
Dianne Hackborn713df152013-05-17 11:27:57 -07002306 public WakeLock(IBinder lock, int flags, String tag, String packageName,
2307 WorkSource workSource, int ownerUid, int ownerPid) {
Jeff Brown96307042012-07-27 15:51:34 -07002308 mLock = lock;
2309 mFlags = flags;
2310 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002311 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07002312 mWorkSource = copyWorkSource(workSource);
2313 mOwnerUid = ownerUid;
2314 mOwnerPid = ownerPid;
2315 }
2316
2317 @Override
2318 public void binderDied() {
2319 PowerManagerService.this.handleWakeLockDeath(this);
2320 }
2321
2322 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2323 int ownerUid, int ownerPid) {
2324 return mFlags == flags
2325 && mTag.equals(tag)
2326 && hasSameWorkSource(workSource)
2327 && mOwnerUid == ownerUid
2328 && mOwnerPid == ownerPid;
2329 }
2330
Dianne Hackborn713df152013-05-17 11:27:57 -07002331 public void updateProperties(int flags, String tag, String packageName,
2332 WorkSource workSource, int ownerUid, int ownerPid) {
2333 if (!mPackageName.equals(packageName)) {
2334 throw new IllegalStateException("Existing wake lock package name changed: "
2335 + mPackageName + " to " + packageName);
2336 }
2337 if (mOwnerUid != ownerUid) {
2338 throw new IllegalStateException("Existing wake lock uid changed: "
2339 + mOwnerUid + " to " + ownerUid);
2340 }
2341 if (mOwnerPid != ownerPid) {
2342 throw new IllegalStateException("Existing wake lock pid changed: "
2343 + mOwnerPid + " to " + ownerPid);
2344 }
Jeff Brown96307042012-07-27 15:51:34 -07002345 mFlags = flags;
2346 mTag = tag;
2347 updateWorkSource(workSource);
Jeff Brown96307042012-07-27 15:51:34 -07002348 }
2349
2350 public boolean hasSameWorkSource(WorkSource workSource) {
2351 return Objects.equal(mWorkSource, workSource);
2352 }
2353
2354 public void updateWorkSource(WorkSource workSource) {
2355 mWorkSource = copyWorkSource(workSource);
2356 }
2357
2358 @Override
2359 public String toString() {
2360 return getLockLevelString()
2361 + " '" + mTag + "'" + getLockFlagsString()
2362 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2363 }
2364
Jeff Brown26875502014-01-30 21:47:47 -08002365 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07002366 private String getLockLevelString() {
2367 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2368 case PowerManager.FULL_WAKE_LOCK:
2369 return "FULL_WAKE_LOCK ";
2370 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2371 return "SCREEN_BRIGHT_WAKE_LOCK ";
2372 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2373 return "SCREEN_DIM_WAKE_LOCK ";
2374 case PowerManager.PARTIAL_WAKE_LOCK:
2375 return "PARTIAL_WAKE_LOCK ";
2376 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2377 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08002378 case PowerManager.DOZE_WAKE_LOCK:
2379 return "DOZE_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07002380 default:
2381 return "??? ";
2382 }
2383 }
2384
2385 private String getLockFlagsString() {
2386 String result = "";
2387 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2388 result += " ACQUIRE_CAUSES_WAKEUP";
2389 }
2390 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2391 result += " ON_AFTER_RELEASE";
2392 }
2393 return result;
2394 }
2395 }
2396
2397 private final class SuspendBlockerImpl implements SuspendBlocker {
2398 private final String mName;
2399 private int mReferenceCount;
2400
2401 public SuspendBlockerImpl(String name) {
2402 mName = name;
2403 }
2404
2405 @Override
2406 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002407 try {
Jeff Brown96307042012-07-27 15:51:34 -07002408 if (mReferenceCount != 0) {
2409 Log.wtf(TAG, "Suspend blocker \"" + mName
2410 + "\" was finalized without being released!");
2411 mReferenceCount = 0;
2412 nativeReleaseSuspendBlocker(mName);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002413 }
2414 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07002415 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002416 }
2417 }
2418
Craig Mautner75fc9de2012-06-18 16:53:27 -07002419 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002420 public void acquire() {
2421 synchronized (this) {
2422 mReferenceCount += 1;
2423 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002424 if (DEBUG_SPEW) {
2425 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2426 }
Jeff Brown96307042012-07-27 15:51:34 -07002427 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07002428 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002429 }
2430 }
2431
Craig Mautner75fc9de2012-06-18 16:53:27 -07002432 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002433 public void release() {
2434 synchronized (this) {
2435 mReferenceCount -= 1;
2436 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002437 if (DEBUG_SPEW) {
2438 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2439 }
Jeff Brown96307042012-07-27 15:51:34 -07002440 nativeReleaseSuspendBlocker(mName);
2441 } else if (mReferenceCount < 0) {
2442 Log.wtf(TAG, "Suspend blocker \"" + mName
2443 + "\" was released without being acquired!", new Throwable());
2444 mReferenceCount = 0;
2445 }
2446 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002447 }
Jeff Brown96307042012-07-27 15:51:34 -07002448
2449 @Override
2450 public String toString() {
2451 synchronized (this) {
2452 return mName + ": ref count=" + mReferenceCount;
2453 }
2454 }
2455 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002456
2457 private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
2458 private int mNestCount;
2459
2460 public boolean isHeld() {
2461 synchronized (this) {
2462 return mNestCount != 0;
2463 }
2464 }
2465
2466 @Override
2467 public void acquire() {
2468 synchronized (this) {
2469 mNestCount += 1;
2470 if (DEBUG) {
2471 Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
2472 }
2473 }
2474 }
2475
2476 @Override
2477 public void release() {
2478 synchronized (this) {
2479 mNestCount -= 1;
2480 if (mNestCount < 0) {
2481 Log.wtf(TAG, "Screen on blocker was released without being acquired!",
2482 new Throwable());
2483 mNestCount = 0;
2484 }
2485 if (mNestCount == 0) {
2486 mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
2487 }
2488 if (DEBUG) {
2489 Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
2490 }
2491 }
2492 }
2493
2494 @Override
2495 public String toString() {
2496 synchronized (this) {
2497 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
2498 }
2499 }
Jeff Brown9e316a12012-10-08 19:17:06 -07002500 }
2501
Jeff Brown6f357d32014-01-15 20:40:55 -08002502 private final class BinderService extends IPowerManager.Stub {
2503 @Override // Binder call
2504 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2505 String packageName, int uid) {
2506 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid));
2507 }
2508
2509 @Override // Binder call
2510 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
2511 WorkSource ws) {
2512 if (lock == null) {
2513 throw new IllegalArgumentException("lock must not be null");
2514 }
2515 if (packageName == null) {
2516 throw new IllegalArgumentException("packageName must not be null");
2517 }
2518 PowerManager.validateWakeLockParameters(flags, tag);
2519
2520 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2521 if (ws != null && ws.size() != 0) {
2522 mContext.enforceCallingOrSelfPermission(
2523 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2524 } else {
2525 ws = null;
2526 }
2527
2528 final int uid = Binder.getCallingUid();
2529 final int pid = Binder.getCallingPid();
2530 final long ident = Binder.clearCallingIdentity();
2531 try {
2532 acquireWakeLockInternal(lock, flags, tag, packageName, ws, uid, pid);
2533 } finally {
2534 Binder.restoreCallingIdentity(ident);
2535 }
2536 }
2537
2538 @Override // Binder call
2539 public void releaseWakeLock(IBinder lock, int flags) {
2540 if (lock == null) {
2541 throw new IllegalArgumentException("lock must not be null");
2542 }
2543
2544 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2545
2546 final long ident = Binder.clearCallingIdentity();
2547 try {
2548 releaseWakeLockInternal(lock, flags);
2549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
2553
2554 @Override // Binder call
2555 public void updateWakeLockUids(IBinder lock, int[] uids) {
2556 WorkSource ws = null;
2557
2558 if (uids != null) {
2559 ws = new WorkSource();
2560 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2561 // one at a time?
2562 for (int i = 0; i < uids.length; i++) {
2563 ws.add(uids[i]);
2564 }
2565 }
2566 updateWakeLockWorkSource(lock, ws);
2567 }
2568
2569 @Override // Binder call
2570 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
2571 if (lock == null) {
2572 throw new IllegalArgumentException("lock must not be null");
2573 }
2574
2575 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2576 if (ws != null && ws.size() != 0) {
2577 mContext.enforceCallingOrSelfPermission(
2578 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2579 } else {
2580 ws = null;
2581 }
2582
2583 final long ident = Binder.clearCallingIdentity();
2584 try {
2585 updateWakeLockWorkSourceInternal(lock, ws);
2586 } finally {
2587 Binder.restoreCallingIdentity(ident);
2588 }
2589 }
2590
2591 @Override // Binder call
2592 public boolean isWakeLockLevelSupported(int level) {
2593 final long ident = Binder.clearCallingIdentity();
2594 try {
2595 return isWakeLockLevelSupportedInternal(level);
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
2600
2601 @Override // Binder call
2602 public void userActivity(long eventTime, int event, int flags) {
2603 final long now = SystemClock.uptimeMillis();
2604 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2605 != PackageManager.PERMISSION_GRANTED) {
2606 // Once upon a time applications could call userActivity().
2607 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
2608 // request instead of throwing a SecurityException so we don't break old apps.
2609 synchronized (mLock) {
2610 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2611 mLastWarningAboutUserActivityPermission = now;
2612 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
2613 + "caller does not have DEVICE_POWER permission. "
2614 + "Please fix your app! "
2615 + " pid=" + Binder.getCallingPid()
2616 + " uid=" + Binder.getCallingUid());
2617 }
2618 }
2619 return;
2620 }
2621
2622 if (eventTime > SystemClock.uptimeMillis()) {
2623 throw new IllegalArgumentException("event time must not be in the future");
2624 }
2625
2626 final int uid = Binder.getCallingUid();
2627 final long ident = Binder.clearCallingIdentity();
2628 try {
2629 userActivityInternal(eventTime, event, flags, uid);
2630 } finally {
2631 Binder.restoreCallingIdentity(ident);
2632 }
2633 }
2634
2635 @Override // Binder call
2636 public void wakeUp(long eventTime) {
2637 if (eventTime > SystemClock.uptimeMillis()) {
2638 throw new IllegalArgumentException("event time must not be in the future");
2639 }
2640
2641 mContext.enforceCallingOrSelfPermission(
2642 android.Manifest.permission.DEVICE_POWER, null);
2643
2644 final long ident = Binder.clearCallingIdentity();
2645 try {
2646 wakeUpInternal(eventTime);
2647 } finally {
2648 Binder.restoreCallingIdentity(ident);
2649 }
2650 }
2651
2652 @Override // Binder call
2653 public void goToSleep(long eventTime, int reason) {
2654 if (eventTime > SystemClock.uptimeMillis()) {
2655 throw new IllegalArgumentException("event time must not be in the future");
2656 }
2657
2658 mContext.enforceCallingOrSelfPermission(
2659 android.Manifest.permission.DEVICE_POWER, null);
2660
2661 final long ident = Binder.clearCallingIdentity();
2662 try {
2663 goToSleepInternal(eventTime, reason);
2664 } finally {
2665 Binder.restoreCallingIdentity(ident);
2666 }
2667 }
2668
2669 @Override // Binder call
2670 public void nap(long eventTime) {
2671 if (eventTime > SystemClock.uptimeMillis()) {
2672 throw new IllegalArgumentException("event time must not be in the future");
2673 }
2674
2675 mContext.enforceCallingOrSelfPermission(
2676 android.Manifest.permission.DEVICE_POWER, null);
2677
2678 final long ident = Binder.clearCallingIdentity();
2679 try {
2680 napInternal(eventTime);
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
2685
2686 @Override // Binder call
2687 public boolean isScreenOn() {
2688 final long ident = Binder.clearCallingIdentity();
2689 try {
2690 return isScreenOnInternal();
2691 } finally {
2692 Binder.restoreCallingIdentity(ident);
2693 }
2694 }
2695
2696 /**
2697 * Reboots the device.
2698 *
2699 * @param confirm If true, shows a reboot confirmation dialog.
2700 * @param reason The reason for the reboot, or null if none.
2701 * @param wait If true, this call waits for the reboot to complete and does not return.
2702 */
2703 @Override // Binder call
2704 public void reboot(boolean confirm, String reason, boolean wait) {
2705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2706
2707 final long ident = Binder.clearCallingIdentity();
2708 try {
2709 shutdownOrRebootInternal(false, confirm, reason, wait);
2710 } finally {
2711 Binder.restoreCallingIdentity(ident);
2712 }
2713 }
2714
2715 /**
2716 * Shuts down the device.
2717 *
2718 * @param confirm If true, shows a shutdown confirmation dialog.
2719 * @param wait If true, this call waits for the shutdown to complete and does not return.
2720 */
2721 @Override // Binder call
2722 public void shutdown(boolean confirm, boolean wait) {
2723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2724
2725 final long ident = Binder.clearCallingIdentity();
2726 try {
2727 shutdownOrRebootInternal(true, confirm, null, wait);
2728 } finally {
2729 Binder.restoreCallingIdentity(ident);
2730 }
2731 }
2732
2733 /**
2734 * Crash the runtime (causing a complete restart of the Android framework).
2735 * Requires REBOOT permission. Mostly for testing. Should not return.
2736 */
2737 @Override // Binder call
2738 public void crash(String message) {
2739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2740
2741 final long ident = Binder.clearCallingIdentity();
2742 try {
2743 crashInternal(message);
2744 } finally {
2745 Binder.restoreCallingIdentity(ident);
2746 }
2747 }
2748
2749 /**
2750 * Set the setting that determines whether the device stays on when plugged in.
2751 * The argument is a bit string, with each bit specifying a power source that,
2752 * when the device is connected to that source, causes the device to stay on.
2753 * See {@link android.os.BatteryManager} for the list of power sources that
2754 * can be specified. Current values include
2755 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
2756 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
2757 *
2758 * Used by "adb shell svc power stayon ..."
2759 *
2760 * @param val an {@code int} containing the bits that specify which power sources
2761 * should cause the device to stay on.
2762 */
2763 @Override // Binder call
2764 public void setStayOnSetting(int val) {
2765 mContext.enforceCallingOrSelfPermission(
2766 android.Manifest.permission.WRITE_SETTINGS, null);
2767
2768 final long ident = Binder.clearCallingIdentity();
2769 try {
2770 setStayOnSettingInternal(val);
2771 } finally {
2772 Binder.restoreCallingIdentity(ident);
2773 }
2774 }
2775
2776 /**
2777 * Used by device administration to set the maximum screen off timeout.
2778 *
2779 * This method must only be called by the device administration policy manager.
2780 */
2781 @Override // Binder call
2782 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
2783 final long ident = Binder.clearCallingIdentity();
2784 try {
2785 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
2786 } finally {
2787 Binder.restoreCallingIdentity(ident);
2788 }
2789 }
2790
2791 /**
2792 * Used by the settings application and brightness control widgets to
2793 * temporarily override the current screen brightness setting so that the
2794 * user can observe the effect of an intended settings change without applying
2795 * it immediately.
2796 *
2797 * The override will be canceled when the setting value is next updated.
2798 *
2799 * @param brightness The overridden brightness.
2800 *
2801 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
2802 */
2803 @Override // Binder call
2804 public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
2805 mContext.enforceCallingOrSelfPermission(
2806 android.Manifest.permission.DEVICE_POWER, null);
2807
2808 final long ident = Binder.clearCallingIdentity();
2809 try {
2810 setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
2811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815
2816 /**
2817 * Used by the settings application and brightness control widgets to
2818 * temporarily override the current screen auto-brightness adjustment setting so that the
2819 * user can observe the effect of an intended settings change without applying
2820 * it immediately.
2821 *
2822 * The override will be canceled when the setting value is next updated.
2823 *
2824 * @param adj The overridden brightness, or Float.NaN to disable the override.
2825 *
Jeff Brownad9ef192014-04-08 17:26:30 -07002826 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
Jeff Brown6f357d32014-01-15 20:40:55 -08002827 */
2828 @Override // Binder call
2829 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
2830 mContext.enforceCallingOrSelfPermission(
2831 android.Manifest.permission.DEVICE_POWER, null);
2832
2833 final long ident = Binder.clearCallingIdentity();
2834 try {
2835 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
2836 } finally {
2837 Binder.restoreCallingIdentity(ident);
2838 }
2839 }
2840
2841 /**
2842 * Used by the phone application to make the attention LED flash when ringing.
2843 */
2844 @Override // Binder call
2845 public void setAttentionLight(boolean on, int color) {
2846 mContext.enforceCallingOrSelfPermission(
2847 android.Manifest.permission.DEVICE_POWER, null);
2848
2849 final long ident = Binder.clearCallingIdentity();
2850 try {
2851 setAttentionLightInternal(on, color);
2852 } finally {
2853 Binder.restoreCallingIdentity(ident);
2854 }
2855 }
2856
2857 @Override // Binder call
2858 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2859 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
2860 != PackageManager.PERMISSION_GRANTED) {
2861 pw.println("Permission Denial: can't dump PowerManager from from pid="
2862 + Binder.getCallingPid()
2863 + ", uid=" + Binder.getCallingUid());
2864 return;
2865 }
2866
2867 final long ident = Binder.clearCallingIdentity();
2868 try {
2869 dumpInternal(pw);
2870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
2873 }
2874 }
2875
Jeff Brown4ccb8232014-01-16 22:16:42 -08002876 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08002877 /**
2878 * Used by the window manager to override the screen brightness based on the
2879 * current foreground activity.
2880 *
2881 * This method must only be called by the window manager.
2882 *
2883 * @param brightness The overridden brightness, or -1 to disable the override.
2884 */
2885 @Override
2886 public void setScreenBrightnessOverrideFromWindowManager(int brightness) {
2887 mContext.enforceCallingOrSelfPermission(
2888 android.Manifest.permission.DEVICE_POWER, null);
2889
2890 final long ident = Binder.clearCallingIdentity();
2891 try {
2892 setScreenBrightnessOverrideFromWindowManagerInternal(brightness);
2893 } finally {
2894 Binder.restoreCallingIdentity(ident);
2895 }
2896 }
2897
2898 /**
2899 * Used by the window manager to override the button brightness based on the
2900 * current foreground activity.
2901 *
2902 * This method must only be called by the window manager.
2903 *
2904 * @param brightness The overridden brightness, or -1 to disable the override.
2905 */
2906 @Override
2907 public void setButtonBrightnessOverrideFromWindowManager(int brightness) {
2908 // Do nothing.
2909 // Button lights are not currently supported in the new implementation.
2910 mContext.enforceCallingOrSelfPermission(
2911 android.Manifest.permission.DEVICE_POWER, null);
2912 }
2913
2914 /**
2915 * Used by the window manager to override the user activity timeout based on the
2916 * current foreground activity. It can only be used to make the timeout shorter
2917 * than usual, not longer.
2918 *
2919 * This method must only be called by the window manager.
2920 *
2921 * @param timeoutMillis The overridden timeout, or -1 to disable the override.
2922 */
2923 @Override
2924 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
2925 mContext.enforceCallingOrSelfPermission(
2926 android.Manifest.permission.DEVICE_POWER, null);
2927
2928 final long ident = Binder.clearCallingIdentity();
2929 try {
2930 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
2931 } finally {
2932 Binder.restoreCallingIdentity(ident);
2933 }
2934 }
2935
2936 @Override
2937 public void setPolicy(WindowManagerPolicy policy) {
2938 PowerManagerService.this.setPolicy(policy);
2939 }
2940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941}