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