blob: 94876bb651c2b17304292baeaf2dcf445eaa65e6 [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 Brown6f357d32014-01-15 20:40:55 -080023import com.android.server.ServiceThread;
Adam Lesinski182f73f2013-12-05 16:48:06 -080024import com.android.server.lights.Light;
25import com.android.server.lights.LightsManager;
26import com.android.server.twilight.TwilightManager;
Jeff Brown4f8ecd82012-06-18 18:29:13 -070027import com.android.server.Watchdog;
Jeff Brown62c82e42012-09-26 01:30:41 -070028import com.android.server.dreams.DreamManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Jeff Brown96307042012-07-27 15:51:34 -070030import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070037import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080038import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080039import android.hardware.SensorManager;
40import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080041import android.hardware.display.DisplayManagerInternal;
Jeff 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;
60import android.util.EventLog;
61import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080062import android.util.Slog;
Jeff Brown96307042012-07-27 15:51:34 -070063import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.view.WindowManagerPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
66import java.io.FileDescriptor;
67import java.io.PrintWriter;
68import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Jeff Brown96307042012-07-27 15:51:34 -070070import libcore.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Jeff Brown96307042012-07-27 15:51:34 -070072/**
73 * The power manager service is responsible for coordinating power management
74 * functions on the device.
75 */
Jeff Brown6f357d32014-01-15 20:40:55 -080076public final class PowerManagerService extends com.android.server.SystemService
Jeff Brown96307042012-07-27 15:51:34 -070077 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
Jeff Brown88c997a2012-06-22 13:57:45 -070080 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -070081 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -070082
Jeff Brown96307042012-07-27 15:51:34 -070083 // Message: Sent when a user activity timeout occurs to update the power state.
84 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
85 // Message: Sent when the device enters or exits a napping or dreaming state.
86 private static final int MSG_SANDMAN = 2;
Jeff Brownc38c9be2012-10-04 13:16:19 -070087 // Message: Sent when the screen on blocker is released.
88 private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3;
Jeff Brown20767b22012-10-09 18:57:07 -070089 // Message: Sent to poll whether the boot animation has terminated.
90 private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4;
Jeff Brown7304c342012-05-11 18:42:42 -070091
Jeff Brown96307042012-07-27 15:51:34 -070092 // Dirty bit: mWakeLocks changed
93 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
94 // Dirty bit: mWakefulness changed
95 private static final int DIRTY_WAKEFULNESS = 1 << 1;
96 // Dirty bit: user activity was poked or may have timed out
97 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
98 // Dirty bit: actual display power state was updated asynchronously
99 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
100 // Dirty bit: mBootCompleted changed
101 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
102 // Dirty bit: settings changed
103 private static final int DIRTY_SETTINGS = 1 << 5;
104 // Dirty bit: mIsPowered changed
105 private static final int DIRTY_IS_POWERED = 1 << 6;
106 // Dirty bit: mStayOn changed
107 private static final int DIRTY_STAY_ON = 1 << 7;
108 // Dirty bit: battery state changed
109 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700110 // Dirty bit: proximity state changed
111 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownc38c9be2012-10-04 13:16:19 -0700112 // Dirty bit: screen on blocker state became held or unheld
113 private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10;
Jeff Brownec6aa592012-10-17 20:30:25 -0700114 // Dirty bit: dock state changed
115 private static final int DIRTY_DOCK_STATE = 1 << 11;
Jeff Brown7304c342012-05-11 18:42:42 -0700116
Jeff Brown96307042012-07-27 15:51:34 -0700117 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp().
118 // The screen should be off or in the process of being turned off by the display controller.
119 private static final int WAKEFULNESS_ASLEEP = 0;
120 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep().
Jeff Brown62c82e42012-09-26 01:30:41 -0700121 // When the user activity timeout expires, the device may start napping or go to sleep.
Jeff Brown96307042012-07-27 15:51:34 -0700122 private static final int WAKEFULNESS_AWAKE = 1;
123 // Wakefulness: The device is napping. It is deciding whether to dream or go to sleep
124 // but hasn't gotten around to it yet. It can be awoken by a call to wakeUp(), which
125 // ends the nap. User activity may brighten the screen but does not end the nap.
126 private static final int WAKEFULNESS_NAPPING = 2;
127 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(),
128 // which ends the dream. The device goes to sleep when goToSleep() is called, when
129 // the dream ends or when unplugged.
130 // User activity may brighten the screen but does not end the dream.
131 private static final int WAKEFULNESS_DREAMING = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Jeff Brown96307042012-07-27 15:51:34 -0700133 // Summarizes the state of all active wakelocks.
134 private static final int WAKE_LOCK_CPU = 1 << 0;
135 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
136 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
137 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
138 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700139 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
Jeff Brown96307042012-07-27 15:51:34 -0700141 // Summarizes the user activity state.
142 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
143 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Jeff Brown96307042012-07-27 15:51:34 -0700145 // Default and minimum screen off timeout in milliseconds.
146 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
147 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700148
Jeff Brownff532542012-10-02 21:18:04 -0700149 // The screen dim duration, in milliseconds.
Jeff Brown96307042012-07-27 15:51:34 -0700150 // This is subtracted from the end of the screen off timeout so the
151 // minimum screen off timeout should be longer than this.
152 private static final int SCREEN_DIM_DURATION = 7 * 1000;
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800153
Jeff Brownff532542012-10-02 21:18:04 -0700154 // The maximum screen dim time expressed as a ratio relative to the screen
155 // off timeout. If the screen off timeout is very short then we want the
156 // dim timeout to also be quite short so that most of the time is spent on.
157 // Otherwise the user won't get much screen on time before dimming occurs.
158 private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f;
159
Jeff Brown20767b22012-10-09 18:57:07 -0700160 // The name of the boot animation service in init.rc.
161 private static final String BOOT_ANIMATION_SERVICE = "bootanim";
162
163 // Poll interval in milliseconds for watching boot animation finished.
164 private static final int BOOT_ANIMATION_POLL_INTERVAL = 200;
165
Jeff Brown016ff142012-10-15 16:47:22 -0700166 // If the battery level drops by this percentage and the user activity timeout
167 // has expired, then assume the device is receiving insufficient current to charge
168 // effectively and terminate the dream.
169 private static final int DREAM_BATTERY_LEVEL_DRAIN_CUTOFF = 5;
170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private Context mContext;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 private LightsManager mLightsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 private BatteryService mBatteryService;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800174 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700175 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700176 private IAppOpsService mAppOps;
Jeff Brown6f357d32014-01-15 20:40:55 -0800177 private ServiceThread mHandlerThread;
Jeff Brown96307042012-07-27 15:51:34 -0700178 private PowerManagerHandler mHandler;
179 private WindowManagerPolicy mPolicy;
180 private Notifier mNotifier;
181 private DisplayPowerController mDisplayPowerController;
Jeff Brown3b971592013-01-09 18:46:37 -0800182 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700183 private SettingsObserver mSettingsObserver;
Jeff Brown62c82e42012-09-26 01:30:41 -0700184 private DreamManagerService mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800185 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700186
Jeff Brown96307042012-07-27 15:51:34 -0700187 private final Object mLock = new Object();
188
189 // A bitfield that indicates what parts of the power state have
190 // changed and need to be recalculated.
191 private int mDirty;
192
193 // Indicates whether the device is awake or asleep or somewhere in between.
194 // This is distinct from the screen power state, which is managed separately.
195 private int mWakefulness;
196
197 // True if MSG_SANDMAN has been scheduled.
198 private boolean mSandmanScheduled;
199
200 // Table of all suspend blockers.
201 // There should only be a few of these.
202 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
203
204 // Table of all wake locks acquired by applications.
205 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
206
207 // A bitfield that summarizes the state of all active wakelocks.
208 private int mWakeLockSummary;
209
210 // If true, instructs the display controller to wait for the proximity sensor to
211 // go negative before turning the screen on.
212 private boolean mRequestWaitForNegativeProximity;
213
214 // Timestamp of the last time the device was awoken or put to sleep.
215 private long mLastWakeTime;
216 private long mLastSleepTime;
217
218 // True if we need to send a wake up or go to sleep finished notification
219 // when the display is ready.
220 private boolean mSendWakeUpFinishedNotificationWhenReady;
221 private boolean mSendGoToSleepFinishedNotificationWhenReady;
222
223 // Timestamp of the last call to user activity.
224 private long mLastUserActivityTime;
225 private long mLastUserActivityTimeNoChangeLights;
226
227 // A bitfield that summarizes the effect of the user activity timer.
228 // A zero value indicates that the user activity timer has expired.
229 private int mUserActivitySummary;
230
231 // The desired display power state. The actual state may lag behind the
232 // requested because it is updated asynchronously by the display power controller.
233 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
234
Jeff Brown96307042012-07-27 15:51:34 -0700235 // True if the display power state has been fully applied, which means the display
236 // is actually on or actually off or whatever was requested.
237 private boolean mDisplayReady;
238
Jeff Brown27f7a862012-12-12 15:43:31 -0800239 // The suspend blocker used to keep the CPU alive when an application has acquired
240 // a wake lock.
241 private final SuspendBlocker mWakeLockSuspendBlocker;
242
243 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700244 private boolean mHoldingWakeLockSuspendBlocker;
245
Jeff Brown27f7a862012-12-12 15:43:31 -0800246 // The suspend blocker used to keep the CPU alive when the display is on, the
247 // display is getting ready or there is user activity (in which case the display
248 // must be on).
249 private final SuspendBlocker mDisplaySuspendBlocker;
250
251 // True if the display suspend blocker has been acquired.
252 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700253
Jeff Brownc38c9be2012-10-04 13:16:19 -0700254 // The screen on blocker used to keep the screen from turning on while the lock
255 // screen is coming up.
256 private final ScreenOnBlockerImpl mScreenOnBlocker;
257
Jeff Brown9e316a12012-10-08 19:17:06 -0700258 // The display blanker used to turn the screen on or off.
259 private final DisplayBlankerImpl mDisplayBlanker;
260
Jeff Brown96307042012-07-27 15:51:34 -0700261 // True if systemReady() has been called.
262 private boolean mSystemReady;
263
264 // True if boot completed occurred. We keep the screen on until this happens.
265 private boolean mBootCompleted;
266
267 // True if the device is plugged into a power source.
268 private boolean mIsPowered;
269
Jeff Brownf3fb8952012-10-02 20:57:05 -0700270 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
271 private int mPlugType;
272
Jeff Brown016ff142012-10-15 16:47:22 -0700273 // The current battery level percentage.
274 private int mBatteryLevel;
275
276 // The battery level percentage at the time the dream started.
277 // This is used to terminate a dream and go to sleep if the battery is
278 // draining faster than it is charging and the user activity timeout has expired.
279 private int mBatteryLevelWhenDreamStarted;
280
Jeff Brownec6aa592012-10-17 20:30:25 -0700281 // The current dock state.
282 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
283
Jeff Brown96307042012-07-27 15:51:34 -0700284 // True if the device should wake up when plugged or unplugged.
285 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
286
Jeff Brownec083212013-09-11 20:45:25 -0700287 // True if the device should suspend when the screen is off due to proximity.
288 private boolean mSuspendWhenScreenOffDueToProximityConfig;
289
Jeff Brown96307042012-07-27 15:51:34 -0700290 // True if dreams are supported on this device.
291 private boolean mDreamsSupportedConfig;
292
John Spurlocked108f32012-10-18 16:49:24 -0400293 // Default value for dreams enabled
294 private boolean mDreamsEnabledByDefaultConfig;
295
296 // Default value for dreams activate-on-sleep
297 private boolean mDreamsActivatedOnSleepByDefaultConfig;
298
299 // Default value for dreams activate-on-dock
300 private boolean mDreamsActivatedOnDockByDefaultConfig;
301
Jeff Brown96307042012-07-27 15:51:34 -0700302 // True if dreams are enabled by the user.
303 private boolean mDreamsEnabledSetting;
304
John Spurlock1a868b72012-08-22 09:56:51 -0400305 // True if dreams should be activated on sleep.
306 private boolean mDreamsActivateOnSleepSetting;
307
Jeff Brownec6aa592012-10-17 20:30:25 -0700308 // True if dreams should be activated on dock.
309 private boolean mDreamsActivateOnDockSetting;
310
Jeff Brown96307042012-07-27 15:51:34 -0700311 // The screen off timeout setting value in milliseconds.
312 private int mScreenOffTimeoutSetting;
313
314 // The maximum allowable screen off timeout according to the device
315 // administration policy. Overrides other settings.
316 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE;
317
318 // The stay on while plugged in setting.
319 // A bitfield of battery conditions under which to make the screen stay on.
320 private int mStayOnWhilePluggedInSetting;
321
322 // True if the device should stay on.
323 private boolean mStayOn;
324
Jeff Brown93cbbb22012-10-04 13:18:36 -0700325 // True if the proximity sensor reads a positive result.
326 private boolean mProximityPositive;
327
Jeff Brown96307042012-07-27 15:51:34 -0700328 // Screen brightness setting limits.
329 private int mScreenBrightnessSettingMinimum;
330 private int mScreenBrightnessSettingMaximum;
331 private int mScreenBrightnessSettingDefault;
332
333 // The screen brightness setting, from 0 to 255.
334 // Use -1 if no value has been set.
335 private int mScreenBrightnessSetting;
336
Jeff Brown330560f2012-08-21 22:10:57 -0700337 // The screen auto-brightness adjustment setting, from -1 to 1.
338 // Use 0 if there is no adjustment.
339 private float mScreenAutoBrightnessAdjustmentSetting;
340
Jeff Brown96307042012-07-27 15:51:34 -0700341 // The screen brightness mode.
342 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
343 private int mScreenBrightnessModeSetting;
344
345 // The screen brightness setting override from the window manager
346 // to allow the current foreground activity to override the brightness.
347 // Use -1 to disable.
348 private int mScreenBrightnessOverrideFromWindowManager = -1;
349
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700350 // The user activity timeout override from the window manager
351 // to allow the current foreground activity to override the user activity timeout.
352 // Use -1 to disable.
353 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
354
Jeff Brown96307042012-07-27 15:51:34 -0700355 // The screen brightness setting override from the settings application
356 // to temporarily adjust the brightness until next updated,
357 // Use -1 to disable.
358 private int mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359
Jeff Brown330560f2012-08-21 22:10:57 -0700360 // The screen brightness adjustment setting override from the settings
361 // application to temporarily adjust the auto-brightness adjustment factor
362 // until next updated, in the range -1..1.
363 // Use NaN to disable.
364 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
365
Jeff Brown9ba8d782012-10-01 16:38:23 -0700366 // Time when we last logged a warning about calling userActivity() without permission.
367 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
368
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700369 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370
Jeff Brown96307042012-07-27 15:51:34 -0700371 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright);
372 private static native void nativeAcquireSuspendBlocker(String name);
373 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700374 private static native void nativeSetInteractive(boolean enable);
375 private static native void nativeSetAutoSuspend(boolean enable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376
Jeff Brown4f8ecd82012-06-18 18:29:13 -0700377 public PowerManagerService() {
Jeff Brown96307042012-07-27 15:51:34 -0700378 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800379 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
380 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
381 mDisplaySuspendBlocker.acquire();
382 mHoldingDisplaySuspendBlocker = true;
383
Jeff Brownc38c9be2012-10-04 13:16:19 -0700384 mScreenOnBlocker = new ScreenOnBlockerImpl();
Jeff Brown9e316a12012-10-08 19:17:06 -0700385 mDisplayBlanker = new DisplayBlankerImpl();
Jeff Brown96307042012-07-27 15:51:34 -0700386 mWakefulness = WAKEFULNESS_AWAKE;
387 }
Jeff Brown7304c342012-05-11 18:42:42 -0700388
389 nativeInit();
Jeff Brownf75724b2012-08-25 13:34:32 -0700390 nativeSetPowerState(true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 }
392
Jeff Brown6f357d32014-01-15 20:40:55 -0800393 @Override
394 public void onCreate(Context context) {
395 mContext = context;
396 }
397
398 @Override
399 public void onStart() {
400 publishBinderService(Context.POWER_SERVICE, new BinderService());
401 publishLocalService(PowerManagerInternal.class, new LocalService());
402 }
403
Jeff Brown96307042012-07-27 15:51:34 -0700404 /**
405 * Initialize the power manager.
406 * Must be called before any other functions within the power manager are called.
407 */
Jeff Brown6f357d32014-01-15 20:40:55 -0800408 public void init(LightsManager ls,
Adam Lesinski182f73f2013-12-05 16:48:06 -0800409 BatteryService bs, IBatteryStats bss,
Jeff Brown4ccb8232014-01-16 22:16:42 -0800410 IAppOpsService appOps) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800411 mLightsManager = ls;
Jeff Brown9e316a12012-10-08 19:17:06 -0700412 mBatteryService = bs;
413 mBatteryStats = bss;
Dianne Hackborn713df152013-05-17 11:27:57 -0700414 mAppOps = appOps;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800415 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
416 mHandlerThread = new ServiceThread(TAG,
417 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
Jeff Brown9e316a12012-10-08 19:17:06 -0700418 mHandlerThread.start();
419 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
420
421 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800422 Watchdog.getInstance().addThread(mHandler);
Jeff Brown9e316a12012-10-08 19:17:06 -0700423
Jeff Brownf75724b2012-08-25 13:34:32 -0700424 // Forcibly turn the screen on at boot so that it is in a known power state.
425 // We do this in init() rather than in the constructor because setting the
426 // screen state requires a call into surface flinger which then needs to call back
427 // into the activity manager to check permissions. Unfortunately the
428 // activity manager is not running when the constructor is called, so we
429 // have to defer setting the screen state until this point.
Jeff Brown9e316a12012-10-08 19:17:06 -0700430 mDisplayBlanker.unblankAllDisplays();
Jeff Brown96307042012-07-27 15:51:34 -0700431 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800432
Jeff Brown6f357d32014-01-15 20:40:55 -0800433 void setPolicy(WindowManagerPolicy policy) {
Jeff Brown96307042012-07-27 15:51:34 -0700434 synchronized (mLock) {
435 mPolicy = policy;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800438
Adam Lesinski182f73f2013-12-05 16:48:06 -0800439 public void systemReady(TwilightManager twilight, DreamManagerService dreamManager) {
Jeff Brown96307042012-07-27 15:51:34 -0700440 synchronized (mLock) {
441 mSystemReady = true;
Jeff Brown62c82e42012-09-26 01:30:41 -0700442 mDreamManager = dreamManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443
Adam Lesinski182f73f2013-12-05 16:48:06 -0800444 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700445 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
446 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
447 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700449 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800450
Jeff Brownc38c9be2012-10-04 13:16:19 -0700451 // The notifier runs on the system server's main looper so as not to interfere
452 // with the animations and other critical functions of the power manager.
453 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Dianne Hackborn713df152013-05-17 11:27:57 -0700454 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
Jeff Brownc38c9be2012-10-04 13:16:19 -0700455 mScreenOnBlocker, mPolicy);
456
457 // The display power controller runs on the power manager service's
Jeff Brown3b971592013-01-09 18:46:37 -0800458 // own handler thread to ensure timely operation.
Jeff Brown96307042012-07-27 15:51:34 -0700459 mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(),
Adam Lesinski182f73f2013-12-05 16:48:06 -0800460 mContext, mNotifier, mLightsManager, twilight, sensorManager,
Jeff Brown4ccb8232014-01-16 22:16:42 -0800461 mDisplaySuspendBlocker, mDisplayBlanker,
Jeff Brown3b971592013-01-09 18:46:37 -0800462 mDisplayPowerControllerCallbacks, mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463
Jeff Brown3b971592013-01-09 18:46:37 -0800464 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700465 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
466 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700467 mSettingsObserver = new SettingsObserver(mHandler);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800468 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400469
Jeff Brown96307042012-07-27 15:51:34 -0700470 // Register for broadcasts from other components of the system.
471 IntentFilter filter = new IntentFilter();
472 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Jeff Brownd4935962012-09-25 13:27:20 -0700473 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700474
Jeff Brown96307042012-07-27 15:51:34 -0700475 filter = new IntentFilter();
476 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
Jeff Brownd4935962012-09-25 13:27:20 -0700477 mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700478
479 filter = new IntentFilter();
Dianne Hackbornbe87e2f2012-09-28 16:31:34 -0700480 filter.addAction(Intent.ACTION_DREAMING_STARTED);
481 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
Jeff Brownd4935962012-09-25 13:27:20 -0700482 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
483
484 filter = new IntentFilter();
485 filter.addAction(Intent.ACTION_USER_SWITCHED);
486 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
John Spurlockf4f6b4c2012-08-25 12:08:03 -0400487
Jeff Brownec6aa592012-10-17 20:30:25 -0700488 filter = new IntentFilter();
489 filter.addAction(Intent.ACTION_DOCK_EVENT);
490 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
491
Jeff Brown96307042012-07-27 15:51:34 -0700492 // Register for settings changes.
493 final ContentResolver resolver = mContext.getContentResolver();
494 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700495 Settings.Secure.SCREENSAVER_ENABLED),
496 false, mSettingsObserver, UserHandle.USER_ALL);
John Spurlock1a868b72012-08-22 09:56:51 -0400497 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700498 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
499 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brownec6aa592012-10-17 20:30:25 -0700500 resolver.registerContentObserver(Settings.Secure.getUriFor(
501 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
502 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700503 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700504 Settings.System.SCREEN_OFF_TIMEOUT),
505 false, mSettingsObserver, UserHandle.USER_ALL);
Christopher Tatead735322012-09-07 14:19:43 -0700506 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700507 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
508 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700509 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700510 Settings.System.SCREEN_BRIGHTNESS),
511 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700512 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Brownd4935962012-09-25 13:27:20 -0700513 Settings.System.SCREEN_BRIGHTNESS_MODE),
514 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Brown96307042012-07-27 15:51:34 -0700515
516 // Go.
517 readConfigurationLocked();
518 updateSettingsLocked();
519 mDirty |= DIRTY_BATTERY_STATE;
520 updatePowerStateLocked();
521 }
522 }
523
524 private void readConfigurationLocked() {
525 final Resources resources = mContext.getResources();
526
527 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700528 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Jeff Brownec083212013-09-11 20:45:25 -0700529 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
530 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700531 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400532 com.android.internal.R.bool.config_dreamsSupported);
533 mDreamsEnabledByDefaultConfig = resources.getBoolean(
534 com.android.internal.R.bool.config_dreamsEnabledByDefault);
535 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
536 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
537 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
538 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 }
540
Jeff Brown96307042012-07-27 15:51:34 -0700541 private void updateSettingsLocked() {
542 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700543
Jeff Brownd4935962012-09-25 13:27:20 -0700544 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400545 Settings.Secure.SCREENSAVER_ENABLED,
546 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700547 UserHandle.USER_CURRENT) != 0);
548 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400549 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
550 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700551 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700552 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400553 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
554 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700555 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700556 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
557 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
558 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700559 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700560 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Jeff Brown7304c342012-05-11 18:42:42 -0700561
Jeff Brown96307042012-07-27 15:51:34 -0700562 final int oldScreenBrightnessSetting = mScreenBrightnessSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700563 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver,
564 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault,
565 UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700566 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) {
567 mTemporaryScreenBrightnessSettingOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 }
Jeff Brown96307042012-07-27 15:51:34 -0700569
Jeff Brown330560f2012-08-21 22:10:57 -0700570 final float oldScreenAutoBrightnessAdjustmentSetting =
571 mScreenAutoBrightnessAdjustmentSetting;
Jeff Brownd4935962012-09-25 13:27:20 -0700572 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver,
573 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f,
574 UserHandle.USER_CURRENT);
Jeff Brown330560f2012-08-21 22:10:57 -0700575 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) {
Jeff Brown5d03a532012-08-22 13:22:02 -0700576 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN;
Jeff Brown330560f2012-08-21 22:10:57 -0700577 }
578
Jeff Brownd4935962012-09-25 13:27:20 -0700579 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700580 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700581 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700582
583 mDirty |= DIRTY_SETTINGS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585
Jeff Brown96307042012-07-27 15:51:34 -0700586 private void handleSettingsChangedLocked() {
587 updateSettingsLocked();
588 updatePowerStateLocked();
589 }
590
Dianne Hackborn713df152013-05-17 11:27:57 -0700591 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
592 WorkSource ws, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700593 synchronized (mLock) {
594 if (DEBUG_SPEW) {
595 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
596 + ", flags=0x" + Integer.toHexString(flags)
597 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599
Jeff Brown96307042012-07-27 15:51:34 -0700600 WakeLock wakeLock;
601 int index = findWakeLockIndexLocked(lock);
602 if (index >= 0) {
603 wakeLock = mWakeLocks.get(index);
604 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
605 // Update existing wake lock. This shouldn't happen but is harmless.
606 notifyWakeLockReleasedLocked(wakeLock);
Dianne Hackborn713df152013-05-17 11:27:57 -0700607 wakeLock.updateProperties(flags, tag, packageName, ws, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700608 notifyWakeLockAcquiredLocked(wakeLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 } else {
Dianne Hackborn713df152013-05-17 11:27:57 -0700611 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, uid, pid);
Jeff Brown96307042012-07-27 15:51:34 -0700612 try {
613 lock.linkToDeath(wakeLock, 0);
614 } catch (RemoteException ex) {
615 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
Jeff Brown96307042012-07-27 15:51:34 -0700617 notifyWakeLockAcquiredLocked(wakeLock);
618 mWakeLocks.add(wakeLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
Jeff Brown96307042012-07-27 15:51:34 -0700621 applyWakeLockFlagsOnAcquireLocked(wakeLock);
622 mDirty |= DIRTY_WAKE_LOCKS;
623 updatePowerStateLocked();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700624 }
625 }
626
Jeff Brownec083212013-09-11 20:45:25 -0700627 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -0800628 private static boolean isScreenLock(final WakeLock wakeLock) {
629 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
630 case PowerManager.FULL_WAKE_LOCK:
631 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
632 case PowerManager.SCREEN_DIM_WAKE_LOCK:
633 return true;
634 }
635 return false;
636 }
637
Jeff Brown96307042012-07-27 15:51:34 -0700638 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700639 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
640 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700641 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 }
643 }
644
Jeff Brown96307042012-07-27 15:51:34 -0700645 private void releaseWakeLockInternal(IBinder lock, int flags) {
646 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -0700647 int index = findWakeLockIndexLocked(lock);
648 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800649 if (DEBUG_SPEW) {
650 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
651 + " [not found], flags=0x" + Integer.toHexString(flags));
652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 return;
654 }
Mike Lockwood3333fa42009-10-26 14:50:42 -0400655
Jeff Brown96307042012-07-27 15:51:34 -0700656 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800657 if (DEBUG_SPEW) {
658 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
659 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
660 }
661
Jeff Brown96307042012-07-27 15:51:34 -0700662 mWakeLocks.remove(index);
663 notifyWakeLockReleasedLocked(wakeLock);
664 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
665
666 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) {
667 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
669
Jeff Brown96307042012-07-27 15:51:34 -0700670 applyWakeLockFlagsOnReleaseLocked(wakeLock);
671 mDirty |= DIRTY_WAKE_LOCKS;
672 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700675
Jeff Brown96307042012-07-27 15:51:34 -0700676 private void handleWakeLockDeath(WakeLock wakeLock) {
677 synchronized (mLock) {
678 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800679 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
680 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -0700681 }
682
683 int index = mWakeLocks.indexOf(wakeLock);
684 if (index < 0) {
685 return;
686 }
687
688 mWakeLocks.remove(index);
689 notifyWakeLockReleasedLocked(wakeLock);
690
691 applyWakeLockFlagsOnReleaseLocked(wakeLock);
692 mDirty |= DIRTY_WAKE_LOCKS;
693 updatePowerStateLocked();
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700694 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800696
Jeff Brown96307042012-07-27 15:51:34 -0700697 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -0700698 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
699 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -0700700 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
701 PowerManager.USER_ACTIVITY_EVENT_OTHER,
702 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
703 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706
Jeff Brown96307042012-07-27 15:51:34 -0700707 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) {
708 synchronized (mLock) {
709 int index = findWakeLockIndexLocked(lock);
710 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800711 if (DEBUG_SPEW) {
712 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
713 + " [not found], ws=" + ws);
714 }
Jeff Brown96307042012-07-27 15:51:34 -0700715 throw new IllegalArgumentException("Wake lock not active");
716 }
717
718 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -0800719 if (DEBUG_SPEW) {
720 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
721 + " [" + wakeLock.mTag + "], ws=" + ws);
722 }
723
Jeff Brown96307042012-07-27 15:51:34 -0700724 if (!wakeLock.hasSameWorkSource(ws)) {
725 notifyWakeLockReleasedLocked(wakeLock);
726 wakeLock.updateWorkSource(ws);
727 notifyWakeLockAcquiredLocked(wakeLock);
728 }
729 }
730 }
731
732 private int findWakeLockIndexLocked(IBinder lock) {
733 final int count = mWakeLocks.size();
734 for (int i = 0; i < count; i++) {
735 if (mWakeLocks.get(i).mLock == lock) {
736 return i;
737 }
738 }
739 return -1;
740 }
741
742 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
743 if (mSystemReady) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700744 wakeLock.mNotifiedAcquired = true;
745 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Jeff Brown96307042012-07-27 15:51:34 -0700746 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
747 }
748 }
749
750 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700751 if (mSystemReady && wakeLock.mNotifiedAcquired) {
752 wakeLock.mNotifiedAcquired = false;
753 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Jeff Brown96307042012-07-27 15:51:34 -0700754 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource);
755 }
756 }
757
Jeff Brownec083212013-09-11 20:45:25 -0700758 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700759 private boolean isWakeLockLevelSupportedInternal(int level) {
760 synchronized (mLock) {
761 switch (level) {
762 case PowerManager.PARTIAL_WAKE_LOCK:
763 case PowerManager.SCREEN_DIM_WAKE_LOCK:
764 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
765 case PowerManager.FULL_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700766 return true;
Jeff Brown96307042012-07-27 15:51:34 -0700767
768 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
769 return mSystemReady && mDisplayPowerController.isProximitySensorAvailable();
770
771 default:
772 return false;
773 }
774 }
775 }
776
Jeff Brown96307042012-07-27 15:51:34 -0700777 // Called from native code.
778 private void userActivityFromNative(long eventTime, int event, int flags) {
779 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
780 }
781
782 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
783 synchronized (mLock) {
784 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
785 updatePowerStateLocked();
786 }
787 }
788 }
789
790 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
791 if (DEBUG_SPEW) {
792 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
793 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
794 + ", uid=" + uid);
795 }
796
797 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
798 || mWakefulness == WAKEFULNESS_ASLEEP || !mBootCompleted || !mSystemReady) {
799 return false;
800 }
801
802 mNotifier.onUserActivity(event, uid);
803
804 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
805 if (eventTime > mLastUserActivityTimeNoChangeLights
806 && eventTime > mLastUserActivityTime) {
807 mLastUserActivityTimeNoChangeLights = eventTime;
808 mDirty |= DIRTY_USER_ACTIVITY;
809 return true;
810 }
811 } else {
812 if (eventTime > mLastUserActivityTime) {
813 mLastUserActivityTime = eventTime;
814 mDirty |= DIRTY_USER_ACTIVITY;
815 return true;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700816 }
817 }
818 return false;
819 }
820
Jeff Brown96307042012-07-27 15:51:34 -0700821 // Called from native code.
822 private void wakeUpFromNative(long eventTime) {
823 wakeUpInternal(eventTime);
824 }
825
826 private void wakeUpInternal(long eventTime) {
827 synchronized (mLock) {
828 if (wakeUpNoUpdateLocked(eventTime)) {
829 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700830 }
831 }
Jeff Brown96307042012-07-27 15:51:34 -0700832 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700833
Jeff Brown96307042012-07-27 15:51:34 -0700834 private boolean wakeUpNoUpdateLocked(long eventTime) {
835 if (DEBUG_SPEW) {
836 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime);
Joe Onorato60607a92010-10-23 14:49:30 -0700837 }
Jeff Brown96307042012-07-27 15:51:34 -0700838
839 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
840 || !mBootCompleted || !mSystemReady) {
841 return false;
842 }
843
844 switch (mWakefulness) {
845 case WAKEFULNESS_ASLEEP:
846 Slog.i(TAG, "Waking up from sleep...");
Jeff Brown54308352012-10-04 17:59:58 -0700847 sendPendingNotificationsLocked();
Jeff Brown96307042012-07-27 15:51:34 -0700848 mNotifier.onWakeUpStarted();
849 mSendWakeUpFinishedNotificationWhenReady = true;
Jeff Brown96307042012-07-27 15:51:34 -0700850 break;
851 case WAKEFULNESS_DREAMING:
852 Slog.i(TAG, "Waking up from dream...");
853 break;
854 case WAKEFULNESS_NAPPING:
855 Slog.i(TAG, "Waking up from nap...");
856 break;
857 }
858
859 mLastWakeTime = eventTime;
860 mWakefulness = WAKEFULNESS_AWAKE;
861 mDirty |= DIRTY_WAKEFULNESS;
862
863 userActivityNoUpdateLocked(
864 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
865 return true;
866 }
867
Jeff Brown96307042012-07-27 15:51:34 -0700868 // Called from native code.
869 private void goToSleepFromNative(long eventTime, int reason) {
870 goToSleepInternal(eventTime, reason);
871 }
872
873 private void goToSleepInternal(long eventTime, int reason) {
874 synchronized (mLock) {
875 if (goToSleepNoUpdateLocked(eventTime, reason)) {
876 updatePowerStateLocked();
877 }
878 }
879 }
880
Jeff Brownec083212013-09-11 20:45:25 -0700881 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -0700882 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) {
883 if (DEBUG_SPEW) {
884 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason);
885 }
886
887 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
888 || !mBootCompleted || !mSystemReady) {
889 return false;
890 }
891
892 switch (reason) {
893 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
894 Slog.i(TAG, "Going to sleep due to device administration policy...");
895 break;
896 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
897 Slog.i(TAG, "Going to sleep due to screen timeout...");
898 break;
899 default:
900 Slog.i(TAG, "Going to sleep by user request...");
901 reason = PowerManager.GO_TO_SLEEP_REASON_USER;
902 break;
903 }
904
Jeff Brown54308352012-10-04 17:59:58 -0700905 sendPendingNotificationsLocked();
906 mNotifier.onGoToSleepStarted(reason);
907 mSendGoToSleepFinishedNotificationWhenReady = true;
908
Jeff Brown96307042012-07-27 15:51:34 -0700909 mLastSleepTime = eventTime;
910 mDirty |= DIRTY_WAKEFULNESS;
911 mWakefulness = WAKEFULNESS_ASLEEP;
Jeff Brown96307042012-07-27 15:51:34 -0700912
913 // Report the number of wake locks that will be cleared by going to sleep.
914 int numWakeLocksCleared = 0;
915 final int numWakeLocks = mWakeLocks.size();
916 for (int i = 0; i < numWakeLocks; i++) {
917 final WakeLock wakeLock = mWakeLocks.get(i);
918 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
919 case PowerManager.FULL_WAKE_LOCK:
920 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
921 case PowerManager.SCREEN_DIM_WAKE_LOCK:
922 numWakeLocksCleared += 1;
923 break;
924 }
925 }
926 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);
927 return true;
928 }
929
Jeff Brown62c82e42012-09-26 01:30:41 -0700930 private void napInternal(long eventTime) {
931 synchronized (mLock) {
932 if (napNoUpdateLocked(eventTime)) {
933 updatePowerStateLocked();
934 }
935 }
936 }
937
938 private boolean napNoUpdateLocked(long eventTime) {
939 if (DEBUG_SPEW) {
940 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime);
941 }
942
943 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
944 || !mBootCompleted || !mSystemReady) {
945 return false;
946 }
947
948 Slog.i(TAG, "Nap time...");
949
950 mDirty |= DIRTY_WAKEFULNESS;
951 mWakefulness = WAKEFULNESS_NAPPING;
952 return true;
953 }
954
Jeff Brown96307042012-07-27 15:51:34 -0700955 /**
956 * Updates the global power state based on dirty bits recorded in mDirty.
957 *
958 * This is the main function that performs power state transitions.
959 * We centralize them here so that we can recompute the power state completely
960 * each time something important changes, and ensure that we do it the same
961 * way each time. The point is to gather all of the transition logic here.
962 */
963 private void updatePowerStateLocked() {
964 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700965 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800967
Jeff Brown96307042012-07-27 15:51:34 -0700968 // Phase 0: Basic state updates.
969 updateIsPoweredLocked(mDirty);
970 updateStayOnLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
Jeff Brown96307042012-07-27 15:51:34 -0700972 // Phase 1: Update wakefulness.
973 // Loop because the wake lock and user activity computations are influenced
974 // by changes in wakefulness.
975 final long now = SystemClock.uptimeMillis();
976 int dirtyPhase2 = 0;
977 for (;;) {
978 int dirtyPhase1 = mDirty;
979 dirtyPhase2 |= dirtyPhase1;
980 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800981
Jeff Brown96307042012-07-27 15:51:34 -0700982 updateWakeLockSummaryLocked(dirtyPhase1);
983 updateUserActivitySummaryLocked(now, dirtyPhase1);
984 if (!updateWakefulnessLocked(dirtyPhase1)) {
985 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987 }
988
Jeff Brown96307042012-07-27 15:51:34 -0700989 // Phase 2: Update dreams and display power state.
990 updateDreamLocked(dirtyPhase2);
991 updateDisplayPowerStateLocked(dirtyPhase2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992
Jeff Brown96307042012-07-27 15:51:34 -0700993 // Phase 3: Send notifications, if needed.
Jeff Brown54308352012-10-04 17:59:58 -0700994 if (mDisplayReady) {
995 sendPendingNotificationsLocked();
996 }
Craig Mautner75fc9de2012-06-18 16:53:27 -0700997
Jeff Brown96307042012-07-27 15:51:34 -0700998 // Phase 4: Update suspend blocker.
999 // Because we might release the last suspend blocker here, we need to make sure
1000 // we finished everything else first!
1001 updateSuspendBlockerLocked();
1002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003
Jeff Brown96307042012-07-27 15:51:34 -07001004 private void sendPendingNotificationsLocked() {
Jeff Brown54308352012-10-04 17:59:58 -07001005 if (mSendWakeUpFinishedNotificationWhenReady) {
1006 mSendWakeUpFinishedNotificationWhenReady = false;
1007 mNotifier.onWakeUpFinished();
1008 }
1009 if (mSendGoToSleepFinishedNotificationWhenReady) {
1010 mSendGoToSleepFinishedNotificationWhenReady = false;
1011 mNotifier.onGoToSleepFinished();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014
Jim Miller92e66dd2012-02-21 18:57:12 -08001015 /**
Jeff Brown96307042012-07-27 15:51:34 -07001016 * Updates the value of mIsPowered.
1017 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001018 */
Jeff Brown96307042012-07-27 15:51:34 -07001019 private void updateIsPoweredLocked(int dirty) {
1020 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001021 final boolean wasPowered = mIsPowered;
1022 final int oldPlugType = mPlugType;
Jeff Browna4d82042012-10-02 19:11:19 -07001023 mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
Jeff Brownf3fb8952012-10-02 20:57:05 -07001024 mPlugType = mBatteryService.getPlugType();
Jeff Brown016ff142012-10-15 16:47:22 -07001025 mBatteryLevel = mBatteryService.getBatteryLevel();
Jeff Browna4d82042012-10-02 19:11:19 -07001026
1027 if (DEBUG) {
1028 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001029 + ", mIsPowered=" + mIsPowered
1030 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001031 + ", mPlugType=" + mPlugType
1032 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001033 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001034
Jeff Brownf3fb8952012-10-02 20:57:05 -07001035 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001036 mDirty |= DIRTY_IS_POWERED;
1037
Jeff Brown3b971592013-01-09 18:46:37 -08001038 // Update wireless dock detection state.
1039 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
1040 mIsPowered, mPlugType, mBatteryLevel);
1041
Jeff Brown96307042012-07-27 15:51:34 -07001042 // Treat plugging and unplugging the devices as a user activity.
1043 // Users find it disconcerting when they plug or unplug the device
1044 // and it shuts off right away.
1045 // Some devices also wake the device when plugged or unplugged because
1046 // they don't have a charging LED.
1047 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001048 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1049 dockedOnWirelessCharger)) {
Jeff Brown96307042012-07-27 15:51:34 -07001050 wakeUpNoUpdateLocked(now);
1051 }
1052 userActivityNoUpdateLocked(
1053 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001054
1055 // Tell the notifier whether wireless charging has started so that
Jeff Brown3b971592013-01-09 18:46:37 -08001056 // it can provide feedback to the user.
1057 if (dockedOnWirelessCharger) {
Jeff Brown84e27562012-12-07 13:56:34 -08001058 mNotifier.onWirelessChargingStarted();
1059 }
Jeff Brown96307042012-07-27 15:51:34 -07001060 }
1061 }
1062 }
1063
Jeff Brown3b971592013-01-09 18:46:37 -08001064 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1065 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001066 // Don't wake when powered unless configured to do so.
1067 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1068 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001069 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001070
Jeff Brown3b971592013-01-09 18:46:37 -08001071 // Don't wake when undocked from wireless charger.
1072 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001073 if (wasPowered && !mIsPowered
1074 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1075 return false;
1076 }
Jeff Brown3b971592013-01-09 18:46:37 -08001077
1078 // Don't wake when docked on wireless charger unless we are certain of it.
1079 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001080 if (!wasPowered && mIsPowered
1081 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001082 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001083 return false;
1084 }
1085
1086 // If already dreaming and becoming powered, then don't wake.
1087 if (mIsPowered && (mWakefulness == WAKEFULNESS_NAPPING
1088 || mWakefulness == WAKEFULNESS_DREAMING)) {
1089 return false;
1090 }
1091
1092 // Otherwise wake up!
1093 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001094 }
1095
Jeff Brown96307042012-07-27 15:51:34 -07001096 /**
1097 * Updates the value of mStayOn.
1098 * Sets DIRTY_STAY_ON if a change occurred.
1099 */
1100 private void updateStayOnLocked(int dirty) {
1101 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001102 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001103 if (mStayOnWhilePluggedInSetting != 0
1104 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1105 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting);
1106 } else {
1107 mStayOn = false;
1108 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001109
1110 if (mStayOn != wasStayOn) {
1111 mDirty |= DIRTY_STAY_ON;
1112 }
Jeff Brown96307042012-07-27 15:51:34 -07001113 }
1114 }
1115
1116 /**
1117 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1118 * Note that most wake-locks are ignored when the system is asleep.
1119 *
1120 * This function must have no other side-effects.
1121 */
Jeff Brownec083212013-09-11 20:45:25 -07001122 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001123 private void updateWakeLockSummaryLocked(int dirty) {
1124 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1125 mWakeLockSummary = 0;
1126
1127 final int numWakeLocks = mWakeLocks.size();
1128 for (int i = 0; i < numWakeLocks; i++) {
1129 final WakeLock wakeLock = mWakeLocks.get(i);
1130 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1131 case PowerManager.PARTIAL_WAKE_LOCK:
1132 mWakeLockSummary |= WAKE_LOCK_CPU;
1133 break;
1134 case PowerManager.FULL_WAKE_LOCK:
1135 if (mWakefulness != WAKEFULNESS_ASLEEP) {
1136 mWakeLockSummary |= WAKE_LOCK_CPU
1137 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
Jeff Brown10428742012-10-09 15:47:30 -07001138 if (mWakefulness == WAKEFULNESS_AWAKE) {
1139 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1140 }
Jeff Brown96307042012-07-27 15:51:34 -07001141 }
1142 break;
1143 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1144 if (mWakefulness != WAKEFULNESS_ASLEEP) {
1145 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT;
Jeff Brown10428742012-10-09 15:47:30 -07001146 if (mWakefulness == WAKEFULNESS_AWAKE) {
1147 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1148 }
Jeff Brown96307042012-07-27 15:51:34 -07001149 }
1150 break;
1151 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1152 if (mWakefulness != WAKEFULNESS_ASLEEP) {
1153 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM;
Jeff Brown10428742012-10-09 15:47:30 -07001154 if (mWakefulness == WAKEFULNESS_AWAKE) {
1155 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE;
1156 }
Jeff Brown96307042012-07-27 15:51:34 -07001157 }
1158 break;
1159 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1160 if (mWakefulness != WAKEFULNESS_ASLEEP) {
Jeff Brownec083212013-09-11 20:45:25 -07001161 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07001162 }
1163 break;
1164 }
1165 }
1166
1167 if (DEBUG_SPEW) {
1168 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
1169 + wakefulnessToString(mWakefulness)
1170 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1171 }
1172 }
1173 }
1174
1175 /**
1176 * Updates the value of mUserActivitySummary to summarize the user requested
1177 * state of the system such as whether the screen should be bright or dim.
1178 * Note that user activity is ignored when the system is asleep.
1179 *
1180 * This function must have no other side-effects.
1181 */
1182 private void updateUserActivitySummaryLocked(long now, int dirty) {
1183 // Update the status of the user activity timeout timer.
1184 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
1185 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1186
1187 long nextTimeout = 0;
1188 if (mWakefulness != WAKEFULNESS_ASLEEP) {
1189 final int screenOffTimeout = getScreenOffTimeoutLocked();
Jeff Brownff532542012-10-02 21:18:04 -07001190 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07001191
1192 mUserActivitySummary = 0;
1193 if (mLastUserActivityTime >= mLastWakeTime) {
1194 nextTimeout = mLastUserActivityTime
1195 + screenOffTimeout - screenDimDuration;
1196 if (now < nextTimeout) {
1197 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT;
1198 } else {
1199 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1200 if (now < nextTimeout) {
1201 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM;
1202 }
1203 }
1204 }
1205 if (mUserActivitySummary == 0
1206 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1207 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
1208 if (now < nextTimeout
1209 && mDisplayPowerRequest.screenState
1210 != DisplayPowerRequest.SCREEN_STATE_OFF) {
1211 mUserActivitySummary = mDisplayPowerRequest.screenState
1212 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ?
1213 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM;
1214 }
1215 }
1216 if (mUserActivitySummary != 0) {
1217 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
1218 msg.setAsynchronous(true);
1219 mHandler.sendMessageAtTime(msg, nextTimeout);
1220 }
1221 } else {
1222 mUserActivitySummary = 0;
1223 }
1224
1225 if (DEBUG_SPEW) {
1226 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
1227 + wakefulnessToString(mWakefulness)
1228 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1229 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
1230 }
1231 }
1232 }
1233
1234 /**
1235 * Called when a user activity timeout has occurred.
1236 * Simply indicates that something about user activity has changed so that the new
1237 * state can be recomputed when the power state is updated.
1238 *
1239 * This function must have no other side-effects besides setting the dirty
1240 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
1241 */
1242 private void handleUserActivityTimeout() { // runs on handler thread
1243 synchronized (mLock) {
1244 if (DEBUG_SPEW) {
1245 Slog.d(TAG, "handleUserActivityTimeout");
1246 }
1247
1248 mDirty |= DIRTY_USER_ACTIVITY;
1249 updatePowerStateLocked();
1250 }
1251 }
1252
1253 private int getScreenOffTimeoutLocked() {
1254 int timeout = mScreenOffTimeoutSetting;
1255 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
1256 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
1257 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001258 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
1259 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
1260 }
Jeff Brown96307042012-07-27 15:51:34 -07001261 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT);
1262 }
1263
Jeff Brownff532542012-10-02 21:18:04 -07001264 private int getScreenDimDurationLocked(int screenOffTimeout) {
1265 return Math.min(SCREEN_DIM_DURATION,
1266 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO));
Jeff Brown96307042012-07-27 15:51:34 -07001267 }
1268
1269 /**
1270 * Updates the wakefulness of the device.
1271 *
1272 * This is the function that decides whether the device should start napping
1273 * based on the current wake locks and user activity state. It may modify mDirty
1274 * if the wakefulness changes.
1275 *
1276 * Returns true if the wakefulness changed and we need to restart power state calculation.
1277 */
1278 private boolean updateWakefulnessLocked(int dirty) {
1279 boolean changed = false;
1280 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07001281 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
1282 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001283 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
1284 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001285 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07001286 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001287 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07001288 if (shouldNapAtBedTimeLocked()) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001289 changed = napNoUpdateLocked(time);
1290 } else {
1291 changed = goToSleepNoUpdateLocked(time,
1292 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1293 }
Jeff Brown96307042012-07-27 15:51:34 -07001294 }
1295 }
1296 return changed;
1297 }
1298
Jeff Brown645832d2012-10-03 14:57:03 -07001299 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07001300 * Returns true if the device should automatically nap and start dreaming when the user
1301 * activity timeout has expired and it's bedtime.
1302 */
1303 private boolean shouldNapAtBedTimeLocked() {
1304 return mDreamsActivateOnSleepSetting
1305 || (mDreamsActivateOnDockSetting
1306 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
1307 }
1308
1309 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001310 * Returns true if the device should go to sleep now.
1311 * Also used when exiting a dream to determine whether we should go back
1312 * to being fully awake or else go to sleep for good.
1313 */
Jeff Brown96307042012-07-27 15:51:34 -07001314 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001315 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07001316 }
1317
1318 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07001319 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07001320 * or the stay on while powered setting. We also keep the phone awake when
1321 * the proximity sensor returns a positive result so that the device does not
1322 * lock while in a phone call. This function only controls whether the device
1323 * will go to sleep or dream which is independent of whether it will be allowed
1324 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07001325 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07001326 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001327 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07001328 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07001329 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07001330 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
1331 | USER_ACTIVITY_SCREEN_DIM)) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07001332 }
1333
1334 /**
1335 * Determines whether to post a message to the sandman to update the dream state.
1336 */
1337 private void updateDreamLocked(int dirty) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001338 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07001339 | DIRTY_USER_ACTIVITY
1340 | DIRTY_WAKE_LOCKS
1341 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04001342 | DIRTY_SETTINGS
1343 | DIRTY_IS_POWERED
1344 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07001345 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown62c82e42012-09-26 01:30:41 -07001346 | DIRTY_BATTERY_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001347 scheduleSandmanLocked();
1348 }
1349 }
1350
1351 private void scheduleSandmanLocked() {
1352 if (!mSandmanScheduled) {
1353 mSandmanScheduled = true;
1354 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
1355 msg.setAsynchronous(true);
1356 mHandler.sendMessage(msg);
1357 }
1358 }
1359
1360 /**
1361 * Called when the device enters or exits a napping or dreaming state.
1362 *
1363 * We do this asynchronously because we must call out of the power manager to start
1364 * the dream and we don't want to hold our lock while doing so. There is a risk that
1365 * the device will wake or go to sleep in the meantime so we have to handle that case.
1366 */
1367 private void handleSandman() { // runs on handler thread
1368 // Handle preconditions.
1369 boolean startDreaming = false;
1370 synchronized (mLock) {
1371 mSandmanScheduled = false;
John Spurlock10fb2242012-08-23 15:32:28 -04001372 boolean canDream = canDreamLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001373 if (DEBUG_SPEW) {
Jeff Brown016ff142012-10-15 16:47:22 -07001374 Slog.d(TAG, "handleSandman: canDream=" + canDream
Jeff Brown96307042012-07-27 15:51:34 -07001375 + ", mWakefulness=" + wakefulnessToString(mWakefulness));
1376 }
1377
John Spurlock10fb2242012-08-23 15:32:28 -04001378 if (canDream && mWakefulness == WAKEFULNESS_NAPPING) {
Jeff Brown96307042012-07-27 15:51:34 -07001379 startDreaming = true;
1380 }
1381 }
1382
Jeff Brown96307042012-07-27 15:51:34 -07001383 // Start dreaming if needed.
1384 // We only control the dream on the handler thread, so we don't need to worry about
1385 // concurrent attempts to start or stop the dream.
1386 boolean isDreaming = false;
1387 if (mDreamManager != null) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001388 if (startDreaming) {
1389 mDreamManager.startDream();
Jeff Brown96307042012-07-27 15:51:34 -07001390 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001391 isDreaming = mDreamManager.isDreaming();
Jeff Brown96307042012-07-27 15:51:34 -07001392 }
1393
1394 // Update dream state.
1395 // We might need to stop the dream again if the preconditions changed.
1396 boolean continueDreaming = false;
1397 synchronized (mLock) {
1398 if (isDreaming && canDreamLocked()) {
1399 if (mWakefulness == WAKEFULNESS_NAPPING) {
1400 mWakefulness = WAKEFULNESS_DREAMING;
1401 mDirty |= DIRTY_WAKEFULNESS;
Jeff Brown016ff142012-10-15 16:47:22 -07001402 mBatteryLevelWhenDreamStarted = mBatteryLevel;
Jeff Brown96307042012-07-27 15:51:34 -07001403 updatePowerStateLocked();
1404 continueDreaming = true;
1405 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown016ff142012-10-15 16:47:22 -07001406 if (!isBeingKeptAwakeLocked()
1407 && mBatteryLevel < mBatteryLevelWhenDreamStarted
1408 - DREAM_BATTERY_LEVEL_DRAIN_CUTOFF) {
1409 // If the user activity timeout expired and the battery appears
1410 // to be draining faster than it is charging then stop dreaming
1411 // and go to sleep.
1412 Slog.i(TAG, "Stopping dream because the battery appears to "
1413 + "be draining faster than it is charging. "
1414 + "Battery level when dream started: "
1415 + mBatteryLevelWhenDreamStarted + "%. "
1416 + "Battery level now: " + mBatteryLevel + "%.");
1417 } else {
1418 continueDreaming = true;
1419 }
Jeff Brown96307042012-07-27 15:51:34 -07001420 }
1421 }
1422 if (!continueDreaming) {
1423 handleDreamFinishedLocked();
1424 }
Jeff Brown96307042012-07-27 15:51:34 -07001425 }
1426
1427 // Stop dreaming if needed.
1428 // It's possible that something else changed to make us need to start the dream again.
1429 // If so, then the power manager will have posted another message to the handler
1430 // to take care of it later.
1431 if (mDreamManager != null) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001432 if (!continueDreaming) {
1433 mDreamManager.stopDream();
Jeff Brown96307042012-07-27 15:51:34 -07001434 }
1435 }
1436 }
1437
1438 /**
Jeff Brown645832d2012-10-03 14:57:03 -07001439 * Returns true if the device is allowed to dream in its current state
1440 * assuming that it is currently napping or dreaming.
Jeff Brown96307042012-07-27 15:51:34 -07001441 */
1442 private boolean canDreamLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07001443 return mDreamsSupportedConfig
John Spurlock10fb2242012-08-23 15:32:28 -04001444 && mDreamsEnabledSetting
Jeff Brown645832d2012-10-03 14:57:03 -07001445 && mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF
1446 && mBootCompleted
Jeff Brown93cbbb22012-10-04 13:18:36 -07001447 && (mIsPowered || isBeingKeptAwakeLocked());
Jeff Brown96307042012-07-27 15:51:34 -07001448 }
1449
1450 /**
1451 * Called when a dream is ending to figure out what to do next.
1452 */
1453 private void handleDreamFinishedLocked() {
1454 if (mWakefulness == WAKEFULNESS_NAPPING
1455 || mWakefulness == WAKEFULNESS_DREAMING) {
1456 if (isItBedTimeYetLocked()) {
1457 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
1458 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
1459 updatePowerStateLocked();
1460 } else {
1461 wakeUpNoUpdateLocked(SystemClock.uptimeMillis());
1462 updatePowerStateLocked();
1463 }
1464 }
1465 }
1466
Jeff Brownc38c9be2012-10-04 13:16:19 -07001467 private void handleScreenOnBlockerReleased() {
1468 synchronized (mLock) {
1469 mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED;
1470 updatePowerStateLocked();
1471 }
1472 }
1473
Jeff Brown96307042012-07-27 15:51:34 -07001474 /**
1475 * Updates the display power state asynchronously.
1476 * When the update is finished, mDisplayReady will be set to true. The display
1477 * controller posts a message to tell us when the actual display power state
1478 * has been updated so we come back here to double-check and finish up.
1479 *
1480 * This function recalculates the display power state each time.
1481 */
1482 private void updateDisplayPowerStateLocked(int dirty) {
1483 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
1484 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Jeff Brownc38c9be2012-10-04 13:16:19 -07001485 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) {
1486 int newScreenState = getDesiredScreenPowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07001487 if (newScreenState != mDisplayPowerRequest.screenState) {
Jeff Brown96307042012-07-27 15:51:34 -07001488 mDisplayPowerRequest.screenState = newScreenState;
1489 nativeSetPowerState(
1490 newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF,
1491 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT);
1492 }
1493
1494 int screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001495 float screenAutoBrightnessAdjustment = 0.0f;
Jeff Brown96307042012-07-27 15:51:34 -07001496 boolean autoBrightness = (mScreenBrightnessModeSetting ==
1497 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
1498 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
1499 screenBrightness = mScreenBrightnessOverrideFromWindowManager;
1500 autoBrightness = false;
1501 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) {
1502 screenBrightness = mTemporaryScreenBrightnessSettingOverride;
1503 } else if (isValidBrightness(mScreenBrightnessSetting)) {
Jeff Brown330560f2012-08-21 22:10:57 -07001504 screenBrightness = mScreenBrightnessSetting;
Jeff Brown96307042012-07-27 15:51:34 -07001505 }
1506 if (autoBrightness) {
1507 screenBrightness = mScreenBrightnessSettingDefault;
Jeff Brown330560f2012-08-21 22:10:57 -07001508 if (isValidAutoBrightnessAdjustment(
1509 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) {
1510 screenAutoBrightnessAdjustment =
1511 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride;
1512 } else if (isValidAutoBrightnessAdjustment(
1513 mScreenAutoBrightnessAdjustmentSetting)) {
1514 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting;
1515 }
Jeff Brown96307042012-07-27 15:51:34 -07001516 }
1517 screenBrightness = Math.max(Math.min(screenBrightness,
1518 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum);
Jeff Brown330560f2012-08-21 22:10:57 -07001519 screenAutoBrightnessAdjustment = Math.max(Math.min(
1520 screenAutoBrightnessAdjustment, 1.0f), -1.0f);
Jeff Brown96307042012-07-27 15:51:34 -07001521 mDisplayPowerRequest.screenBrightness = screenBrightness;
Jeff Brown330560f2012-08-21 22:10:57 -07001522 mDisplayPowerRequest.screenAutoBrightnessAdjustment =
1523 screenAutoBrightnessAdjustment;
Jeff Brown96307042012-07-27 15:51:34 -07001524 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
1525
1526 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
1527
Jeff Brownc38c9be2012-10-04 13:16:19 -07001528 mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld();
1529
Jeff Brown96307042012-07-27 15:51:34 -07001530 mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest,
1531 mRequestWaitForNegativeProximity);
1532 mRequestWaitForNegativeProximity = false;
1533
1534 if (DEBUG_SPEW) {
Jeff Brownc38c9be2012-10-04 13:16:19 -07001535 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown96307042012-07-27 15:51:34 -07001536 + ", newScreenState=" + newScreenState
1537 + ", mWakefulness=" + mWakefulness
1538 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
1539 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
1540 + ", mBootCompleted=" + mBootCompleted);
1541 }
1542 }
1543 }
1544
1545 private static boolean isValidBrightness(int value) {
1546 return value >= 0 && value <= 255;
1547 }
1548
Jeff Brown330560f2012-08-21 22:10:57 -07001549 private static boolean isValidAutoBrightnessAdjustment(float value) {
Jeff Brown5d03a532012-08-22 13:22:02 -07001550 // Handles NaN by always returning false.
1551 return value >= -1.0f && value <= 1.0f;
Jeff Brown330560f2012-08-21 22:10:57 -07001552 }
1553
Jeff Brownc38c9be2012-10-04 13:16:19 -07001554 private int getDesiredScreenPowerStateLocked() {
Jeff Brown96307042012-07-27 15:51:34 -07001555 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1556 return DisplayPowerRequest.SCREEN_STATE_OFF;
1557 }
1558
1559 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
1560 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
1561 || !mBootCompleted) {
1562 return DisplayPowerRequest.SCREEN_STATE_BRIGHT;
1563 }
1564
1565 return DisplayPowerRequest.SCREEN_STATE_DIM;
1566 }
1567
1568 private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks =
1569 new DisplayPowerController.Callbacks() {
1570 @Override
1571 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001572 synchronized (mLock) {
1573 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
1574 updatePowerStateLocked();
1575 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001576 }
1577
1578 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07001579 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001580 synchronized (mLock) {
1581 mProximityPositive = true;
1582 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1583 updatePowerStateLocked();
1584 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001585 }
1586
1587 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001588 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07001589 synchronized (mLock) {
1590 mProximityPositive = false;
1591 mDirty |= DIRTY_PROXIMITY_POSITIVE;
1592 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1593 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1594 updatePowerStateLocked();
1595 }
Jeff Brown96307042012-07-27 15:51:34 -07001596 }
1597 };
Jim Miller92e66dd2012-02-21 18:57:12 -08001598
Jeff Brown96307042012-07-27 15:51:34 -07001599 private boolean shouldUseProximitySensorLocked() {
1600 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
1601 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001602
Jeff Brown96307042012-07-27 15:51:34 -07001603 /**
1604 * Updates the suspend blocker that keeps the CPU alive.
1605 *
1606 * This function must have no other side-effects.
1607 */
1608 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07001609 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
1610 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlocker();
Jeff Brown27f7a862012-12-12 15:43:31 -08001611
1612 // First acquire suspend blockers if needed.
1613 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
1614 mWakeLockSuspendBlocker.acquire();
1615 mHoldingWakeLockSuspendBlocker = true;
1616 }
1617 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
1618 mDisplaySuspendBlocker.acquire();
1619 mHoldingDisplaySuspendBlocker = true;
1620 }
1621
1622 // Then release suspend blockers if needed.
1623 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
1624 mWakeLockSuspendBlocker.release();
1625 mHoldingWakeLockSuspendBlocker = false;
1626 }
1627 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
1628 mDisplaySuspendBlocker.release();
1629 mHoldingDisplaySuspendBlocker = false;
1630 }
Jeff Brown96307042012-07-27 15:51:34 -07001631 }
1632
Jeff Brownec083212013-09-11 20:45:25 -07001633 /**
1634 * Return true if we must keep a suspend blocker active on behalf of the display.
1635 * We do so if the screen is on or is in transition between states.
1636 */
1637 private boolean needDisplaySuspendBlocker() {
1638 if (!mDisplayReady) {
1639 return true;
1640 }
1641 if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) {
1642 // If we asked for the screen to be on but it is off due to the proximity
1643 // sensor then we may suspend but only if the configuration allows it.
1644 // On some hardware it may not be safe to suspend because the proximity
1645 // sensor may not be correctly configured as a wake-up source.
1646 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
1647 || !mSuspendWhenScreenOffDueToProximityConfig) {
1648 return true;
1649 }
1650 }
1651 return false;
1652 }
1653
Jeff Brown96307042012-07-27 15:51:34 -07001654 private boolean isScreenOnInternal() {
1655 synchronized (mLock) {
1656 return !mSystemReady
1657 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001658 }
1659 }
1660
Jeff Brown96307042012-07-27 15:51:34 -07001661 private void handleBatteryStateChangedLocked() {
1662 mDirty |= DIRTY_BATTERY_STATE;
1663 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001664 }
1665
Jeff Brown20767b22012-10-09 18:57:07 -07001666 private void startWatchingForBootAnimationFinished() {
1667 mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED);
1668 }
1669
1670 private void checkIfBootAnimationFinished() {
1671 if (DEBUG) {
1672 Slog.d(TAG, "Check if boot animation finished...");
1673 }
1674
1675 if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) {
1676 mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED,
1677 BOOT_ANIMATION_POLL_INTERVAL);
1678 return;
1679 }
1680
1681 synchronized (mLock) {
1682 if (!mBootCompleted) {
1683 Slog.i(TAG, "Boot animation finished.");
1684 handleBootCompletedLocked();
1685 }
1686 }
1687 }
1688
Jeff Brown96307042012-07-27 15:51:34 -07001689 private void handleBootCompletedLocked() {
1690 final long now = SystemClock.uptimeMillis();
1691 mBootCompleted = true;
1692 mDirty |= DIRTY_BOOT_COMPLETED;
1693 userActivityNoUpdateLocked(
1694 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
1695 updatePowerStateLocked();
Dianne Hackborn254cb442010-01-27 19:23:59 -08001696 }
1697
Jeff Brownab887a02012-10-15 16:00:40 -07001698 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001699 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07001700 if (mHandler == null || !mSystemReady) {
Jeff Brownab887a02012-10-15 16:00:40 -07001701 throw new IllegalStateException("Too early to call shutdown() or reboot()");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001702 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001703
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001704 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07001705 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001706 public void run() {
1707 synchronized (this) {
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001708 if (shutdown) {
1709 ShutdownThread.shutdown(mContext, confirm);
1710 } else {
1711 ShutdownThread.reboot(mContext, reason, confirm);
1712 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001713 }
San Mehat1e512792010-01-07 10:40:29 -08001714 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001715 };
Jeff Brown96307042012-07-27 15:51:34 -07001716
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001717 // ShutdownThread must run on a looper capable of displaying the UI.
Jeff Brown96307042012-07-27 15:51:34 -07001718 Message msg = Message.obtain(mHandler, runnable);
1719 msg.setAsynchronous(true);
1720 mHandler.sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001721
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001722 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07001723 if (wait) {
1724 synchronized (runnable) {
1725 while (true) {
1726 try {
1727 runnable.wait();
1728 } catch (InterruptedException e) {
1729 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05001730 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001731 }
Doug Zongker50a21f42009-11-19 12:49:53 -08001732 }
1733 }
1734
Jeff Brown96307042012-07-27 15:51:34 -07001735 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08001736 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07001737 @Override
Jeff Brown96307042012-07-27 15:51:34 -07001738 public void run() {
1739 throw new RuntimeException(message);
1740 }
Dan Egnor60d87622009-12-16 16:32:58 -08001741 };
1742 try {
1743 t.start();
1744 t.join();
1745 } catch (InterruptedException e) {
1746 Log.wtf(TAG, e);
1747 }
1748 }
1749
Jeff Brown96307042012-07-27 15:51:34 -07001750 private void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07001751 Settings.Global.putInt(mContext.getContentResolver(),
1752 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754
Jeff Brown96307042012-07-27 15:51:34 -07001755 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) {
1756 synchronized (mLock) {
1757 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
1758 mDirty |= DIRTY_SETTINGS;
1759 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 }
1762
Jeff Brown96307042012-07-27 15:51:34 -07001763 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
1764 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
1765 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001767
Jeff Brown96307042012-07-27 15:51:34 -07001768 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001769 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07001770 synchronized (mLock) {
1771 if (!mSystemReady) {
1772 return;
1773 }
1774 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001775 }
Jeff Brown96307042012-07-27 15:51:34 -07001776
1777 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001778 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07001779 }
1780
Jeff Brown96307042012-07-27 15:51:34 -07001781 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
1782 synchronized (mLock) {
1783 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
1784 mScreenBrightnessOverrideFromWindowManager = brightness;
1785 mDirty |= DIRTY_SETTINGS;
1786 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05001787 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04001788 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07001789 }
1790
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001791 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
1792 synchronized (mLock) {
1793 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
1794 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
1795 mDirty |= DIRTY_SETTINGS;
1796 updatePowerStateLocked();
1797 }
1798 }
1799 }
1800
Jeff Brown96307042012-07-27 15:51:34 -07001801 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) {
1802 synchronized (mLock) {
1803 if (mTemporaryScreenBrightnessSettingOverride != brightness) {
1804 mTemporaryScreenBrightnessSettingOverride = brightness;
1805 mDirty |= DIRTY_SETTINGS;
1806 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05001807 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001808 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07001809 }
1810
Jeff Brown330560f2012-08-21 22:10:57 -07001811 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) {
1812 synchronized (mLock) {
1813 // Note: This condition handles NaN because NaN is not equal to any other
1814 // value, including itself.
1815 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) {
1816 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj;
1817 mDirty |= DIRTY_SETTINGS;
1818 updatePowerStateLocked();
1819 }
1820 }
Jeff Brown96307042012-07-27 15:51:34 -07001821 }
1822
1823 /**
1824 * Low-level function turn the device off immediately, without trying
1825 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
1826 */
1827 public static void lowLevelShutdown() {
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07001828 SystemProperties.set("sys.powerctl", "shutdown");
Jeff Brown96307042012-07-27 15:51:34 -07001829 }
1830
1831 /**
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07001832 * Low-level function to reboot the device. On success, this function
1833 * doesn't return. If more than 5 seconds passes from the time,
1834 * a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07001835 *
1836 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07001837 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07001838 public static void lowLevelReboot(String reason) {
1839 if (reason == null) {
1840 reason = "";
1841 }
1842 SystemProperties.set("sys.powerctl", "reboot," + reason);
1843 try {
1844 Thread.sleep(20000);
1845 } catch (InterruptedException e) {
1846 Thread.currentThread().interrupt();
1847 }
Jeff Brown96307042012-07-27 15:51:34 -07001848 }
1849
1850 @Override // Watchdog.Monitor implementation
1851 public void monitor() {
1852 // Grab and release lock for watchdog monitor to detect deadlocks.
1853 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05001854 }
Jeff Brown96307042012-07-27 15:51:34 -07001855 }
1856
Jeff Brown6f357d32014-01-15 20:40:55 -08001857 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07001858 pw.println("POWER MANAGER (dumpsys power)\n");
1859
1860 final DisplayPowerController dpc;
Jeff Brown3b971592013-01-09 18:46:37 -08001861 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07001862 synchronized (mLock) {
1863 pw.println("Power Manager State:");
1864 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
1865 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness));
1866 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07001867 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07001868 pw.println(" mBatteryLevel=" + mBatteryLevel);
1869 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07001870 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07001871 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07001872 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07001873 pw.println(" mBootCompleted=" + mBootCompleted);
1874 pw.println(" mSystemReady=" + mSystemReady);
1875 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1876 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
1877 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
1878 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
1879 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
1880 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
1881 pw.println(" mSendWakeUpFinishedNotificationWhenReady="
1882 + mSendWakeUpFinishedNotificationWhenReady);
1883 pw.println(" mSendGoToSleepFinishedNotificationWhenReady="
1884 + mSendGoToSleepFinishedNotificationWhenReady);
1885 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
1886 pw.println(" mLastUserActivityTimeNoChangeLights="
1887 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
1888 pw.println(" mDisplayReady=" + mDisplayReady);
1889 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08001890 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07001891
1892 pw.println();
1893 pw.println("Settings and Configuration:");
Jeff Brownec083212013-09-11 20:45:25 -07001894 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
1895 + mWakeUpWhenPluggedOrUnpluggedConfig);
1896 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
1897 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07001898 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07001899 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
1900 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
1901 + mDreamsActivatedOnSleepByDefaultConfig);
1902 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
1903 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown96307042012-07-27 15:51:34 -07001904 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04001905 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07001906 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001907 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
1908 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
1909 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
1910 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
1911 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
1912 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
Jeff Brown330560f2012-08-21 22:10:57 -07001913 pw.println(" mScreenAutoBrightnessAdjustmentSetting="
1914 + mScreenAutoBrightnessAdjustmentSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001915 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
1916 pw.println(" mScreenBrightnessOverrideFromWindowManager="
1917 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001918 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
1919 + mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown96307042012-07-27 15:51:34 -07001920 pw.println(" mTemporaryScreenBrightnessSettingOverride="
1921 + mTemporaryScreenBrightnessSettingOverride);
Jeff Brown330560f2012-08-21 22:10:57 -07001922 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride="
1923 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride);
Jeff Brown96307042012-07-27 15:51:34 -07001924 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
1925 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
1926 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
1927
Jeff Brownff532542012-10-02 21:18:04 -07001928 final int screenOffTimeout = getScreenOffTimeoutLocked();
1929 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
1930 pw.println();
1931 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
1932 pw.println("Screen dim duration: " + screenDimDuration + " ms");
1933
Jeff Brown96307042012-07-27 15:51:34 -07001934 pw.println();
1935 pw.println("Wake Locks: size=" + mWakeLocks.size());
1936 for (WakeLock wl : mWakeLocks) {
1937 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04001938 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05001939
Jeff Brown96307042012-07-27 15:51:34 -07001940 pw.println();
1941 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
1942 for (SuspendBlocker sb : mSuspendBlockers) {
1943 pw.println(" " + sb);
1944 }
1945
Jeff Brownc38c9be2012-10-04 13:16:19 -07001946 pw.println();
1947 pw.println("Screen On Blocker: " + mScreenOnBlocker);
1948
Jeff Brown9e316a12012-10-08 19:17:06 -07001949 pw.println();
1950 pw.println("Display Blanker: " + mDisplayBlanker);
1951
Jeff Brown96307042012-07-27 15:51:34 -07001952 dpc = mDisplayPowerController;
Jeff Brown3b971592013-01-09 18:46:37 -08001953 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07001954 }
1955
1956 if (dpc != null) {
1957 dpc.dump(pw);
1958 }
Jeff Brown3b971592013-01-09 18:46:37 -08001959
1960 if (wcd != null) {
1961 wcd.dump(pw);
1962 }
Jeff Brown96307042012-07-27 15:51:34 -07001963 }
1964
1965 private SuspendBlocker createSuspendBlockerLocked(String name) {
1966 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
1967 mSuspendBlockers.add(suspendBlocker);
1968 return suspendBlocker;
1969 }
1970
1971 private static String wakefulnessToString(int wakefulness) {
1972 switch (wakefulness) {
1973 case WAKEFULNESS_ASLEEP:
1974 return "Asleep";
1975 case WAKEFULNESS_AWAKE:
1976 return "Awake";
1977 case WAKEFULNESS_DREAMING:
1978 return "Dreaming";
1979 case WAKEFULNESS_NAPPING:
1980 return "Napping";
1981 default:
1982 return Integer.toString(wakefulness);
1983 }
1984 }
1985
1986 private static WorkSource copyWorkSource(WorkSource workSource) {
1987 return workSource != null ? new WorkSource(workSource) : null;
1988 }
1989
1990 private final class BatteryReceiver extends BroadcastReceiver {
1991 @Override
1992 public void onReceive(Context context, Intent intent) {
1993 synchronized (mLock) {
1994 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05001995 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05001996 }
1997 }
1998
Jeff Brown96307042012-07-27 15:51:34 -07001999 private final class BootCompletedReceiver extends BroadcastReceiver {
2000 @Override
2001 public void onReceive(Context context, Intent intent) {
Jeff Brown20767b22012-10-09 18:57:07 -07002002 // This is our early signal that the system thinks it has finished booting.
2003 // However, the boot animation may still be running for a few more seconds
2004 // since it is ultimately in charge of when it terminates.
2005 // Defer transitioning into the boot completed state until the animation exits.
2006 // We do this so that the screen does not start to dim prematurely before
2007 // the user has actually had a chance to interact with the device.
2008 startWatchingForBootAnimationFinished();
Joe Onoratod28f7532010-11-06 12:56:53 -07002009 }
Jeff Brown96307042012-07-27 15:51:34 -07002010 }
2011
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002012 private final class DreamReceiver extends BroadcastReceiver {
2013 @Override
2014 public void onReceive(Context context, Intent intent) {
2015 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002016 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002017 }
2018 }
2019 }
2020
Jeff Brownd4935962012-09-25 13:27:20 -07002021 private final class UserSwitchedReceiver extends BroadcastReceiver {
2022 @Override
2023 public void onReceive(Context context, Intent intent) {
2024 synchronized (mLock) {
2025 handleSettingsChangedLocked();
2026 }
2027 }
2028 }
2029
Jeff Brownec6aa592012-10-17 20:30:25 -07002030 private final class DockReceiver extends BroadcastReceiver {
2031 @Override
2032 public void onReceive(Context context, Intent intent) {
2033 synchronized (mLock) {
2034 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2035 Intent.EXTRA_DOCK_STATE_UNDOCKED);
2036 if (mDockState != dockState) {
2037 mDockState = dockState;
2038 mDirty |= DIRTY_DOCK_STATE;
2039 updatePowerStateLocked();
2040 }
2041 }
2042 }
2043 }
2044
Jeff Brown96307042012-07-27 15:51:34 -07002045 private final class SettingsObserver extends ContentObserver {
2046 public SettingsObserver(Handler handler) {
2047 super(handler);
2048 }
2049
2050 @Override
2051 public void onChange(boolean selfChange, Uri uri) {
2052 synchronized (mLock) {
2053 handleSettingsChangedLocked();
2054 }
2055 }
2056 }
2057
Jeff Brown96307042012-07-27 15:51:34 -07002058 /**
2059 * Handler for asynchronous operations performed by the power manager.
2060 */
2061 private final class PowerManagerHandler extends Handler {
2062 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07002063 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07002064 }
2065
2066 @Override
2067 public void handleMessage(Message msg) {
2068 switch (msg.what) {
2069 case MSG_USER_ACTIVITY_TIMEOUT:
2070 handleUserActivityTimeout();
2071 break;
2072 case MSG_SANDMAN:
2073 handleSandman();
2074 break;
Jeff Brownc38c9be2012-10-04 13:16:19 -07002075 case MSG_SCREEN_ON_BLOCKER_RELEASED:
2076 handleScreenOnBlockerReleased();
2077 break;
Jeff Brown20767b22012-10-09 18:57:07 -07002078 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED:
2079 checkIfBootAnimationFinished();
2080 break;
Jeff Brown96307042012-07-27 15:51:34 -07002081 }
2082 }
2083 }
2084
2085 /**
2086 * Represents a wake lock that has been acquired by an application.
2087 */
2088 private final class WakeLock implements IBinder.DeathRecipient {
2089 public final IBinder mLock;
2090 public int mFlags;
2091 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002092 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07002093 public WorkSource mWorkSource;
Dianne Hackborn713df152013-05-17 11:27:57 -07002094 public final int mOwnerUid;
2095 public final int mOwnerPid;
2096 public boolean mNotifiedAcquired;
Jeff Brown96307042012-07-27 15:51:34 -07002097
Dianne Hackborn713df152013-05-17 11:27:57 -07002098 public WakeLock(IBinder lock, int flags, String tag, String packageName,
2099 WorkSource workSource, int ownerUid, int ownerPid) {
Jeff Brown96307042012-07-27 15:51:34 -07002100 mLock = lock;
2101 mFlags = flags;
2102 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07002103 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07002104 mWorkSource = copyWorkSource(workSource);
2105 mOwnerUid = ownerUid;
2106 mOwnerPid = ownerPid;
2107 }
2108
2109 @Override
2110 public void binderDied() {
2111 PowerManagerService.this.handleWakeLockDeath(this);
2112 }
2113
2114 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
2115 int ownerUid, int ownerPid) {
2116 return mFlags == flags
2117 && mTag.equals(tag)
2118 && hasSameWorkSource(workSource)
2119 && mOwnerUid == ownerUid
2120 && mOwnerPid == ownerPid;
2121 }
2122
Dianne Hackborn713df152013-05-17 11:27:57 -07002123 public void updateProperties(int flags, String tag, String packageName,
2124 WorkSource workSource, int ownerUid, int ownerPid) {
2125 if (!mPackageName.equals(packageName)) {
2126 throw new IllegalStateException("Existing wake lock package name changed: "
2127 + mPackageName + " to " + packageName);
2128 }
2129 if (mOwnerUid != ownerUid) {
2130 throw new IllegalStateException("Existing wake lock uid changed: "
2131 + mOwnerUid + " to " + ownerUid);
2132 }
2133 if (mOwnerPid != ownerPid) {
2134 throw new IllegalStateException("Existing wake lock pid changed: "
2135 + mOwnerPid + " to " + ownerPid);
2136 }
Jeff Brown96307042012-07-27 15:51:34 -07002137 mFlags = flags;
2138 mTag = tag;
2139 updateWorkSource(workSource);
Jeff Brown96307042012-07-27 15:51:34 -07002140 }
2141
2142 public boolean hasSameWorkSource(WorkSource workSource) {
2143 return Objects.equal(mWorkSource, workSource);
2144 }
2145
2146 public void updateWorkSource(WorkSource workSource) {
2147 mWorkSource = copyWorkSource(workSource);
2148 }
2149
2150 @Override
2151 public String toString() {
2152 return getLockLevelString()
2153 + " '" + mTag + "'" + getLockFlagsString()
2154 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")";
2155 }
2156
2157 private String getLockLevelString() {
2158 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2159 case PowerManager.FULL_WAKE_LOCK:
2160 return "FULL_WAKE_LOCK ";
2161 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2162 return "SCREEN_BRIGHT_WAKE_LOCK ";
2163 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2164 return "SCREEN_DIM_WAKE_LOCK ";
2165 case PowerManager.PARTIAL_WAKE_LOCK:
2166 return "PARTIAL_WAKE_LOCK ";
2167 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2168 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
2169 default:
2170 return "??? ";
2171 }
2172 }
2173
2174 private String getLockFlagsString() {
2175 String result = "";
2176 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
2177 result += " ACQUIRE_CAUSES_WAKEUP";
2178 }
2179 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
2180 result += " ON_AFTER_RELEASE";
2181 }
2182 return result;
2183 }
2184 }
2185
2186 private final class SuspendBlockerImpl implements SuspendBlocker {
2187 private final String mName;
2188 private int mReferenceCount;
2189
2190 public SuspendBlockerImpl(String name) {
2191 mName = name;
2192 }
2193
2194 @Override
2195 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002196 try {
Jeff Brown96307042012-07-27 15:51:34 -07002197 if (mReferenceCount != 0) {
2198 Log.wtf(TAG, "Suspend blocker \"" + mName
2199 + "\" was finalized without being released!");
2200 mReferenceCount = 0;
2201 nativeReleaseSuspendBlocker(mName);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002202 }
2203 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07002204 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002205 }
2206 }
2207
Craig Mautner75fc9de2012-06-18 16:53:27 -07002208 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002209 public void acquire() {
2210 synchronized (this) {
2211 mReferenceCount += 1;
2212 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002213 if (DEBUG_SPEW) {
2214 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
2215 }
Jeff Brown96307042012-07-27 15:51:34 -07002216 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07002217 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002218 }
2219 }
2220
Craig Mautner75fc9de2012-06-18 16:53:27 -07002221 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002222 public void release() {
2223 synchronized (this) {
2224 mReferenceCount -= 1;
2225 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08002226 if (DEBUG_SPEW) {
2227 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
2228 }
Jeff Brown96307042012-07-27 15:51:34 -07002229 nativeReleaseSuspendBlocker(mName);
2230 } else if (mReferenceCount < 0) {
2231 Log.wtf(TAG, "Suspend blocker \"" + mName
2232 + "\" was released without being acquired!", new Throwable());
2233 mReferenceCount = 0;
2234 }
2235 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002236 }
Jeff Brown96307042012-07-27 15:51:34 -07002237
2238 @Override
2239 public String toString() {
2240 synchronized (this) {
2241 return mName + ": ref count=" + mReferenceCount;
2242 }
2243 }
2244 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07002245
2246 private final class ScreenOnBlockerImpl implements ScreenOnBlocker {
2247 private int mNestCount;
2248
2249 public boolean isHeld() {
2250 synchronized (this) {
2251 return mNestCount != 0;
2252 }
2253 }
2254
2255 @Override
2256 public void acquire() {
2257 synchronized (this) {
2258 mNestCount += 1;
2259 if (DEBUG) {
2260 Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount);
2261 }
2262 }
2263 }
2264
2265 @Override
2266 public void release() {
2267 synchronized (this) {
2268 mNestCount -= 1;
2269 if (mNestCount < 0) {
2270 Log.wtf(TAG, "Screen on blocker was released without being acquired!",
2271 new Throwable());
2272 mNestCount = 0;
2273 }
2274 if (mNestCount == 0) {
2275 mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED);
2276 }
2277 if (DEBUG) {
2278 Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount);
2279 }
2280 }
2281 }
2282
2283 @Override
2284 public String toString() {
2285 synchronized (this) {
2286 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount;
2287 }
2288 }
Jeff Brown9e316a12012-10-08 19:17:06 -07002289 }
2290
2291 private final class DisplayBlankerImpl implements DisplayBlanker {
2292 private boolean mBlanked;
2293
2294 @Override
2295 public void blankAllDisplays() {
2296 synchronized (this) {
2297 mBlanked = true;
Jeff Brown4ccb8232014-01-16 22:16:42 -08002298 mDisplayManagerInternal.blankAllDisplaysFromPowerManager();
Jeff Brown9e316a12012-10-08 19:17:06 -07002299 nativeSetInteractive(false);
2300 nativeSetAutoSuspend(true);
2301 }
2302 }
2303
2304 @Override
2305 public void unblankAllDisplays() {
2306 synchronized (this) {
2307 nativeSetAutoSuspend(false);
2308 nativeSetInteractive(true);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002309 mDisplayManagerInternal.unblankAllDisplaysFromPowerManager();
Jeff Brown9e316a12012-10-08 19:17:06 -07002310 mBlanked = false;
2311 }
2312 }
2313
2314 @Override
2315 public String toString() {
2316 synchronized (this) {
2317 return "blanked=" + mBlanked;
2318 }
2319 }
2320 }
Jeff Brown6f357d32014-01-15 20:40:55 -08002321
2322 private final class BinderService extends IPowerManager.Stub {
2323 @Override // Binder call
2324 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
2325 String packageName, int uid) {
2326 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid));
2327 }
2328
2329 @Override // Binder call
2330 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
2331 WorkSource ws) {
2332 if (lock == null) {
2333 throw new IllegalArgumentException("lock must not be null");
2334 }
2335 if (packageName == null) {
2336 throw new IllegalArgumentException("packageName must not be null");
2337 }
2338 PowerManager.validateWakeLockParameters(flags, tag);
2339
2340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2341 if (ws != null && ws.size() != 0) {
2342 mContext.enforceCallingOrSelfPermission(
2343 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2344 } else {
2345 ws = null;
2346 }
2347
2348 final int uid = Binder.getCallingUid();
2349 final int pid = Binder.getCallingPid();
2350 final long ident = Binder.clearCallingIdentity();
2351 try {
2352 acquireWakeLockInternal(lock, flags, tag, packageName, ws, uid, pid);
2353 } finally {
2354 Binder.restoreCallingIdentity(ident);
2355 }
2356 }
2357
2358 @Override // Binder call
2359 public void releaseWakeLock(IBinder lock, int flags) {
2360 if (lock == null) {
2361 throw new IllegalArgumentException("lock must not be null");
2362 }
2363
2364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2365
2366 final long ident = Binder.clearCallingIdentity();
2367 try {
2368 releaseWakeLockInternal(lock, flags);
2369 } finally {
2370 Binder.restoreCallingIdentity(ident);
2371 }
2372 }
2373
2374 @Override // Binder call
2375 public void updateWakeLockUids(IBinder lock, int[] uids) {
2376 WorkSource ws = null;
2377
2378 if (uids != null) {
2379 ws = new WorkSource();
2380 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
2381 // one at a time?
2382 for (int i = 0; i < uids.length; i++) {
2383 ws.add(uids[i]);
2384 }
2385 }
2386 updateWakeLockWorkSource(lock, ws);
2387 }
2388
2389 @Override // Binder call
2390 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
2391 if (lock == null) {
2392 throw new IllegalArgumentException("lock must not be null");
2393 }
2394
2395 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
2396 if (ws != null && ws.size() != 0) {
2397 mContext.enforceCallingOrSelfPermission(
2398 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
2399 } else {
2400 ws = null;
2401 }
2402
2403 final long ident = Binder.clearCallingIdentity();
2404 try {
2405 updateWakeLockWorkSourceInternal(lock, ws);
2406 } finally {
2407 Binder.restoreCallingIdentity(ident);
2408 }
2409 }
2410
2411 @Override // Binder call
2412 public boolean isWakeLockLevelSupported(int level) {
2413 final long ident = Binder.clearCallingIdentity();
2414 try {
2415 return isWakeLockLevelSupportedInternal(level);
2416 } finally {
2417 Binder.restoreCallingIdentity(ident);
2418 }
2419 }
2420
2421 @Override // Binder call
2422 public void userActivity(long eventTime, int event, int flags) {
2423 final long now = SystemClock.uptimeMillis();
2424 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2425 != PackageManager.PERMISSION_GRANTED) {
2426 // Once upon a time applications could call userActivity().
2427 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
2428 // request instead of throwing a SecurityException so we don't break old apps.
2429 synchronized (mLock) {
2430 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
2431 mLastWarningAboutUserActivityPermission = now;
2432 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
2433 + "caller does not have DEVICE_POWER permission. "
2434 + "Please fix your app! "
2435 + " pid=" + Binder.getCallingPid()
2436 + " uid=" + Binder.getCallingUid());
2437 }
2438 }
2439 return;
2440 }
2441
2442 if (eventTime > SystemClock.uptimeMillis()) {
2443 throw new IllegalArgumentException("event time must not be in the future");
2444 }
2445
2446 final int uid = Binder.getCallingUid();
2447 final long ident = Binder.clearCallingIdentity();
2448 try {
2449 userActivityInternal(eventTime, event, flags, uid);
2450 } finally {
2451 Binder.restoreCallingIdentity(ident);
2452 }
2453 }
2454
2455 @Override // Binder call
2456 public void wakeUp(long eventTime) {
2457 if (eventTime > SystemClock.uptimeMillis()) {
2458 throw new IllegalArgumentException("event time must not be in the future");
2459 }
2460
2461 mContext.enforceCallingOrSelfPermission(
2462 android.Manifest.permission.DEVICE_POWER, null);
2463
2464 final long ident = Binder.clearCallingIdentity();
2465 try {
2466 wakeUpInternal(eventTime);
2467 } finally {
2468 Binder.restoreCallingIdentity(ident);
2469 }
2470 }
2471
2472 @Override // Binder call
2473 public void goToSleep(long eventTime, int reason) {
2474 if (eventTime > SystemClock.uptimeMillis()) {
2475 throw new IllegalArgumentException("event time must not be in the future");
2476 }
2477
2478 mContext.enforceCallingOrSelfPermission(
2479 android.Manifest.permission.DEVICE_POWER, null);
2480
2481 final long ident = Binder.clearCallingIdentity();
2482 try {
2483 goToSleepInternal(eventTime, reason);
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
2487 }
2488
2489 @Override // Binder call
2490 public void nap(long eventTime) {
2491 if (eventTime > SystemClock.uptimeMillis()) {
2492 throw new IllegalArgumentException("event time must not be in the future");
2493 }
2494
2495 mContext.enforceCallingOrSelfPermission(
2496 android.Manifest.permission.DEVICE_POWER, null);
2497
2498 final long ident = Binder.clearCallingIdentity();
2499 try {
2500 napInternal(eventTime);
2501 } finally {
2502 Binder.restoreCallingIdentity(ident);
2503 }
2504 }
2505
2506 @Override // Binder call
2507 public boolean isScreenOn() {
2508 final long ident = Binder.clearCallingIdentity();
2509 try {
2510 return isScreenOnInternal();
2511 } finally {
2512 Binder.restoreCallingIdentity(ident);
2513 }
2514 }
2515
2516 /**
2517 * Reboots the device.
2518 *
2519 * @param confirm If true, shows a reboot confirmation dialog.
2520 * @param reason The reason for the reboot, or null if none.
2521 * @param wait If true, this call waits for the reboot to complete and does not return.
2522 */
2523 @Override // Binder call
2524 public void reboot(boolean confirm, String reason, boolean wait) {
2525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2526
2527 final long ident = Binder.clearCallingIdentity();
2528 try {
2529 shutdownOrRebootInternal(false, confirm, reason, wait);
2530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534
2535 /**
2536 * Shuts down the device.
2537 *
2538 * @param confirm If true, shows a shutdown confirmation dialog.
2539 * @param wait If true, this call waits for the shutdown to complete and does not return.
2540 */
2541 @Override // Binder call
2542 public void shutdown(boolean confirm, boolean wait) {
2543 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2544
2545 final long ident = Binder.clearCallingIdentity();
2546 try {
2547 shutdownOrRebootInternal(true, confirm, null, wait);
2548 } finally {
2549 Binder.restoreCallingIdentity(ident);
2550 }
2551 }
2552
2553 /**
2554 * Crash the runtime (causing a complete restart of the Android framework).
2555 * Requires REBOOT permission. Mostly for testing. Should not return.
2556 */
2557 @Override // Binder call
2558 public void crash(String message) {
2559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2560
2561 final long ident = Binder.clearCallingIdentity();
2562 try {
2563 crashInternal(message);
2564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568
2569 /**
2570 * Set the setting that determines whether the device stays on when plugged in.
2571 * The argument is a bit string, with each bit specifying a power source that,
2572 * when the device is connected to that source, causes the device to stay on.
2573 * See {@link android.os.BatteryManager} for the list of power sources that
2574 * can be specified. Current values include
2575 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
2576 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
2577 *
2578 * Used by "adb shell svc power stayon ..."
2579 *
2580 * @param val an {@code int} containing the bits that specify which power sources
2581 * should cause the device to stay on.
2582 */
2583 @Override // Binder call
2584 public void setStayOnSetting(int val) {
2585 mContext.enforceCallingOrSelfPermission(
2586 android.Manifest.permission.WRITE_SETTINGS, null);
2587
2588 final long ident = Binder.clearCallingIdentity();
2589 try {
2590 setStayOnSettingInternal(val);
2591 } finally {
2592 Binder.restoreCallingIdentity(ident);
2593 }
2594 }
2595
2596 /**
2597 * Used by device administration to set the maximum screen off timeout.
2598 *
2599 * This method must only be called by the device administration policy manager.
2600 */
2601 @Override // Binder call
2602 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) {
2603 final long ident = Binder.clearCallingIdentity();
2604 try {
2605 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs);
2606 } finally {
2607 Binder.restoreCallingIdentity(ident);
2608 }
2609 }
2610
2611 /**
2612 * Used by the settings application and brightness control widgets to
2613 * temporarily override the current screen brightness setting so that the
2614 * user can observe the effect of an intended settings change without applying
2615 * it immediately.
2616 *
2617 * The override will be canceled when the setting value is next updated.
2618 *
2619 * @param brightness The overridden brightness.
2620 *
2621 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS
2622 */
2623 @Override // Binder call
2624 public void setTemporaryScreenBrightnessSettingOverride(int brightness) {
2625 mContext.enforceCallingOrSelfPermission(
2626 android.Manifest.permission.DEVICE_POWER, null);
2627
2628 final long ident = Binder.clearCallingIdentity();
2629 try {
2630 setTemporaryScreenBrightnessSettingOverrideInternal(brightness);
2631 } finally {
2632 Binder.restoreCallingIdentity(ident);
2633 }
2634 }
2635
2636 /**
2637 * Used by the settings application and brightness control widgets to
2638 * temporarily override the current screen auto-brightness adjustment setting so that the
2639 * user can observe the effect of an intended settings change without applying
2640 * it immediately.
2641 *
2642 * The override will be canceled when the setting value is next updated.
2643 *
2644 * @param adj The overridden brightness, or Float.NaN to disable the override.
2645 *
2646 * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ
2647 */
2648 @Override // Binder call
2649 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) {
2650 mContext.enforceCallingOrSelfPermission(
2651 android.Manifest.permission.DEVICE_POWER, null);
2652
2653 final long ident = Binder.clearCallingIdentity();
2654 try {
2655 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj);
2656 } finally {
2657 Binder.restoreCallingIdentity(ident);
2658 }
2659 }
2660
2661 /**
2662 * Used by the phone application to make the attention LED flash when ringing.
2663 */
2664 @Override // Binder call
2665 public void setAttentionLight(boolean on, int color) {
2666 mContext.enforceCallingOrSelfPermission(
2667 android.Manifest.permission.DEVICE_POWER, null);
2668
2669 final long ident = Binder.clearCallingIdentity();
2670 try {
2671 setAttentionLightInternal(on, color);
2672 } finally {
2673 Binder.restoreCallingIdentity(ident);
2674 }
2675 }
2676
2677 @Override // Binder call
2678 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2679 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
2680 != PackageManager.PERMISSION_GRANTED) {
2681 pw.println("Permission Denial: can't dump PowerManager from from pid="
2682 + Binder.getCallingPid()
2683 + ", uid=" + Binder.getCallingUid());
2684 return;
2685 }
2686
2687 final long ident = Binder.clearCallingIdentity();
2688 try {
2689 dumpInternal(pw);
2690 } finally {
2691 Binder.restoreCallingIdentity(ident);
2692 }
2693 }
2694 }
2695
Jeff Brown4ccb8232014-01-16 22:16:42 -08002696 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08002697 /**
2698 * Used by the window manager to override the screen brightness based on the
2699 * current foreground activity.
2700 *
2701 * This method must only be called by the window manager.
2702 *
2703 * @param brightness The overridden brightness, or -1 to disable the override.
2704 */
2705 @Override
2706 public void setScreenBrightnessOverrideFromWindowManager(int brightness) {
2707 mContext.enforceCallingOrSelfPermission(
2708 android.Manifest.permission.DEVICE_POWER, null);
2709
2710 final long ident = Binder.clearCallingIdentity();
2711 try {
2712 setScreenBrightnessOverrideFromWindowManagerInternal(brightness);
2713 } finally {
2714 Binder.restoreCallingIdentity(ident);
2715 }
2716 }
2717
2718 /**
2719 * Used by the window manager to override the button brightness based on the
2720 * current foreground activity.
2721 *
2722 * This method must only be called by the window manager.
2723 *
2724 * @param brightness The overridden brightness, or -1 to disable the override.
2725 */
2726 @Override
2727 public void setButtonBrightnessOverrideFromWindowManager(int brightness) {
2728 // Do nothing.
2729 // Button lights are not currently supported in the new implementation.
2730 mContext.enforceCallingOrSelfPermission(
2731 android.Manifest.permission.DEVICE_POWER, null);
2732 }
2733
2734 /**
2735 * Used by the window manager to override the user activity timeout based on the
2736 * current foreground activity. It can only be used to make the timeout shorter
2737 * than usual, not longer.
2738 *
2739 * This method must only be called by the window manager.
2740 *
2741 * @param timeoutMillis The overridden timeout, or -1 to disable the override.
2742 */
2743 @Override
2744 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
2745 mContext.enforceCallingOrSelfPermission(
2746 android.Manifest.permission.DEVICE_POWER, null);
2747
2748 final long ident = Binder.clearCallingIdentity();
2749 try {
2750 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
2751 } finally {
2752 Binder.restoreCallingIdentity(ident);
2753 }
2754 }
2755
2756 @Override
2757 public void setPolicy(WindowManagerPolicy policy) {
2758 PowerManagerService.this.setPolicy(policy);
2759 }
2760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761}