1 /* 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 17 package com.android.server.power; 18 19 import com.android.internal.app.IBatteryStats; 20 import com.android.server.BatteryService; 21 import com.android.server.EventLogTags; 22 import com.android.server.LightsService; 23 import com.android.server.TwilightService; 24 import com.android.server.Watchdog; 25 import com.android.server.am.ActivityManagerService; 26 import com.android.server.display.DisplayManagerService; 27 import com.android.server.dreams.DreamManagerService; 28 29 import android.Manifest; 30 import android.content.BroadcastReceiver; 31 import android.content.ContentResolver; 32 import android.content.Context; 33 import android.content.Intent; 34 import android.content.IntentFilter; 35 import android.content.pm.PackageManager; 36 import android.content.res.Resources; 37 import android.database.ContentObserver; 38 import android.net.Uri; 39 import android.os.BatteryManager; 40 import android.os.Binder; 41 import android.os.Handler; 42 import android.os.HandlerThread; 43 import android.os.IBinder; 44 import android.os.IPowerManager; 45 import android.os.Looper; 46 import android.os.Message; 47 import android.os.PowerManager; 48 import android.os.Process; 49 import android.os.RemoteException; 50 import android.os.SystemClock; 51 import android.os.SystemService; 52 import android.os.UserHandle; 53 import android.os.WorkSource; 54 import android.provider.Settings; 55 import android.util.EventLog; 56 import android.util.Log; 57 import android.util.Slog; 58 import android.util.TimeUtils; 59 import android.view.WindowManagerPolicy; 60 61 import java.io.FileDescriptor; 62 import java.io.IOException; 63 import java.io.PrintWriter; 64 import java.util.ArrayList; 65 66 import libcore.util.Objects; 67 68 /** 69 * The power manager service is responsible for coordinating power management 70 * functions on the device. 71 */ 72 public final class PowerManagerService extends IPowerManager.Stub 73 implements Watchdog.Monitor { 74 private static final String TAG = "PowerManagerService"; 75 76 private static final boolean DEBUG = false; 77 private static final boolean DEBUG_SPEW = DEBUG && true; 78 79 // Message: Sent when a user activity timeout occurs to update the power state. 80 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 81 // Message: Sent when the device enters or exits a napping or dreaming state. 82 private static final int MSG_SANDMAN = 2; 83 // Message: Sent when the screen on blocker is released. 84 private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3; 85 // Message: Sent to poll whether the boot animation has terminated. 86 private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4; 87 88 // Dirty bit: mWakeLocks changed 89 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 90 // Dirty bit: mWakefulness changed 91 private static final int DIRTY_WAKEFULNESS = 1 << 1; 92 // Dirty bit: user activity was poked or may have timed out 93 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 94 // Dirty bit: actual display power state was updated asynchronously 95 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 96 // Dirty bit: mBootCompleted changed 97 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 98 // Dirty bit: settings changed 99 private static final int DIRTY_SETTINGS = 1 << 5; 100 // Dirty bit: mIsPowered changed 101 private static final int DIRTY_IS_POWERED = 1 << 6; 102 // Dirty bit: mStayOn changed 103 private static final int DIRTY_STAY_ON = 1 << 7; 104 // Dirty bit: battery state changed 105 private static final int DIRTY_BATTERY_STATE = 1 << 8; 106 // Dirty bit: proximity state changed 107 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9; 108 // Dirty bit: screen on blocker state became held or unheld 109 private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10; 110 // Dirty bit: dock state changed 111 private static final int DIRTY_DOCK_STATE = 1 << 11; 112 113 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp(). 114 // The screen should be off or in the process of being turned off by the display controller. 115 private static final int WAKEFULNESS_ASLEEP = 0; 116 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep(). 117 // When the user activity timeout expires, the device may start napping or go to sleep. 118 private static final int WAKEFULNESS_AWAKE = 1; 119 // Wakefulness: The device is napping. It is deciding whether to dream or go to sleep 120 // but hasn't gotten around to it yet. It can be awoken by a call to wakeUp(), which 121 // ends the nap. User activity may brighten the screen but does not end the nap. 122 private static final int WAKEFULNESS_NAPPING = 2; 123 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(), 124 // which ends the dream. The device goes to sleep when goToSleep() is called, when 125 // the dream ends or when unplugged. 126 // User activity may brighten the screen but does not end the dream. 127 private static final int WAKEFULNESS_DREAMING = 3; 128 129 // Summarizes the state of all active wakelocks. 130 private static final int WAKE_LOCK_CPU = 1 << 0; 131 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 132 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 133 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 134 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 135 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake 136 137 // Summarizes the user activity state. 138 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 139 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 140 141 // Default and minimum screen off timeout in milliseconds. 142 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 143 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000; 144 145 // The screen dim duration, in milliseconds. 146 // This is subtracted from the end of the screen off timeout so the 147 // minimum screen off timeout should be longer than this. 148 private static final int SCREEN_DIM_DURATION = 7 * 1000; 149 150 // The maximum screen dim time expressed as a ratio relative to the screen 151 // off timeout. If the screen off timeout is very short then we want the 152 // dim timeout to also be quite short so that most of the time is spent on. 153 // Otherwise the user won't get much screen on time before dimming occurs. 154 private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f; 155 156 // Upper bound on the battery charge percentage in order to consider turning 157 // the screen on when the device starts charging wirelessly. 158 // See point of use for more details. 159 private static final int WIRELESS_CHARGER_TURN_ON_BATTERY_LEVEL_LIMIT = 95; 160 161 // The name of the boot animation service in init.rc. 162 private static final String BOOT_ANIMATION_SERVICE = "bootanim"; 163 164 // Poll interval in milliseconds for watching boot animation finished. 165 private static final int BOOT_ANIMATION_POLL_INTERVAL = 200; 166 167 // If the battery level drops by this percentage and the user activity timeout 168 // has expired, then assume the device is receiving insufficient current to charge 169 // effectively and terminate the dream. 170 private static final int DREAM_BATTERY_LEVEL_DRAIN_CUTOFF = 5; 171 172 private Context mContext; 173 private LightsService mLightsService; 174 private BatteryService mBatteryService; 175 private DisplayManagerService mDisplayManagerService; 176 private IBatteryStats mBatteryStats; 177 private HandlerThread mHandlerThread; 178 private PowerManagerHandler mHandler; 179 private WindowManagerPolicy mPolicy; 180 private Notifier mNotifier; 181 private DisplayPowerController mDisplayPowerController; 182 private SettingsObserver mSettingsObserver; 183 private DreamManagerService mDreamManager; 184 private LightsService.Light mAttentionLight; 185 186 private final Object mLock = new Object(); 187 188 // A bitfield that indicates what parts of the power state have 189 // changed and need to be recalculated. 190 private int mDirty; 191 192 // Indicates whether the device is awake or asleep or somewhere in between. 193 // This is distinct from the screen power state, which is managed separately. 194 private int mWakefulness; 195 196 // True if MSG_SANDMAN has been scheduled. 197 private boolean mSandmanScheduled; 198 199 // Table of all suspend blockers. 200 // There should only be a few of these. 201 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 202 203 // Table of all wake locks acquired by applications. 204 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 205 206 // A bitfield that summarizes the state of all active wakelocks. 207 private int mWakeLockSummary; 208 209 // If true, instructs the display controller to wait for the proximity sensor to 210 // go negative before turning the screen on. 211 private boolean mRequestWaitForNegativeProximity; 212 213 // Timestamp of the last time the device was awoken or put to sleep. 214 private long mLastWakeTime; 215 private long mLastSleepTime; 216 217 // True if we need to send a wake up or go to sleep finished notification 218 // when the display is ready. 219 private boolean mSendWakeUpFinishedNotificationWhenReady; 220 private boolean mSendGoToSleepFinishedNotificationWhenReady; 221 222 // Timestamp of the last call to user activity. 223 private long mLastUserActivityTime; 224 private long mLastUserActivityTimeNoChangeLights; 225 226 // A bitfield that summarizes the effect of the user activity timer. 227 // A zero value indicates that the user activity timer has expired. 228 private int mUserActivitySummary; 229 230 // The desired display power state. The actual state may lag behind the 231 // requested because it is updated asynchronously by the display power controller. 232 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 233 234 // The time the screen was last turned off, in elapsedRealtime() timebase. 235 private long mLastScreenOffEventElapsedRealTime; 236 237 // True if the display power state has been fully applied, which means the display 238 // is actually on or actually off or whatever was requested. 239 private boolean mDisplayReady; 240 241 // True if holding a wake-lock to block suspend of the CPU. 242 private boolean mHoldingWakeLockSuspendBlocker; 243 244 // The suspend blocker used to keep the CPU alive when wake locks have been acquired. 245 private final SuspendBlocker mWakeLockSuspendBlocker; 246 247 // The screen on blocker used to keep the screen from turning on while the lock 248 // screen is coming up. 249 private final ScreenOnBlockerImpl mScreenOnBlocker; 250 251 // The display blanker used to turn the screen on or off. 252 private final DisplayBlankerImpl mDisplayBlanker; 253 254 // True if systemReady() has been called. 255 private boolean mSystemReady; 256 257 // True if boot completed occurred. We keep the screen on until this happens. 258 private boolean mBootCompleted; 259 260 // True if the device is plugged into a power source. 261 private boolean mIsPowered; 262 263 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS. 264 private int mPlugType; 265 266 // The current battery level percentage. 267 private int mBatteryLevel; 268 269 // The battery level percentage at the time the dream started. 270 // This is used to terminate a dream and go to sleep if the battery is 271 // draining faster than it is charging and the user activity timeout has expired. 272 private int mBatteryLevelWhenDreamStarted; 273 274 // The current dock state. 275 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; 276 277 // True if the device should wake up when plugged or unplugged. 278 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 279 280 // True if dreams are supported on this device. 281 private boolean mDreamsSupportedConfig; 282 283 // Default value for dreams enabled 284 private boolean mDreamsEnabledByDefaultConfig; 285 286 // Default value for dreams activate-on-sleep 287 private boolean mDreamsActivatedOnSleepByDefaultConfig; 288 289 // Default value for dreams activate-on-dock 290 private boolean mDreamsActivatedOnDockByDefaultConfig; 291 292 // True if dreams are enabled by the user. 293 private boolean mDreamsEnabledSetting; 294 295 // True if dreams should be activated on sleep. 296 private boolean mDreamsActivateOnSleepSetting; 297 298 // True if dreams should be activated on dock. 299 private boolean mDreamsActivateOnDockSetting; 300 301 // The screen off timeout setting value in milliseconds. 302 private int mScreenOffTimeoutSetting; 303 304 // The maximum allowable screen off timeout according to the device 305 // administration policy. Overrides other settings. 306 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 307 308 // The stay on while plugged in setting. 309 // A bitfield of battery conditions under which to make the screen stay on. 310 private int mStayOnWhilePluggedInSetting; 311 312 // True if the device should stay on. 313 private boolean mStayOn; 314 315 // True if the proximity sensor reads a positive result. 316 private boolean mProximityPositive; 317 318 // Screen brightness setting limits. 319 private int mScreenBrightnessSettingMinimum; 320 private int mScreenBrightnessSettingMaximum; 321 private int mScreenBrightnessSettingDefault; 322 323 // The screen brightness setting, from 0 to 255. 324 // Use -1 if no value has been set. 325 private int mScreenBrightnessSetting; 326 327 // The screen auto-brightness adjustment setting, from -1 to 1. 328 // Use 0 if there is no adjustment. 329 private float mScreenAutoBrightnessAdjustmentSetting; 330 331 // The screen brightness mode. 332 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 333 private int mScreenBrightnessModeSetting; 334 335 // The screen brightness setting override from the window manager 336 // to allow the current foreground activity to override the brightness. 337 // Use -1 to disable. 338 private int mScreenBrightnessOverrideFromWindowManager = -1; 339 340 // The user activity timeout override from the window manager 341 // to allow the current foreground activity to override the user activity timeout. 342 // Use -1 to disable. 343 private long mUserActivityTimeoutOverrideFromWindowManager = -1; 344 345 // The screen brightness setting override from the settings application 346 // to temporarily adjust the brightness until next updated, 347 // Use -1 to disable. 348 private int mTemporaryScreenBrightnessSettingOverride = -1; 349 350 // The screen brightness adjustment setting override from the settings 351 // application to temporarily adjust the auto-brightness adjustment factor 352 // until next updated, in the range -1..1. 353 // Use NaN to disable. 354 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 355 356 // Time when we last logged a warning about calling userActivity() without permission. 357 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE; 358 359 private native void nativeInit(); 360 private static native void nativeShutdown(); 361 private static native void nativeReboot(String reason) throws IOException; 362 363 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright); 364 private static native void nativeAcquireSuspendBlocker(String name); 365 private static native void nativeReleaseSuspendBlocker(String name); 366 private static native void nativeSetInteractive(boolean enable); 367 private static native void nativeSetAutoSuspend(boolean enable); 368 369 public PowerManagerService() { 370 synchronized (mLock) { 371 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService"); 372 mWakeLockSuspendBlocker.acquire(); 373 mScreenOnBlocker = new ScreenOnBlockerImpl(); 374 mDisplayBlanker = new DisplayBlankerImpl(); 375 mHoldingWakeLockSuspendBlocker = true; 376 mWakefulness = WAKEFULNESS_AWAKE; 377 } 378 379 nativeInit(); 380 nativeSetPowerState(true, true); 381 } 382 383 /** 384 * Initialize the power manager. 385 * Must be called before any other functions within the power manager are called. 386 */ 387 public void init(Context context, LightsService ls, 388 ActivityManagerService am, BatteryService bs, IBatteryStats bss, 389 DisplayManagerService dm) { 390 mContext = context; 391 mLightsService = ls; 392 mBatteryService = bs; 393 mBatteryStats = bss; 394 mDisplayManagerService = dm; 395 mHandlerThread = new HandlerThread(TAG); 396 mHandlerThread.start(); 397 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 398 399 Watchdog.getInstance().addMonitor(this); 400 401 // Forcibly turn the screen on at boot so that it is in a known power state. 402 // We do this in init() rather than in the constructor because setting the 403 // screen state requires a call into surface flinger which then needs to call back 404 // into the activity manager to check permissions. Unfortunately the 405 // activity manager is not running when the constructor is called, so we 406 // have to defer setting the screen state until this point. 407 mDisplayBlanker.unblankAllDisplays(); 408 } 409 410 public void setPolicy(WindowManagerPolicy policy) { 411 synchronized (mLock) { 412 mPolicy = policy; 413 } 414 } 415 416 public void systemReady(TwilightService twilight, DreamManagerService dreamManager) { 417 synchronized (mLock) { 418 mSystemReady = true; 419 mDreamManager = dreamManager; 420 421 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 422 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 423 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 424 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 425 426 // The notifier runs on the system server's main looper so as not to interfere 427 // with the animations and other critical functions of the power manager. 428 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, 429 createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 430 mScreenOnBlocker, mPolicy); 431 432 // The display power controller runs on the power manager service's 433 // own handler thread. 434 mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(), 435 mContext, mNotifier, mLightsService, twilight, 436 mDisplayBlanker, mDisplayPowerControllerCallbacks, mHandler); 437 438 mSettingsObserver = new SettingsObserver(mHandler); 439 mAttentionLight = mLightsService.getLight(LightsService.LIGHT_ID_ATTENTION); 440 441 // Register for broadcasts from other components of the system. 442 IntentFilter filter = new IntentFilter(); 443 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 444 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler); 445 446 filter = new IntentFilter(); 447 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 448 mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler); 449 450 filter = new IntentFilter(); 451 filter.addAction(Intent.ACTION_DREAMING_STARTED); 452 filter.addAction(Intent.ACTION_DREAMING_STOPPED); 453 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler); 454 455 filter = new IntentFilter(); 456 filter.addAction(Intent.ACTION_USER_SWITCHED); 457 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler); 458 459 filter = new IntentFilter(); 460 filter.addAction(Intent.ACTION_DOCK_EVENT); 461 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler); 462 463 // Register for settings changes. 464 final ContentResolver resolver = mContext.getContentResolver(); 465 resolver.registerContentObserver(Settings.Secure.getUriFor( 466 Settings.Secure.SCREENSAVER_ENABLED), 467 false, mSettingsObserver, UserHandle.USER_ALL); 468 resolver.registerContentObserver(Settings.Secure.getUriFor( 469 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), 470 false, mSettingsObserver, UserHandle.USER_ALL); 471 resolver.registerContentObserver(Settings.Secure.getUriFor( 472 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), 473 false, mSettingsObserver, UserHandle.USER_ALL); 474 resolver.registerContentObserver(Settings.System.getUriFor( 475 Settings.System.SCREEN_OFF_TIMEOUT), 476 false, mSettingsObserver, UserHandle.USER_ALL); 477 resolver.registerContentObserver(Settings.Global.getUriFor( 478 Settings.Global.STAY_ON_WHILE_PLUGGED_IN), 479 false, mSettingsObserver, UserHandle.USER_ALL); 480 resolver.registerContentObserver(Settings.System.getUriFor( 481 Settings.System.SCREEN_BRIGHTNESS), 482 false, mSettingsObserver, UserHandle.USER_ALL); 483 resolver.registerContentObserver(Settings.System.getUriFor( 484 Settings.System.SCREEN_BRIGHTNESS_MODE), 485 false, mSettingsObserver, UserHandle.USER_ALL); 486 487 // Go. 488 readConfigurationLocked(); 489 updateSettingsLocked(); 490 mDirty |= DIRTY_BATTERY_STATE; 491 updatePowerStateLocked(); 492 } 493 } 494 495 private void readConfigurationLocked() { 496 final Resources resources = mContext.getResources(); 497 498 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 499 com.android.internal.R.bool.config_unplugTurnsOnScreen); 500 mDreamsSupportedConfig = resources.getBoolean( 501 com.android.internal.R.bool.config_dreamsSupported); 502 mDreamsEnabledByDefaultConfig = resources.getBoolean( 503 com.android.internal.R.bool.config_dreamsEnabledByDefault); 504 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean( 505 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault); 506 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean( 507 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault); 508 } 509 510 private void updateSettingsLocked() { 511 final ContentResolver resolver = mContext.getContentResolver(); 512 513 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver, 514 Settings.Secure.SCREENSAVER_ENABLED, 515 mDreamsEnabledByDefaultConfig ? 1 : 0, 516 UserHandle.USER_CURRENT) != 0); 517 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver, 518 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 519 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0, 520 UserHandle.USER_CURRENT) != 0); 521 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver, 522 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK, 523 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0, 524 UserHandle.USER_CURRENT) != 0); 525 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver, 526 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT, 527 UserHandle.USER_CURRENT); 528 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver, 529 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC); 530 531 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 532 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver, 533 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault, 534 UserHandle.USER_CURRENT); 535 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 536 mTemporaryScreenBrightnessSettingOverride = -1; 537 } 538 539 final float oldScreenAutoBrightnessAdjustmentSetting = 540 mScreenAutoBrightnessAdjustmentSetting; 541 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver, 542 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, 543 UserHandle.USER_CURRENT); 544 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 545 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 546 } 547 548 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver, 549 Settings.System.SCREEN_BRIGHTNESS_MODE, 550 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT); 551 552 mDirty |= DIRTY_SETTINGS; 553 } 554 555 private void handleSettingsChangedLocked() { 556 updateSettingsLocked(); 557 updatePowerStateLocked(); 558 } 559 560 @Override // Binder call 561 public void acquireWakeLock(IBinder lock, int flags, String tag, WorkSource ws) { 562 if (lock == null) { 563 throw new IllegalArgumentException("lock must not be null"); 564 } 565 PowerManager.validateWakeLockParameters(flags, tag); 566 567 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 568 if (ws != null && ws.size() != 0) { 569 mContext.enforceCallingOrSelfPermission( 570 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 571 } else { 572 ws = null; 573 } 574 575 final int uid = Binder.getCallingUid(); 576 final int pid = Binder.getCallingPid(); 577 final long ident = Binder.clearCallingIdentity(); 578 try { 579 acquireWakeLockInternal(lock, flags, tag, ws, uid, pid); 580 } finally { 581 Binder.restoreCallingIdentity(ident); 582 } 583 } 584 585 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, WorkSource ws, 586 int uid, int pid) { 587 synchronized (mLock) { 588 if (DEBUG_SPEW) { 589 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 590 + ", flags=0x" + Integer.toHexString(flags) 591 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 592 } 593 594 WakeLock wakeLock; 595 int index = findWakeLockIndexLocked(lock); 596 if (index >= 0) { 597 wakeLock = mWakeLocks.get(index); 598 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 599 // Update existing wake lock. This shouldn't happen but is harmless. 600 notifyWakeLockReleasedLocked(wakeLock); 601 wakeLock.updateProperties(flags, tag, ws, uid, pid); 602 notifyWakeLockAcquiredLocked(wakeLock); 603 } 604 } else { 605 wakeLock = new WakeLock(lock, flags, tag, ws, uid, pid); 606 try { 607 lock.linkToDeath(wakeLock, 0); 608 } catch (RemoteException ex) { 609 throw new IllegalArgumentException("Wake lock is already dead."); 610 } 611 notifyWakeLockAcquiredLocked(wakeLock); 612 mWakeLocks.add(wakeLock); 613 } 614 615 applyWakeLockFlagsOnAcquireLocked(wakeLock); 616 mDirty |= DIRTY_WAKE_LOCKS; 617 updatePowerStateLocked(); 618 } 619 } 620 621 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) { 622 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 623 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 624 } 625 } 626 627 @Override // Binder call 628 public void releaseWakeLock(IBinder lock, int flags) { 629 if (lock == null) { 630 throw new IllegalArgumentException("lock must not be null"); 631 } 632 633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 634 635 final long ident = Binder.clearCallingIdentity(); 636 try { 637 releaseWakeLockInternal(lock, flags); 638 } finally { 639 Binder.restoreCallingIdentity(ident); 640 } 641 } 642 643 private void releaseWakeLockInternal(IBinder lock, int flags) { 644 synchronized (mLock) { 645 if (DEBUG_SPEW) { 646 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 647 + ", flags=0x" + Integer.toHexString(flags)); 648 } 649 650 int index = findWakeLockIndexLocked(lock); 651 if (index < 0) { 652 return; 653 } 654 655 WakeLock wakeLock = mWakeLocks.get(index); 656 mWakeLocks.remove(index); 657 notifyWakeLockReleasedLocked(wakeLock); 658 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 659 660 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) { 661 mRequestWaitForNegativeProximity = true; 662 } 663 664 applyWakeLockFlagsOnReleaseLocked(wakeLock); 665 mDirty |= DIRTY_WAKE_LOCKS; 666 updatePowerStateLocked(); 667 } 668 } 669 670 private void handleWakeLockDeath(WakeLock wakeLock) { 671 synchronized (mLock) { 672 if (DEBUG_SPEW) { 673 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)); 674 } 675 676 int index = mWakeLocks.indexOf(wakeLock); 677 if (index < 0) { 678 return; 679 } 680 681 mWakeLocks.remove(index); 682 notifyWakeLockReleasedLocked(wakeLock); 683 684 applyWakeLockFlagsOnReleaseLocked(wakeLock); 685 mDirty |= DIRTY_WAKE_LOCKS; 686 updatePowerStateLocked(); 687 } 688 } 689 690 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 691 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 692 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 693 PowerManager.USER_ACTIVITY_EVENT_OTHER, 694 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 695 wakeLock.mOwnerUid); 696 } 697 } 698 699 @Override // Binder call 700 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) { 701 if (lock == null) { 702 throw new IllegalArgumentException("lock must not be null"); 703 } 704 705 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 706 if (ws != null && ws.size() != 0) { 707 mContext.enforceCallingOrSelfPermission( 708 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 709 } else { 710 ws = null; 711 } 712 713 final long ident = Binder.clearCallingIdentity(); 714 try { 715 updateWakeLockWorkSourceInternal(lock, ws); 716 } finally { 717 Binder.restoreCallingIdentity(ident); 718 } 719 } 720 721 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) { 722 synchronized (mLock) { 723 int index = findWakeLockIndexLocked(lock); 724 if (index < 0) { 725 throw new IllegalArgumentException("Wake lock not active"); 726 } 727 728 WakeLock wakeLock = mWakeLocks.get(index); 729 if (!wakeLock.hasSameWorkSource(ws)) { 730 notifyWakeLockReleasedLocked(wakeLock); 731 wakeLock.updateWorkSource(ws); 732 notifyWakeLockAcquiredLocked(wakeLock); 733 } 734 } 735 } 736 737 private int findWakeLockIndexLocked(IBinder lock) { 738 final int count = mWakeLocks.size(); 739 for (int i = 0; i < count; i++) { 740 if (mWakeLocks.get(i).mLock == lock) { 741 return i; 742 } 743 } 744 return -1; 745 } 746 747 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 748 if (mSystemReady) { 749 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, 750 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 751 } 752 } 753 754 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 755 if (mSystemReady) { 756 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 757 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 758 } 759 } 760 761 @Override // Binder call 762 public boolean isWakeLockLevelSupported(int level) { 763 final long ident = Binder.clearCallingIdentity(); 764 try { 765 return isWakeLockLevelSupportedInternal(level); 766 } finally { 767 Binder.restoreCallingIdentity(ident); 768 } 769 } 770 771 private boolean isWakeLockLevelSupportedInternal(int level) { 772 synchronized (mLock) { 773 switch (level) { 774 case PowerManager.PARTIAL_WAKE_LOCK: 775 case PowerManager.SCREEN_DIM_WAKE_LOCK: 776 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 777 case PowerManager.FULL_WAKE_LOCK: 778 return true; 779 780 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 781 return mSystemReady && mDisplayPowerController.isProximitySensorAvailable(); 782 783 default: 784 return false; 785 } 786 } 787 } 788 789 @Override // Binder call 790 public void userActivity(long eventTime, int event, int flags) { 791 final long now = SystemClock.uptimeMillis(); 792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 793 != PackageManager.PERMISSION_GRANTED) { 794 // Once upon a time applications could call userActivity(). 795 // Now we require the DEVICE_POWER permission. Log a warning and ignore the 796 // request instead of throwing a SecurityException so we don't break old apps. 797 synchronized (mLock) { 798 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) { 799 mLastWarningAboutUserActivityPermission = now; 800 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the " 801 + "caller does not have DEVICE_POWER permission. " 802 + "Please fix your app! " 803 + " pid=" + Binder.getCallingPid() 804 + " uid=" + Binder.getCallingUid()); 805 } 806 } 807 return; 808 } 809 810 if (eventTime > SystemClock.uptimeMillis()) { 811 throw new IllegalArgumentException("event time must not be in the future"); 812 } 813 814 final int uid = Binder.getCallingUid(); 815 final long ident = Binder.clearCallingIdentity(); 816 try { 817 userActivityInternal(eventTime, event, flags, uid); 818 } finally { 819 Binder.restoreCallingIdentity(ident); 820 } 821 } 822 823 // Called from native code. 824 private void userActivityFromNative(long eventTime, int event, int flags) { 825 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 826 } 827 828 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 829 synchronized (mLock) { 830 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 831 updatePowerStateLocked(); 832 } 833 } 834 } 835 836 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 837 if (DEBUG_SPEW) { 838 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 839 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 840 + ", uid=" + uid); 841 } 842 843 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 844 || mWakefulness == WAKEFULNESS_ASLEEP || !mBootCompleted || !mSystemReady) { 845 return false; 846 } 847 848 mNotifier.onUserActivity(event, uid); 849 850 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 851 if (eventTime > mLastUserActivityTimeNoChangeLights 852 && eventTime > mLastUserActivityTime) { 853 mLastUserActivityTimeNoChangeLights = eventTime; 854 mDirty |= DIRTY_USER_ACTIVITY; 855 return true; 856 } 857 } else { 858 if (eventTime > mLastUserActivityTime) { 859 mLastUserActivityTime = eventTime; 860 mDirty |= DIRTY_USER_ACTIVITY; 861 return true; 862 } 863 } 864 return false; 865 } 866 867 @Override // Binder call 868 public void wakeUp(long eventTime) { 869 if (eventTime > SystemClock.uptimeMillis()) { 870 throw new IllegalArgumentException("event time must not be in the future"); 871 } 872 873 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 874 875 final long ident = Binder.clearCallingIdentity(); 876 try { 877 wakeUpInternal(eventTime); 878 } finally { 879 Binder.restoreCallingIdentity(ident); 880 } 881 } 882 883 // Called from native code. 884 private void wakeUpFromNative(long eventTime) { 885 wakeUpInternal(eventTime); 886 } 887 888 private void wakeUpInternal(long eventTime) { 889 synchronized (mLock) { 890 if (wakeUpNoUpdateLocked(eventTime)) { 891 updatePowerStateLocked(); 892 } 893 } 894 } 895 896 private boolean wakeUpNoUpdateLocked(long eventTime) { 897 if (DEBUG_SPEW) { 898 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime); 899 } 900 901 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 902 || !mBootCompleted || !mSystemReady) { 903 return false; 904 } 905 906 switch (mWakefulness) { 907 case WAKEFULNESS_ASLEEP: 908 Slog.i(TAG, "Waking up from sleep..."); 909 sendPendingNotificationsLocked(); 910 mNotifier.onWakeUpStarted(); 911 mSendWakeUpFinishedNotificationWhenReady = true; 912 break; 913 case WAKEFULNESS_DREAMING: 914 Slog.i(TAG, "Waking up from dream..."); 915 break; 916 case WAKEFULNESS_NAPPING: 917 Slog.i(TAG, "Waking up from nap..."); 918 break; 919 } 920 921 mLastWakeTime = eventTime; 922 mWakefulness = WAKEFULNESS_AWAKE; 923 mDirty |= DIRTY_WAKEFULNESS; 924 925 userActivityNoUpdateLocked( 926 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 927 return true; 928 } 929 930 @Override // Binder call 931 public void goToSleep(long eventTime, int reason) { 932 if (eventTime > SystemClock.uptimeMillis()) { 933 throw new IllegalArgumentException("event time must not be in the future"); 934 } 935 936 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 937 938 final long ident = Binder.clearCallingIdentity(); 939 try { 940 goToSleepInternal(eventTime, reason); 941 } finally { 942 Binder.restoreCallingIdentity(ident); 943 } 944 } 945 946 // Called from native code. 947 private void goToSleepFromNative(long eventTime, int reason) { 948 goToSleepInternal(eventTime, reason); 949 } 950 951 private void goToSleepInternal(long eventTime, int reason) { 952 synchronized (mLock) { 953 if (goToSleepNoUpdateLocked(eventTime, reason)) { 954 updatePowerStateLocked(); 955 } 956 } 957 } 958 959 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) { 960 if (DEBUG_SPEW) { 961 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason); 962 } 963 964 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 965 || !mBootCompleted || !mSystemReady) { 966 return false; 967 } 968 969 switch (reason) { 970 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 971 Slog.i(TAG, "Going to sleep due to device administration policy..."); 972 break; 973 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 974 Slog.i(TAG, "Going to sleep due to screen timeout..."); 975 break; 976 default: 977 Slog.i(TAG, "Going to sleep by user request..."); 978 reason = PowerManager.GO_TO_SLEEP_REASON_USER; 979 break; 980 } 981 982 sendPendingNotificationsLocked(); 983 mNotifier.onGoToSleepStarted(reason); 984 mSendGoToSleepFinishedNotificationWhenReady = true; 985 986 mLastSleepTime = eventTime; 987 mDirty |= DIRTY_WAKEFULNESS; 988 mWakefulness = WAKEFULNESS_ASLEEP; 989 990 // Report the number of wake locks that will be cleared by going to sleep. 991 int numWakeLocksCleared = 0; 992 final int numWakeLocks = mWakeLocks.size(); 993 for (int i = 0; i < numWakeLocks; i++) { 994 final WakeLock wakeLock = mWakeLocks.get(i); 995 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 996 case PowerManager.FULL_WAKE_LOCK: 997 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 998 case PowerManager.SCREEN_DIM_WAKE_LOCK: 999 numWakeLocksCleared += 1; 1000 break; 1001 } 1002 } 1003 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 1004 return true; 1005 } 1006 1007 @Override // Binder call 1008 public void nap(long eventTime) { 1009 if (eventTime > SystemClock.uptimeMillis()) { 1010 throw new IllegalArgumentException("event time must not be in the future"); 1011 } 1012 1013 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1014 1015 final long ident = Binder.clearCallingIdentity(); 1016 try { 1017 napInternal(eventTime); 1018 } finally { 1019 Binder.restoreCallingIdentity(ident); 1020 } 1021 } 1022 1023 private void napInternal(long eventTime) { 1024 synchronized (mLock) { 1025 if (napNoUpdateLocked(eventTime)) { 1026 updatePowerStateLocked(); 1027 } 1028 } 1029 } 1030 1031 private boolean napNoUpdateLocked(long eventTime) { 1032 if (DEBUG_SPEW) { 1033 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime); 1034 } 1035 1036 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE 1037 || !mBootCompleted || !mSystemReady) { 1038 return false; 1039 } 1040 1041 Slog.i(TAG, "Nap time..."); 1042 1043 mDirty |= DIRTY_WAKEFULNESS; 1044 mWakefulness = WAKEFULNESS_NAPPING; 1045 return true; 1046 } 1047 1048 /** 1049 * Updates the global power state based on dirty bits recorded in mDirty. 1050 * 1051 * This is the main function that performs power state transitions. 1052 * We centralize them here so that we can recompute the power state completely 1053 * each time something important changes, and ensure that we do it the same 1054 * way each time. The point is to gather all of the transition logic here. 1055 */ 1056 private void updatePowerStateLocked() { 1057 if (!mSystemReady || mDirty == 0) { 1058 return; 1059 } 1060 1061 // Phase 0: Basic state updates. 1062 updateIsPoweredLocked(mDirty); 1063 updateStayOnLocked(mDirty); 1064 1065 // Phase 1: Update wakefulness. 1066 // Loop because the wake lock and user activity computations are influenced 1067 // by changes in wakefulness. 1068 final long now = SystemClock.uptimeMillis(); 1069 int dirtyPhase2 = 0; 1070 for (;;) { 1071 int dirtyPhase1 = mDirty; 1072 dirtyPhase2 |= dirtyPhase1; 1073 mDirty = 0; 1074 1075 updateWakeLockSummaryLocked(dirtyPhase1); 1076 updateUserActivitySummaryLocked(now, dirtyPhase1); 1077 if (!updateWakefulnessLocked(dirtyPhase1)) { 1078 break; 1079 } 1080 } 1081 1082 // Phase 2: Update dreams and display power state. 1083 updateDreamLocked(dirtyPhase2); 1084 updateDisplayPowerStateLocked(dirtyPhase2); 1085 1086 // Phase 3: Send notifications, if needed. 1087 if (mDisplayReady) { 1088 sendPendingNotificationsLocked(); 1089 } 1090 1091 // Phase 4: Update suspend blocker. 1092 // Because we might release the last suspend blocker here, we need to make sure 1093 // we finished everything else first! 1094 updateSuspendBlockerLocked(); 1095 } 1096 1097 private void sendPendingNotificationsLocked() { 1098 if (mSendWakeUpFinishedNotificationWhenReady) { 1099 mSendWakeUpFinishedNotificationWhenReady = false; 1100 mNotifier.onWakeUpFinished(); 1101 } 1102 if (mSendGoToSleepFinishedNotificationWhenReady) { 1103 mSendGoToSleepFinishedNotificationWhenReady = false; 1104 mNotifier.onGoToSleepFinished(); 1105 } 1106 } 1107 1108 /** 1109 * Updates the value of mIsPowered. 1110 * Sets DIRTY_IS_POWERED if a change occurred. 1111 */ 1112 private void updateIsPoweredLocked(int dirty) { 1113 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 1114 final boolean wasPowered = mIsPowered; 1115 final int oldPlugType = mPlugType; 1116 mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY); 1117 mPlugType = mBatteryService.getPlugType(); 1118 mBatteryLevel = mBatteryService.getBatteryLevel(); 1119 1120 if (DEBUG) { 1121 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered 1122 + ", mIsPowered=" + mIsPowered 1123 + ", oldPlugType=" + oldPlugType 1124 + ", mPlugType=" + mPlugType 1125 + ", mBatteryLevel=" + mBatteryLevel); 1126 } 1127 1128 if (wasPowered != mIsPowered || oldPlugType != mPlugType) { 1129 mDirty |= DIRTY_IS_POWERED; 1130 1131 // Treat plugging and unplugging the devices as a user activity. 1132 // Users find it disconcerting when they plug or unplug the device 1133 // and it shuts off right away. 1134 // Some devices also wake the device when plugged or unplugged because 1135 // they don't have a charging LED. 1136 final long now = SystemClock.uptimeMillis(); 1137 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType)) { 1138 wakeUpNoUpdateLocked(now); 1139 } 1140 userActivityNoUpdateLocked( 1141 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1142 } 1143 } 1144 } 1145 1146 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(boolean wasPowered, int oldPlugType) { 1147 // Don't wake when powered unless configured to do so. 1148 if (!mWakeUpWhenPluggedOrUnpluggedConfig) { 1149 return false; 1150 } 1151 1152 // FIXME: Need more accurate detection of wireless chargers. 1153 // 1154 // We are unable to accurately detect whether the device is resting on the 1155 // charger unless it is actually receiving power. This causes us some grief 1156 // because the device might not appear to be plugged into the wireless charger 1157 // unless it actually charging. 1158 // 1159 // To avoid spuriously waking the screen, we apply a special policy to 1160 // wireless chargers. 1161 // 1162 // 1. Don't wake the device when unplugged from wireless charger because 1163 // it might be that the device is still resting on the wireless charger 1164 // but is not receiving power anymore because the battery is full. 1165 // 1166 // 2. Don't wake the device when plugged into a wireless charger if the 1167 // battery already appears to be mostly full. This situation may indicate 1168 // that the device was resting on the charger the whole time and simply 1169 // wasn't receiving power because the battery was full. We can't tell 1170 // whether the device was just placed on the charger or whether it has 1171 // been there for half of the night slowly discharging until it hit 1172 // the point where it needed to start charging again. 1173 if (wasPowered && !mIsPowered 1174 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 1175 return false; 1176 } 1177 if (!wasPowered && mIsPowered 1178 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS 1179 && mBatteryLevel >= WIRELESS_CHARGER_TURN_ON_BATTERY_LEVEL_LIMIT) { 1180 return false; 1181 } 1182 1183 // If already dreaming and becoming powered, then don't wake. 1184 if (mIsPowered && (mWakefulness == WAKEFULNESS_NAPPING 1185 || mWakefulness == WAKEFULNESS_DREAMING)) { 1186 return false; 1187 } 1188 1189 // Otherwise wake up! 1190 return true; 1191 } 1192 1193 /** 1194 * Updates the value of mStayOn. 1195 * Sets DIRTY_STAY_ON if a change occurred. 1196 */ 1197 private void updateStayOnLocked(int dirty) { 1198 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 1199 final boolean wasStayOn = mStayOn; 1200 if (mStayOnWhilePluggedInSetting != 0 1201 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1202 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting); 1203 } else { 1204 mStayOn = false; 1205 } 1206 1207 if (mStayOn != wasStayOn) { 1208 mDirty |= DIRTY_STAY_ON; 1209 } 1210 } 1211 } 1212 1213 /** 1214 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 1215 * Note that most wake-locks are ignored when the system is asleep. 1216 * 1217 * This function must have no other side-effects. 1218 */ 1219 private void updateWakeLockSummaryLocked(int dirty) { 1220 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 1221 mWakeLockSummary = 0; 1222 1223 final int numWakeLocks = mWakeLocks.size(); 1224 for (int i = 0; i < numWakeLocks; i++) { 1225 final WakeLock wakeLock = mWakeLocks.get(i); 1226 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1227 case PowerManager.PARTIAL_WAKE_LOCK: 1228 mWakeLockSummary |= WAKE_LOCK_CPU; 1229 break; 1230 case PowerManager.FULL_WAKE_LOCK: 1231 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1232 mWakeLockSummary |= WAKE_LOCK_CPU 1233 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 1234 if (mWakefulness == WAKEFULNESS_AWAKE) { 1235 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1236 } 1237 } 1238 break; 1239 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1240 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1241 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT; 1242 if (mWakefulness == WAKEFULNESS_AWAKE) { 1243 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1244 } 1245 } 1246 break; 1247 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1248 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1249 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM; 1250 if (mWakefulness == WAKEFULNESS_AWAKE) { 1251 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1252 } 1253 } 1254 break; 1255 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1256 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1257 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1258 } 1259 break; 1260 } 1261 } 1262 1263 if (DEBUG_SPEW) { 1264 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1265 + wakefulnessToString(mWakefulness) 1266 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1267 } 1268 } 1269 } 1270 1271 /** 1272 * Updates the value of mUserActivitySummary to summarize the user requested 1273 * state of the system such as whether the screen should be bright or dim. 1274 * Note that user activity is ignored when the system is asleep. 1275 * 1276 * This function must have no other side-effects. 1277 */ 1278 private void updateUserActivitySummaryLocked(long now, int dirty) { 1279 // Update the status of the user activity timeout timer. 1280 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1281 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1282 1283 long nextTimeout = 0; 1284 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1285 final int screenOffTimeout = getScreenOffTimeoutLocked(); 1286 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1287 1288 mUserActivitySummary = 0; 1289 if (mLastUserActivityTime >= mLastWakeTime) { 1290 nextTimeout = mLastUserActivityTime 1291 + screenOffTimeout - screenDimDuration; 1292 if (now < nextTimeout) { 1293 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT; 1294 } else { 1295 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1296 if (now < nextTimeout) { 1297 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM; 1298 } 1299 } 1300 } 1301 if (mUserActivitySummary == 0 1302 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1303 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1304 if (now < nextTimeout 1305 && mDisplayPowerRequest.screenState 1306 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1307 mUserActivitySummary = mDisplayPowerRequest.screenState 1308 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ? 1309 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM; 1310 } 1311 } 1312 if (mUserActivitySummary != 0) { 1313 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1314 msg.setAsynchronous(true); 1315 mHandler.sendMessageAtTime(msg, nextTimeout); 1316 } 1317 } else { 1318 mUserActivitySummary = 0; 1319 } 1320 1321 if (DEBUG_SPEW) { 1322 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1323 + wakefulnessToString(mWakefulness) 1324 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1325 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1326 } 1327 } 1328 } 1329 1330 /** 1331 * Called when a user activity timeout has occurred. 1332 * Simply indicates that something about user activity has changed so that the new 1333 * state can be recomputed when the power state is updated. 1334 * 1335 * This function must have no other side-effects besides setting the dirty 1336 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1337 */ 1338 private void handleUserActivityTimeout() { // runs on handler thread 1339 synchronized (mLock) { 1340 if (DEBUG_SPEW) { 1341 Slog.d(TAG, "handleUserActivityTimeout"); 1342 } 1343 1344 mDirty |= DIRTY_USER_ACTIVITY; 1345 updatePowerStateLocked(); 1346 } 1347 } 1348 1349 private int getScreenOffTimeoutLocked() { 1350 int timeout = mScreenOffTimeoutSetting; 1351 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1352 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1353 } 1354 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) { 1355 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager); 1356 } 1357 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT); 1358 } 1359 1360 private int getScreenDimDurationLocked(int screenOffTimeout) { 1361 return Math.min(SCREEN_DIM_DURATION, 1362 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO)); 1363 } 1364 1365 /** 1366 * Updates the wakefulness of the device. 1367 * 1368 * This is the function that decides whether the device should start napping 1369 * based on the current wake locks and user activity state. It may modify mDirty 1370 * if the wakefulness changes. 1371 * 1372 * Returns true if the wakefulness changed and we need to restart power state calculation. 1373 */ 1374 private boolean updateWakefulnessLocked(int dirty) { 1375 boolean changed = false; 1376 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1377 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE 1378 | DIRTY_DOCK_STATE)) != 0) { 1379 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1380 if (DEBUG_SPEW) { 1381 Slog.d(TAG, "updateWakefulnessLocked: Bed time..."); 1382 } 1383 final long time = SystemClock.uptimeMillis(); 1384 if (shouldNapAtBedTimeLocked()) { 1385 changed = napNoUpdateLocked(time); 1386 } else { 1387 changed = goToSleepNoUpdateLocked(time, 1388 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1389 } 1390 } 1391 } 1392 return changed; 1393 } 1394 1395 /** 1396 * Returns true if the device should automatically nap and start dreaming when the user 1397 * activity timeout has expired and it's bedtime. 1398 */ 1399 private boolean shouldNapAtBedTimeLocked() { 1400 return mDreamsActivateOnSleepSetting 1401 || (mDreamsActivateOnDockSetting 1402 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED); 1403 } 1404 1405 /** 1406 * Returns true if the device should go to sleep now. 1407 * Also used when exiting a dream to determine whether we should go back 1408 * to being fully awake or else go to sleep for good. 1409 */ 1410 private boolean isItBedTimeYetLocked() { 1411 return mBootCompleted && !isBeingKeptAwakeLocked(); 1412 } 1413 1414 /** 1415 * Returns true if the device is being kept awake by a wake lock, user activity 1416 * or the stay on while powered setting. 1417 */ 1418 private boolean isBeingKeptAwakeLocked() { 1419 return mStayOn 1420 || mProximityPositive 1421 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0 1422 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1423 | USER_ACTIVITY_SCREEN_DIM)) != 0; 1424 } 1425 1426 /** 1427 * Determines whether to post a message to the sandman to update the dream state. 1428 */ 1429 private void updateDreamLocked(int dirty) { 1430 if ((dirty & (DIRTY_WAKEFULNESS 1431 | DIRTY_USER_ACTIVITY 1432 | DIRTY_WAKE_LOCKS 1433 | DIRTY_BOOT_COMPLETED 1434 | DIRTY_SETTINGS 1435 | DIRTY_IS_POWERED 1436 | DIRTY_STAY_ON 1437 | DIRTY_PROXIMITY_POSITIVE 1438 | DIRTY_BATTERY_STATE)) != 0) { 1439 scheduleSandmanLocked(); 1440 } 1441 } 1442 1443 private void scheduleSandmanLocked() { 1444 if (!mSandmanScheduled) { 1445 mSandmanScheduled = true; 1446 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1447 msg.setAsynchronous(true); 1448 mHandler.sendMessage(msg); 1449 } 1450 } 1451 1452 /** 1453 * Called when the device enters or exits a napping or dreaming state. 1454 * 1455 * We do this asynchronously because we must call out of the power manager to start 1456 * the dream and we don't want to hold our lock while doing so. There is a risk that 1457 * the device will wake or go to sleep in the meantime so we have to handle that case. 1458 */ 1459 private void handleSandman() { // runs on handler thread 1460 // Handle preconditions. 1461 boolean startDreaming = false; 1462 synchronized (mLock) { 1463 mSandmanScheduled = false; 1464 boolean canDream = canDreamLocked(); 1465 if (DEBUG_SPEW) { 1466 Slog.d(TAG, "handleSandman: canDream=" + canDream 1467 + ", mWakefulness=" + wakefulnessToString(mWakefulness)); 1468 } 1469 1470 if (canDream && mWakefulness == WAKEFULNESS_NAPPING) { 1471 startDreaming = true; 1472 } 1473 } 1474 1475 // Start dreaming if needed. 1476 // We only control the dream on the handler thread, so we don't need to worry about 1477 // concurrent attempts to start or stop the dream. 1478 boolean isDreaming = false; 1479 if (mDreamManager != null) { 1480 if (startDreaming) { 1481 mDreamManager.startDream(); 1482 } 1483 isDreaming = mDreamManager.isDreaming(); 1484 } 1485 1486 // Update dream state. 1487 // We might need to stop the dream again if the preconditions changed. 1488 boolean continueDreaming = false; 1489 synchronized (mLock) { 1490 if (isDreaming && canDreamLocked()) { 1491 if (mWakefulness == WAKEFULNESS_NAPPING) { 1492 mWakefulness = WAKEFULNESS_DREAMING; 1493 mDirty |= DIRTY_WAKEFULNESS; 1494 mBatteryLevelWhenDreamStarted = mBatteryLevel; 1495 updatePowerStateLocked(); 1496 continueDreaming = true; 1497 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1498 if (!isBeingKeptAwakeLocked() 1499 && mBatteryLevel < mBatteryLevelWhenDreamStarted 1500 - DREAM_BATTERY_LEVEL_DRAIN_CUTOFF) { 1501 // If the user activity timeout expired and the battery appears 1502 // to be draining faster than it is charging then stop dreaming 1503 // and go to sleep. 1504 Slog.i(TAG, "Stopping dream because the battery appears to " 1505 + "be draining faster than it is charging. " 1506 + "Battery level when dream started: " 1507 + mBatteryLevelWhenDreamStarted + "%. " 1508 + "Battery level now: " + mBatteryLevel + "%."); 1509 } else { 1510 continueDreaming = true; 1511 } 1512 } 1513 } 1514 if (!continueDreaming) { 1515 handleDreamFinishedLocked(); 1516 } 1517 } 1518 1519 // Stop dreaming if needed. 1520 // It's possible that something else changed to make us need to start the dream again. 1521 // If so, then the power manager will have posted another message to the handler 1522 // to take care of it later. 1523 if (mDreamManager != null) { 1524 if (!continueDreaming) { 1525 mDreamManager.stopDream(); 1526 } 1527 } 1528 } 1529 1530 /** 1531 * Returns true if the device is allowed to dream in its current state 1532 * assuming that it is currently napping or dreaming. 1533 */ 1534 private boolean canDreamLocked() { 1535 return mDreamsSupportedConfig 1536 && mDreamsEnabledSetting 1537 && mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF 1538 && mBootCompleted 1539 && (mIsPowered || isBeingKeptAwakeLocked()); 1540 } 1541 1542 /** 1543 * Called when a dream is ending to figure out what to do next. 1544 */ 1545 private void handleDreamFinishedLocked() { 1546 if (mWakefulness == WAKEFULNESS_NAPPING 1547 || mWakefulness == WAKEFULNESS_DREAMING) { 1548 if (isItBedTimeYetLocked()) { 1549 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1550 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1551 updatePowerStateLocked(); 1552 } else { 1553 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 1554 updatePowerStateLocked(); 1555 } 1556 } 1557 } 1558 1559 private void handleScreenOnBlockerReleased() { 1560 synchronized (mLock) { 1561 mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED; 1562 updatePowerStateLocked(); 1563 } 1564 } 1565 1566 /** 1567 * Updates the display power state asynchronously. 1568 * When the update is finished, mDisplayReady will be set to true. The display 1569 * controller posts a message to tell us when the actual display power state 1570 * has been updated so we come back here to double-check and finish up. 1571 * 1572 * This function recalculates the display power state each time. 1573 */ 1574 private void updateDisplayPowerStateLocked(int dirty) { 1575 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1576 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1577 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) { 1578 int newScreenState = getDesiredScreenPowerStateLocked(); 1579 if (newScreenState != mDisplayPowerRequest.screenState) { 1580 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF 1581 && mDisplayPowerRequest.screenState 1582 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1583 mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime(); 1584 } 1585 1586 mDisplayPowerRequest.screenState = newScreenState; 1587 nativeSetPowerState( 1588 newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF, 1589 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT); 1590 } 1591 1592 int screenBrightness = mScreenBrightnessSettingDefault; 1593 float screenAutoBrightnessAdjustment = 0.0f; 1594 boolean autoBrightness = (mScreenBrightnessModeSetting == 1595 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1596 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1597 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1598 autoBrightness = false; 1599 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1600 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1601 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1602 screenBrightness = mScreenBrightnessSetting; 1603 } 1604 if (autoBrightness) { 1605 screenBrightness = mScreenBrightnessSettingDefault; 1606 if (isValidAutoBrightnessAdjustment( 1607 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1608 screenAutoBrightnessAdjustment = 1609 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1610 } else if (isValidAutoBrightnessAdjustment( 1611 mScreenAutoBrightnessAdjustmentSetting)) { 1612 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1613 } 1614 } 1615 screenBrightness = Math.max(Math.min(screenBrightness, 1616 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1617 screenAutoBrightnessAdjustment = Math.max(Math.min( 1618 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1619 mDisplayPowerRequest.screenBrightness = screenBrightness; 1620 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1621 screenAutoBrightnessAdjustment; 1622 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1623 1624 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1625 1626 mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld(); 1627 1628 mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest, 1629 mRequestWaitForNegativeProximity); 1630 mRequestWaitForNegativeProximity = false; 1631 1632 if (DEBUG_SPEW) { 1633 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady 1634 + ", newScreenState=" + newScreenState 1635 + ", mWakefulness=" + mWakefulness 1636 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1637 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1638 + ", mBootCompleted=" + mBootCompleted); 1639 } 1640 } 1641 } 1642 1643 private static boolean isValidBrightness(int value) { 1644 return value >= 0 && value <= 255; 1645 } 1646 1647 private static boolean isValidAutoBrightnessAdjustment(float value) { 1648 // Handles NaN by always returning false. 1649 return value >= -1.0f && value <= 1.0f; 1650 } 1651 1652 private int getDesiredScreenPowerStateLocked() { 1653 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1654 return DisplayPowerRequest.SCREEN_STATE_OFF; 1655 } 1656 1657 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1658 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1659 || !mBootCompleted) { 1660 return DisplayPowerRequest.SCREEN_STATE_BRIGHT; 1661 } 1662 1663 return DisplayPowerRequest.SCREEN_STATE_DIM; 1664 } 1665 1666 private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks = 1667 new DisplayPowerController.Callbacks() { 1668 @Override 1669 public void onStateChanged() { 1670 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1671 updatePowerStateLocked(); 1672 } 1673 1674 @Override 1675 public void onProximityPositive() { 1676 mProximityPositive = true; 1677 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1678 updatePowerStateLocked(); 1679 } 1680 1681 @Override 1682 public void onProximityNegative() { 1683 mProximityPositive = false; 1684 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1685 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1686 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1687 updatePowerStateLocked(); 1688 } 1689 }; 1690 1691 private boolean shouldUseProximitySensorLocked() { 1692 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 1693 } 1694 1695 /** 1696 * Updates the suspend blocker that keeps the CPU alive. 1697 * 1698 * This function must have no other side-effects. 1699 */ 1700 private void updateSuspendBlockerLocked() { 1701 boolean wantCpu = isCpuNeededLocked(); 1702 if (wantCpu != mHoldingWakeLockSuspendBlocker) { 1703 mHoldingWakeLockSuspendBlocker = wantCpu; 1704 if (wantCpu) { 1705 if (DEBUG) { 1706 Slog.d(TAG, "updateSuspendBlockerLocked: Acquiring suspend blocker."); 1707 } 1708 mWakeLockSuspendBlocker.acquire(); 1709 } else { 1710 if (DEBUG) { 1711 Slog.d(TAG, "updateSuspendBlockerLocked: Releasing suspend blocker."); 1712 } 1713 mWakeLockSuspendBlocker.release(); 1714 } 1715 } 1716 } 1717 1718 private boolean isCpuNeededLocked() { 1719 return !mBootCompleted 1720 || mWakeLockSummary != 0 1721 || mUserActivitySummary != 0 1722 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF 1723 || !mDisplayReady; 1724 } 1725 1726 @Override // Binder call 1727 public boolean isScreenOn() { 1728 final long ident = Binder.clearCallingIdentity(); 1729 try { 1730 return isScreenOnInternal(); 1731 } finally { 1732 Binder.restoreCallingIdentity(ident); 1733 } 1734 } 1735 1736 private boolean isScreenOnInternal() { 1737 synchronized (mLock) { 1738 return !mSystemReady 1739 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF; 1740 } 1741 } 1742 1743 private void handleBatteryStateChangedLocked() { 1744 mDirty |= DIRTY_BATTERY_STATE; 1745 updatePowerStateLocked(); 1746 } 1747 1748 private void startWatchingForBootAnimationFinished() { 1749 mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED); 1750 } 1751 1752 private void checkIfBootAnimationFinished() { 1753 if (DEBUG) { 1754 Slog.d(TAG, "Check if boot animation finished..."); 1755 } 1756 1757 if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) { 1758 mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED, 1759 BOOT_ANIMATION_POLL_INTERVAL); 1760 return; 1761 } 1762 1763 synchronized (mLock) { 1764 if (!mBootCompleted) { 1765 Slog.i(TAG, "Boot animation finished."); 1766 handleBootCompletedLocked(); 1767 } 1768 } 1769 } 1770 1771 private void handleBootCompletedLocked() { 1772 final long now = SystemClock.uptimeMillis(); 1773 mBootCompleted = true; 1774 mDirty |= DIRTY_BOOT_COMPLETED; 1775 userActivityNoUpdateLocked( 1776 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1777 updatePowerStateLocked(); 1778 } 1779 1780 /** 1781 * Reboots the device. 1782 * 1783 * @param confirm If true, shows a reboot confirmation dialog. 1784 * @param reason The reason for the reboot, or null if none. 1785 * @param wait If true, this call waits for the reboot to complete and does not return. 1786 */ 1787 @Override // Binder call 1788 public void reboot(boolean confirm, String reason, boolean wait) { 1789 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1790 1791 final long ident = Binder.clearCallingIdentity(); 1792 try { 1793 shutdownOrRebootInternal(false, confirm, reason, wait); 1794 } finally { 1795 Binder.restoreCallingIdentity(ident); 1796 } 1797 } 1798 1799 /** 1800 * Shuts down the device. 1801 * 1802 * @param confirm If true, shows a shutdown confirmation dialog. 1803 * @param wait If true, this call waits for the shutdown to complete and does not return. 1804 */ 1805 @Override // Binder call 1806 public void shutdown(boolean confirm, boolean wait) { 1807 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1808 1809 final long ident = Binder.clearCallingIdentity(); 1810 try { 1811 shutdownOrRebootInternal(true, confirm, null, wait); 1812 } finally { 1813 Binder.restoreCallingIdentity(ident); 1814 } 1815 } 1816 1817 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm, 1818 final String reason, boolean wait) { 1819 if (mHandler == null || !mSystemReady) { 1820 throw new IllegalStateException("Too early to call shutdown() or reboot()"); 1821 } 1822 1823 Runnable runnable = new Runnable() { 1824 @Override 1825 public void run() { 1826 synchronized (this) { 1827 if (shutdown) { 1828 ShutdownThread.shutdown(mContext, confirm); 1829 } else { 1830 ShutdownThread.reboot(mContext, reason, confirm); 1831 } 1832 } 1833 } 1834 }; 1835 1836 // ShutdownThread must run on a looper capable of displaying the UI. 1837 Message msg = Message.obtain(mHandler, runnable); 1838 msg.setAsynchronous(true); 1839 mHandler.sendMessage(msg); 1840 1841 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 1842 if (wait) { 1843 synchronized (runnable) { 1844 while (true) { 1845 try { 1846 runnable.wait(); 1847 } catch (InterruptedException e) { 1848 } 1849 } 1850 } 1851 } 1852 } 1853 1854 /** 1855 * Crash the runtime (causing a complete restart of the Android framework). 1856 * Requires REBOOT permission. Mostly for testing. Should not return. 1857 */ 1858 @Override // Binder call 1859 public void crash(String message) { 1860 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1861 1862 final long ident = Binder.clearCallingIdentity(); 1863 try { 1864 crashInternal(message); 1865 } finally { 1866 Binder.restoreCallingIdentity(ident); 1867 } 1868 } 1869 1870 private void crashInternal(final String message) { 1871 Thread t = new Thread("PowerManagerService.crash()") { 1872 @Override 1873 public void run() { 1874 throw new RuntimeException(message); 1875 } 1876 }; 1877 try { 1878 t.start(); 1879 t.join(); 1880 } catch (InterruptedException e) { 1881 Log.wtf(TAG, e); 1882 } 1883 } 1884 1885 /** 1886 * Set the setting that determines whether the device stays on when plugged in. 1887 * The argument is a bit string, with each bit specifying a power source that, 1888 * when the device is connected to that source, causes the device to stay on. 1889 * See {@link android.os.BatteryManager} for the list of power sources that 1890 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 1891 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 1892 * 1893 * Used by "adb shell svc power stayon ..." 1894 * 1895 * @param val an {@code int} containing the bits that specify which power sources 1896 * should cause the device to stay on. 1897 */ 1898 @Override // Binder call 1899 public void setStayOnSetting(int val) { 1900 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null); 1901 1902 final long ident = Binder.clearCallingIdentity(); 1903 try { 1904 setStayOnSettingInternal(val); 1905 } finally { 1906 Binder.restoreCallingIdentity(ident); 1907 } 1908 } 1909 1910 private void setStayOnSettingInternal(int val) { 1911 Settings.Global.putInt(mContext.getContentResolver(), 1912 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 1913 } 1914 1915 /** 1916 * Used by device administration to set the maximum screen off timeout. 1917 * 1918 * This method must only be called by the device administration policy manager. 1919 */ 1920 @Override // Binder call 1921 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 1922 final long ident = Binder.clearCallingIdentity(); 1923 try { 1924 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 1925 } finally { 1926 Binder.restoreCallingIdentity(ident); 1927 } 1928 } 1929 1930 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 1931 synchronized (mLock) { 1932 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 1933 mDirty |= DIRTY_SETTINGS; 1934 updatePowerStateLocked(); 1935 } 1936 } 1937 1938 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 1939 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 1940 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 1941 } 1942 1943 /** 1944 * Used by the phone application to make the attention LED flash when ringing. 1945 */ 1946 @Override // Binder call 1947 public void setAttentionLight(boolean on, int color) { 1948 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1949 1950 final long ident = Binder.clearCallingIdentity(); 1951 try { 1952 setAttentionLightInternal(on, color); 1953 } finally { 1954 Binder.restoreCallingIdentity(ident); 1955 } 1956 } 1957 1958 private void setAttentionLightInternal(boolean on, int color) { 1959 LightsService.Light light; 1960 synchronized (mLock) { 1961 if (!mSystemReady) { 1962 return; 1963 } 1964 light = mAttentionLight; 1965 } 1966 1967 // Control light outside of lock. 1968 light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 1969 } 1970 1971 /** 1972 * Used by the Watchdog. 1973 */ 1974 public long timeSinceScreenWasLastOn() { 1975 synchronized (mLock) { 1976 if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) { 1977 return 0; 1978 } 1979 return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime; 1980 } 1981 } 1982 1983 /** 1984 * Used by the window manager to override the screen brightness based on the 1985 * current foreground activity. 1986 * 1987 * This method must only be called by the window manager. 1988 * 1989 * @param brightness The overridden brightness, or -1 to disable the override. 1990 */ 1991 public void setScreenBrightnessOverrideFromWindowManager(int brightness) { 1992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1993 1994 final long ident = Binder.clearCallingIdentity(); 1995 try { 1996 setScreenBrightnessOverrideFromWindowManagerInternal(brightness); 1997 } finally { 1998 Binder.restoreCallingIdentity(ident); 1999 } 2000 } 2001 2002 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 2003 synchronized (mLock) { 2004 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 2005 mScreenBrightnessOverrideFromWindowManager = brightness; 2006 mDirty |= DIRTY_SETTINGS; 2007 updatePowerStateLocked(); 2008 } 2009 } 2010 } 2011 2012 /** 2013 * Used by the window manager to override the button brightness based on the 2014 * current foreground activity. 2015 * 2016 * This method must only be called by the window manager. 2017 * 2018 * @param brightness The overridden brightness, or -1 to disable the override. 2019 */ 2020 public void setButtonBrightnessOverrideFromWindowManager(int brightness) { 2021 // Do nothing. 2022 // Button lights are not currently supported in the new implementation. 2023 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2024 } 2025 2026 /** 2027 * Used by the window manager to override the user activity timeout based on the 2028 * current foreground activity. It can only be used to make the timeout shorter 2029 * than usual, not longer. 2030 * 2031 * This method must only be called by the window manager. 2032 * 2033 * @param timeoutMillis The overridden timeout, or -1 to disable the override. 2034 */ 2035 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 2036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2037 2038 final long ident = Binder.clearCallingIdentity(); 2039 try { 2040 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 2041 } finally { 2042 Binder.restoreCallingIdentity(ident); 2043 } 2044 } 2045 2046 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 2047 synchronized (mLock) { 2048 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 2049 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 2050 mDirty |= DIRTY_SETTINGS; 2051 updatePowerStateLocked(); 2052 } 2053 } 2054 } 2055 2056 /** 2057 * Used by the settings application and brightness control widgets to 2058 * temporarily override the current screen brightness setting so that the 2059 * user can observe the effect of an intended settings change without applying 2060 * it immediately. 2061 * 2062 * The override will be canceled when the setting value is next updated. 2063 * 2064 * @param brightness The overridden brightness. 2065 * 2066 * @see Settings.System#SCREEN_BRIGHTNESS 2067 */ 2068 @Override // Binder call 2069 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 2070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2071 2072 final long ident = Binder.clearCallingIdentity(); 2073 try { 2074 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 2075 } finally { 2076 Binder.restoreCallingIdentity(ident); 2077 } 2078 } 2079 2080 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 2081 synchronized (mLock) { 2082 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 2083 mTemporaryScreenBrightnessSettingOverride = brightness; 2084 mDirty |= DIRTY_SETTINGS; 2085 updatePowerStateLocked(); 2086 } 2087 } 2088 } 2089 2090 /** 2091 * Used by the settings application and brightness control widgets to 2092 * temporarily override the current screen auto-brightness adjustment setting so that the 2093 * user can observe the effect of an intended settings change without applying 2094 * it immediately. 2095 * 2096 * The override will be canceled when the setting value is next updated. 2097 * 2098 * @param adj The overridden brightness, or Float.NaN to disable the override. 2099 * 2100 * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 2101 */ 2102 @Override // Binder call 2103 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 2104 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2105 2106 final long ident = Binder.clearCallingIdentity(); 2107 try { 2108 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 2109 } finally { 2110 Binder.restoreCallingIdentity(ident); 2111 } 2112 } 2113 2114 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 2115 synchronized (mLock) { 2116 // Note: This condition handles NaN because NaN is not equal to any other 2117 // value, including itself. 2118 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 2119 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 2120 mDirty |= DIRTY_SETTINGS; 2121 updatePowerStateLocked(); 2122 } 2123 } 2124 } 2125 2126 /** 2127 * Low-level function turn the device off immediately, without trying 2128 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 2129 */ 2130 public static void lowLevelShutdown() { 2131 nativeShutdown(); 2132 } 2133 2134 /** 2135 * Low-level function to reboot the device. 2136 * 2137 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 2138 * @throws IOException if reboot fails for some reason (eg, lack of 2139 * permission) 2140 */ 2141 public static void lowLevelReboot(String reason) throws IOException { 2142 nativeReboot(reason); 2143 } 2144 2145 @Override // Watchdog.Monitor implementation 2146 public void monitor() { 2147 // Grab and release lock for watchdog monitor to detect deadlocks. 2148 synchronized (mLock) { 2149 } 2150 } 2151 2152 @Override // Binder call 2153 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2154 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 2155 != PackageManager.PERMISSION_GRANTED) { 2156 pw.println("Permission Denial: can't dump PowerManager from from pid=" 2157 + Binder.getCallingPid() 2158 + ", uid=" + Binder.getCallingUid()); 2159 return; 2160 } 2161 2162 pw.println("POWER MANAGER (dumpsys power)\n"); 2163 2164 final DisplayPowerController dpc; 2165 synchronized (mLock) { 2166 pw.println("Power Manager State:"); 2167 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 2168 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness)); 2169 pw.println(" mIsPowered=" + mIsPowered); 2170 pw.println(" mPlugType=" + mPlugType); 2171 pw.println(" mBatteryLevel=" + mBatteryLevel); 2172 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted); 2173 pw.println(" mDockState=" + mDockState); 2174 pw.println(" mStayOn=" + mStayOn); 2175 pw.println(" mProximityPositive=" + mProximityPositive); 2176 pw.println(" mBootCompleted=" + mBootCompleted); 2177 pw.println(" mSystemReady=" + mSystemReady); 2178 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 2179 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 2180 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 2181 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 2182 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 2183 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 2184 pw.println(" mSendWakeUpFinishedNotificationWhenReady=" 2185 + mSendWakeUpFinishedNotificationWhenReady); 2186 pw.println(" mSendGoToSleepFinishedNotificationWhenReady=" 2187 + mSendGoToSleepFinishedNotificationWhenReady); 2188 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 2189 pw.println(" mLastUserActivityTimeNoChangeLights=" 2190 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 2191 pw.println(" mDisplayReady=" + mDisplayReady); 2192 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 2193 2194 pw.println(); 2195 pw.println("Settings and Configuration:"); 2196 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 2197 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 2198 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 2199 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting); 2200 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 2201 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 2202 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 2203 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 2204 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 2205 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 2206 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 2207 + mScreenAutoBrightnessAdjustmentSetting); 2208 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 2209 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 2210 + mScreenBrightnessOverrideFromWindowManager); 2211 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 2212 + mUserActivityTimeoutOverrideFromWindowManager); 2213 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 2214 + mTemporaryScreenBrightnessSettingOverride); 2215 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 2216 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 2217 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 2218 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 2219 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 2220 2221 final int screenOffTimeout = getScreenOffTimeoutLocked(); 2222 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 2223 pw.println(); 2224 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2225 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2226 2227 pw.println(); 2228 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2229 for (WakeLock wl : mWakeLocks) { 2230 pw.println(" " + wl); 2231 } 2232 2233 pw.println(); 2234 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2235 for (SuspendBlocker sb : mSuspendBlockers) { 2236 pw.println(" " + sb); 2237 } 2238 2239 pw.println(); 2240 pw.println("Screen On Blocker: " + mScreenOnBlocker); 2241 2242 pw.println(); 2243 pw.println("Display Blanker: " + mDisplayBlanker); 2244 2245 dpc = mDisplayPowerController; 2246 } 2247 2248 if (dpc != null) { 2249 dpc.dump(pw); 2250 } 2251 } 2252 2253 private SuspendBlocker createSuspendBlockerLocked(String name) { 2254 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2255 mSuspendBlockers.add(suspendBlocker); 2256 return suspendBlocker; 2257 } 2258 2259 private static String wakefulnessToString(int wakefulness) { 2260 switch (wakefulness) { 2261 case WAKEFULNESS_ASLEEP: 2262 return "Asleep"; 2263 case WAKEFULNESS_AWAKE: 2264 return "Awake"; 2265 case WAKEFULNESS_DREAMING: 2266 return "Dreaming"; 2267 case WAKEFULNESS_NAPPING: 2268 return "Napping"; 2269 default: 2270 return Integer.toString(wakefulness); 2271 } 2272 } 2273 2274 private static WorkSource copyWorkSource(WorkSource workSource) { 2275 return workSource != null ? new WorkSource(workSource) : null; 2276 } 2277 2278 private final class BatteryReceiver extends BroadcastReceiver { 2279 @Override 2280 public void onReceive(Context context, Intent intent) { 2281 synchronized (mLock) { 2282 handleBatteryStateChangedLocked(); 2283 } 2284 } 2285 } 2286 2287 private final class BootCompletedReceiver extends BroadcastReceiver { 2288 @Override 2289 public void onReceive(Context context, Intent intent) { 2290 // This is our early signal that the system thinks it has finished booting. 2291 // However, the boot animation may still be running for a few more seconds 2292 // since it is ultimately in charge of when it terminates. 2293 // Defer transitioning into the boot completed state until the animation exits. 2294 // We do this so that the screen does not start to dim prematurely before 2295 // the user has actually had a chance to interact with the device. 2296 startWatchingForBootAnimationFinished(); 2297 } 2298 } 2299 2300 private final class DreamReceiver extends BroadcastReceiver { 2301 @Override 2302 public void onReceive(Context context, Intent intent) { 2303 synchronized (mLock) { 2304 scheduleSandmanLocked(); 2305 } 2306 } 2307 } 2308 2309 private final class UserSwitchedReceiver extends BroadcastReceiver { 2310 @Override 2311 public void onReceive(Context context, Intent intent) { 2312 synchronized (mLock) { 2313 handleSettingsChangedLocked(); 2314 } 2315 } 2316 } 2317 2318 private final class DockReceiver extends BroadcastReceiver { 2319 @Override 2320 public void onReceive(Context context, Intent intent) { 2321 synchronized (mLock) { 2322 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2323 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2324 if (mDockState != dockState) { 2325 mDockState = dockState; 2326 mDirty |= DIRTY_DOCK_STATE; 2327 updatePowerStateLocked(); 2328 } 2329 } 2330 } 2331 } 2332 2333 private final class SettingsObserver extends ContentObserver { 2334 public SettingsObserver(Handler handler) { 2335 super(handler); 2336 } 2337 2338 @Override 2339 public void onChange(boolean selfChange, Uri uri) { 2340 synchronized (mLock) { 2341 handleSettingsChangedLocked(); 2342 } 2343 } 2344 } 2345 2346 /** 2347 * Handler for asynchronous operations performed by the power manager. 2348 */ 2349 private final class PowerManagerHandler extends Handler { 2350 public PowerManagerHandler(Looper looper) { 2351 super(looper, null, true /*async*/); 2352 } 2353 2354 @Override 2355 public void handleMessage(Message msg) { 2356 switch (msg.what) { 2357 case MSG_USER_ACTIVITY_TIMEOUT: 2358 handleUserActivityTimeout(); 2359 break; 2360 case MSG_SANDMAN: 2361 handleSandman(); 2362 break; 2363 case MSG_SCREEN_ON_BLOCKER_RELEASED: 2364 handleScreenOnBlockerReleased(); 2365 break; 2366 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED: 2367 checkIfBootAnimationFinished(); 2368 break; 2369 } 2370 } 2371 } 2372 2373 /** 2374 * Represents a wake lock that has been acquired by an application. 2375 */ 2376 private final class WakeLock implements IBinder.DeathRecipient { 2377 public final IBinder mLock; 2378 public int mFlags; 2379 public String mTag; 2380 public WorkSource mWorkSource; 2381 public int mOwnerUid; 2382 public int mOwnerPid; 2383 2384 public WakeLock(IBinder lock, int flags, String tag, WorkSource workSource, 2385 int ownerUid, int ownerPid) { 2386 mLock = lock; 2387 mFlags = flags; 2388 mTag = tag; 2389 mWorkSource = copyWorkSource(workSource); 2390 mOwnerUid = ownerUid; 2391 mOwnerPid = ownerPid; 2392 } 2393 2394 @Override 2395 public void binderDied() { 2396 PowerManagerService.this.handleWakeLockDeath(this); 2397 } 2398 2399 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 2400 int ownerUid, int ownerPid) { 2401 return mFlags == flags 2402 && mTag.equals(tag) 2403 && hasSameWorkSource(workSource) 2404 && mOwnerUid == ownerUid 2405 && mOwnerPid == ownerPid; 2406 } 2407 2408 public void updateProperties(int flags, String tag, WorkSource workSource, 2409 int ownerUid, int ownerPid) { 2410 mFlags = flags; 2411 mTag = tag; 2412 updateWorkSource(workSource); 2413 mOwnerUid = ownerUid; 2414 mOwnerPid = ownerPid; 2415 } 2416 2417 public boolean hasSameWorkSource(WorkSource workSource) { 2418 return Objects.equal(mWorkSource, workSource); 2419 } 2420 2421 public void updateWorkSource(WorkSource workSource) { 2422 mWorkSource = copyWorkSource(workSource); 2423 } 2424 2425 @Override 2426 public String toString() { 2427 return getLockLevelString() 2428 + " '" + mTag + "'" + getLockFlagsString() 2429 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2430 } 2431 2432 private String getLockLevelString() { 2433 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2434 case PowerManager.FULL_WAKE_LOCK: 2435 return "FULL_WAKE_LOCK "; 2436 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2437 return "SCREEN_BRIGHT_WAKE_LOCK "; 2438 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2439 return "SCREEN_DIM_WAKE_LOCK "; 2440 case PowerManager.PARTIAL_WAKE_LOCK: 2441 return "PARTIAL_WAKE_LOCK "; 2442 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2443 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2444 default: 2445 return "??? "; 2446 } 2447 } 2448 2449 private String getLockFlagsString() { 2450 String result = ""; 2451 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2452 result += " ACQUIRE_CAUSES_WAKEUP"; 2453 } 2454 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2455 result += " ON_AFTER_RELEASE"; 2456 } 2457 return result; 2458 } 2459 } 2460 2461 private final class SuspendBlockerImpl implements SuspendBlocker { 2462 private final String mName; 2463 private int mReferenceCount; 2464 2465 public SuspendBlockerImpl(String name) { 2466 mName = name; 2467 } 2468 2469 @Override 2470 protected void finalize() throws Throwable { 2471 try { 2472 if (mReferenceCount != 0) { 2473 Log.wtf(TAG, "Suspend blocker \"" + mName 2474 + "\" was finalized without being released!"); 2475 mReferenceCount = 0; 2476 nativeReleaseSuspendBlocker(mName); 2477 } 2478 } finally { 2479 super.finalize(); 2480 } 2481 } 2482 2483 @Override 2484 public void acquire() { 2485 synchronized (this) { 2486 mReferenceCount += 1; 2487 if (mReferenceCount == 1) { 2488 nativeAcquireSuspendBlocker(mName); 2489 } 2490 } 2491 } 2492 2493 @Override 2494 public void release() { 2495 synchronized (this) { 2496 mReferenceCount -= 1; 2497 if (mReferenceCount == 0) { 2498 nativeReleaseSuspendBlocker(mName); 2499 } else if (mReferenceCount < 0) { 2500 Log.wtf(TAG, "Suspend blocker \"" + mName 2501 + "\" was released without being acquired!", new Throwable()); 2502 mReferenceCount = 0; 2503 } 2504 } 2505 } 2506 2507 @Override 2508 public String toString() { 2509 synchronized (this) { 2510 return mName + ": ref count=" + mReferenceCount; 2511 } 2512 } 2513 } 2514 2515 private final class ScreenOnBlockerImpl implements ScreenOnBlocker { 2516 private int mNestCount; 2517 2518 public boolean isHeld() { 2519 synchronized (this) { 2520 return mNestCount != 0; 2521 } 2522 } 2523 2524 @Override 2525 public void acquire() { 2526 synchronized (this) { 2527 mNestCount += 1; 2528 if (DEBUG) { 2529 Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount); 2530 } 2531 } 2532 } 2533 2534 @Override 2535 public void release() { 2536 synchronized (this) { 2537 mNestCount -= 1; 2538 if (mNestCount < 0) { 2539 Log.wtf(TAG, "Screen on blocker was released without being acquired!", 2540 new Throwable()); 2541 mNestCount = 0; 2542 } 2543 if (mNestCount == 0) { 2544 mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED); 2545 } 2546 if (DEBUG) { 2547 Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount); 2548 } 2549 } 2550 } 2551 2552 @Override 2553 public String toString() { 2554 synchronized (this) { 2555 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount; 2556 } 2557 } 2558 } 2559 2560 private final class DisplayBlankerImpl implements DisplayBlanker { 2561 private boolean mBlanked; 2562 2563 @Override 2564 public void blankAllDisplays() { 2565 synchronized (this) { 2566 mBlanked = true; 2567 mDisplayManagerService.blankAllDisplaysFromPowerManager(); 2568 nativeSetInteractive(false); 2569 nativeSetAutoSuspend(true); 2570 } 2571 } 2572 2573 @Override 2574 public void unblankAllDisplays() { 2575 synchronized (this) { 2576 nativeSetAutoSuspend(false); 2577 nativeSetInteractive(true); 2578 mDisplayManagerService.unblankAllDisplaysFromPowerManager(); 2579 mBlanked = false; 2580 } 2581 } 2582 2583 @Override 2584 public String toString() { 2585 synchronized (this) { 2586 return "blanked=" + mBlanked; 2587 } 2588 } 2589 } 2590 } 2591