PowerManagerService.java revision 330560f53bccd06be805fee1b7988162119d1295
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.Watchdog; 24import com.android.server.am.ActivityManagerService; 25import com.android.server.display.DisplayManagerService; 26 27import android.Manifest; 28import android.content.BroadcastReceiver; 29import android.content.ContentResolver; 30import android.content.Context; 31import android.content.Intent; 32import android.content.IntentFilter; 33import android.content.pm.PackageManager; 34import android.content.res.Resources; 35import android.database.ContentObserver; 36import android.net.Uri; 37import android.os.BatteryManager; 38import android.os.Binder; 39import android.os.Handler; 40import android.os.HandlerThread; 41import android.os.IBinder; 42import android.os.IPowerManager; 43import android.os.Looper; 44import android.os.Message; 45import android.os.PowerManager; 46import android.os.Process; 47import android.os.RemoteException; 48import android.os.ServiceManager; 49import android.os.SystemClock; 50import android.os.WorkSource; 51import android.provider.Settings; 52import android.service.dreams.IDreamManager; 53import android.util.EventLog; 54import android.util.Log; 55import android.util.Slog; 56import android.util.TimeUtils; 57import android.view.WindowManagerPolicy; 58 59import java.io.FileDescriptor; 60import java.io.IOException; 61import java.io.PrintWriter; 62import java.util.ArrayList; 63 64import libcore.util.Objects; 65 66/** 67 * The power manager service is responsible for coordinating power management 68 * functions on the device. 69 */ 70public final class PowerManagerService extends IPowerManager.Stub 71 implements Watchdog.Monitor { 72 private static final String TAG = "PowerManagerService"; 73 74 private static final boolean DEBUG = false; 75 private static final boolean DEBUG_SPEW = DEBUG && true; 76 77 // Message: Sent when a user activity timeout occurs to update the power state. 78 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 79 // Message: Sent when the device enters or exits a napping or dreaming state. 80 private static final int MSG_SANDMAN = 2; 81 82 // Dirty bit: mWakeLocks changed 83 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 84 // Dirty bit: mWakefulness changed 85 private static final int DIRTY_WAKEFULNESS = 1 << 1; 86 // Dirty bit: user activity was poked or may have timed out 87 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 88 // Dirty bit: actual display power state was updated asynchronously 89 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 90 // Dirty bit: mBootCompleted changed 91 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 92 // Dirty bit: settings changed 93 private static final int DIRTY_SETTINGS = 1 << 5; 94 // Dirty bit: mIsPowered changed 95 private static final int DIRTY_IS_POWERED = 1 << 6; 96 // Dirty bit: mStayOn changed 97 private static final int DIRTY_STAY_ON = 1 << 7; 98 // Dirty bit: battery state changed 99 private static final int DIRTY_BATTERY_STATE = 1 << 8; 100 101 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp(). 102 // The screen should be off or in the process of being turned off by the display controller. 103 private static final int WAKEFULNESS_ASLEEP = 0; 104 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep(). 105 // When the user activity timeout expires, the device may start napping. 106 private static final int WAKEFULNESS_AWAKE = 1; 107 // Wakefulness: The device is napping. It is deciding whether to dream or go to sleep 108 // but hasn't gotten around to it yet. It can be awoken by a call to wakeUp(), which 109 // ends the nap. User activity may brighten the screen but does not end the nap. 110 private static final int WAKEFULNESS_NAPPING = 2; 111 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(), 112 // which ends the dream. The device goes to sleep when goToSleep() is called, when 113 // the dream ends or when unplugged. 114 // User activity may brighten the screen but does not end the dream. 115 private static final int WAKEFULNESS_DREAMING = 3; 116 117 // Summarizes the state of all active wakelocks. 118 private static final int WAKE_LOCK_CPU = 1 << 0; 119 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 120 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 121 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 122 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 123 124 // Summarizes the user activity state. 125 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 126 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 127 128 // Default and minimum screen off timeout in milliseconds. 129 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 130 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000; 131 132 // The screen dim duration, in seconds. 133 // This is subtracted from the end of the screen off timeout so the 134 // minimum screen off timeout should be longer than this. 135 private static final int SCREEN_DIM_DURATION = 7 * 1000; 136 137 private Context mContext; 138 private LightsService mLightsService; 139 private BatteryService mBatteryService; 140 private IBatteryStats mBatteryStats; 141 private HandlerThread mHandlerThread; 142 private PowerManagerHandler mHandler; 143 private WindowManagerPolicy mPolicy; 144 private Notifier mNotifier; 145 private DisplayPowerController mDisplayPowerController; 146 private SettingsObserver mSettingsObserver; 147 private IDreamManager mDreamManager; 148 private LightsService.Light mAttentionLight; 149 150 private final Object mLock = new Object(); 151 152 // A bitfield that indicates what parts of the power state have 153 // changed and need to be recalculated. 154 private int mDirty; 155 156 // Indicates whether the device is awake or asleep or somewhere in between. 157 // This is distinct from the screen power state, which is managed separately. 158 private int mWakefulness; 159 160 // True if MSG_SANDMAN has been scheduled. 161 private boolean mSandmanScheduled; 162 163 // Table of all suspend blockers. 164 // There should only be a few of these. 165 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 166 167 // Table of all wake locks acquired by applications. 168 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 169 170 // A bitfield that summarizes the state of all active wakelocks. 171 private int mWakeLockSummary; 172 173 // If true, instructs the display controller to wait for the proximity sensor to 174 // go negative before turning the screen on. 175 private boolean mRequestWaitForNegativeProximity; 176 177 // Timestamp of the last time the device was awoken or put to sleep. 178 private long mLastWakeTime; 179 private long mLastSleepTime; 180 181 // True if we need to send a wake up or go to sleep finished notification 182 // when the display is ready. 183 private boolean mSendWakeUpFinishedNotificationWhenReady; 184 private boolean mSendGoToSleepFinishedNotificationWhenReady; 185 186 // Timestamp of the last call to user activity. 187 private long mLastUserActivityTime; 188 private long mLastUserActivityTimeNoChangeLights; 189 190 // A bitfield that summarizes the effect of the user activity timer. 191 // A zero value indicates that the user activity timer has expired. 192 private int mUserActivitySummary; 193 194 // The desired display power state. The actual state may lag behind the 195 // requested because it is updated asynchronously by the display power controller. 196 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 197 198 // The time the screen was last turned off, in elapsedRealtime() timebase. 199 private long mLastScreenOffEventElapsedRealTime; 200 201 // True if the display power state has been fully applied, which means the display 202 // is actually on or actually off or whatever was requested. 203 private boolean mDisplayReady; 204 205 // True if holding a wake-lock to block suspend of the CPU. 206 private boolean mHoldingWakeLockSuspendBlocker; 207 208 // The suspend blocker used to keep the CPU alive when wake locks have been acquired. 209 private final SuspendBlocker mWakeLockSuspendBlocker; 210 211 // True if systemReady() has been called. 212 private boolean mSystemReady; 213 214 // True if boot completed occurred. We keep the screen on until this happens. 215 private boolean mBootCompleted; 216 217 // True if the device is plugged into a power source. 218 private boolean mIsPowered; 219 220 // True if the device should wake up when plugged or unplugged. 221 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 222 223 // True if dreams are supported on this device. 224 private boolean mDreamsSupportedConfig; 225 226 // True if dreams are enabled by the user. 227 private boolean mDreamsEnabledSetting; 228 229 // The screen off timeout setting value in milliseconds. 230 private int mScreenOffTimeoutSetting; 231 232 // The maximum allowable screen off timeout according to the device 233 // administration policy. Overrides other settings. 234 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 235 236 // The stay on while plugged in setting. 237 // A bitfield of battery conditions under which to make the screen stay on. 238 private int mStayOnWhilePluggedInSetting; 239 240 // True if the device should stay on. 241 private boolean mStayOn; 242 243 // Screen brightness setting limits. 244 private int mScreenBrightnessSettingMinimum; 245 private int mScreenBrightnessSettingMaximum; 246 private int mScreenBrightnessSettingDefault; 247 248 // The screen brightness setting, from 0 to 255. 249 // Use -1 if no value has been set. 250 private int mScreenBrightnessSetting; 251 252 // The screen auto-brightness adjustment setting, from -1 to 1. 253 // Use 0 if there is no adjustment. 254 private float mScreenAutoBrightnessAdjustmentSetting; 255 256 // The screen brightness mode. 257 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 258 private int mScreenBrightnessModeSetting; 259 260 // The screen brightness setting override from the window manager 261 // to allow the current foreground activity to override the brightness. 262 // Use -1 to disable. 263 private int mScreenBrightnessOverrideFromWindowManager = -1; 264 265 // The screen brightness setting override from the settings application 266 // to temporarily adjust the brightness until next updated, 267 // Use -1 to disable. 268 private int mTemporaryScreenBrightnessSettingOverride = -1; 269 270 // The screen brightness adjustment setting override from the settings 271 // application to temporarily adjust the auto-brightness adjustment factor 272 // until next updated, in the range -1..1. 273 // Use NaN to disable. 274 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 275 276 private native void nativeInit(); 277 private static native void nativeShutdown(); 278 private static native void nativeReboot(String reason) throws IOException; 279 280 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright); 281 private static native void nativeAcquireSuspendBlocker(String name); 282 private static native void nativeReleaseSuspendBlocker(String name); 283 284 static native void nativeSetScreenState(boolean on); 285 286 public PowerManagerService() { 287 synchronized (mLock) { 288 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService"); 289 mWakeLockSuspendBlocker.acquire(); 290 mHoldingWakeLockSuspendBlocker = true; 291 mWakefulness = WAKEFULNESS_AWAKE; 292 } 293 294 nativeInit(); 295 } 296 297 /** 298 * Initialize the power manager. 299 * Must be called before any other functions within the power manager are called. 300 */ 301 public void init(Context context, LightsService ls, 302 ActivityManagerService am, BatteryService bs, IBatteryStats bss, 303 DisplayManagerService dm) { 304 mContext = context; 305 mLightsService = ls; 306 mBatteryService = bs; 307 mBatteryStats = bss; 308 mHandlerThread = new HandlerThread(TAG); 309 mHandlerThread.start(); 310 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 311 312 Watchdog.getInstance().addMonitor(this); 313 } 314 315 public void setPolicy(WindowManagerPolicy policy) { 316 synchronized (mLock) { 317 mPolicy = policy; 318 } 319 } 320 321 public void systemReady() { 322 synchronized (mLock) { 323 mSystemReady = true; 324 325 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 326 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 327 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 328 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 329 330 mNotifier = new Notifier(mHandler.getLooper(), mContext, mBatteryStats, 331 createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 332 mPolicy, mScreenOnListener); 333 mDisplayPowerController = new DisplayPowerController(mHandler.getLooper(), 334 mContext, mNotifier, mLightsService, 335 createSuspendBlockerLocked("PowerManagerService.Display"), 336 mDisplayPowerControllerCallbacks, mHandler); 337 338 mSettingsObserver = new SettingsObserver(mHandler); 339 mAttentionLight = mLightsService.getLight(LightsService.LIGHT_ID_ATTENTION); 340 341 // Register for broadcasts from other components of the system. 342 IntentFilter filter = new IntentFilter(); 343 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 344 mContext.registerReceiver(new BatteryReceiver(), filter); 345 346 filter = new IntentFilter(); 347 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 348 mContext.registerReceiver(new BootCompletedReceiver(), filter); 349 350 filter = new IntentFilter(); 351 filter.addAction(Intent.ACTION_DOCK_EVENT); 352 mContext.registerReceiver(new DockReceiver(), filter); 353 354 // Register for settings changes. 355 final ContentResolver resolver = mContext.getContentResolver(); 356 resolver.registerContentObserver(Settings.Secure.getUriFor( 357 Settings.Secure.SCREENSAVER_ENABLED), false, mSettingsObserver); 358 resolver.registerContentObserver(Settings.System.getUriFor( 359 Settings.System.SCREEN_OFF_TIMEOUT), false, mSettingsObserver); 360 resolver.registerContentObserver(Settings.System.getUriFor( 361 Settings.System.STAY_ON_WHILE_PLUGGED_IN), false, mSettingsObserver); 362 resolver.registerContentObserver(Settings.System.getUriFor( 363 Settings.System.SCREEN_BRIGHTNESS), false, mSettingsObserver); 364 resolver.registerContentObserver(Settings.System.getUriFor( 365 Settings.System.SCREEN_BRIGHTNESS_MODE), false, mSettingsObserver); 366 367 // Go. 368 readConfigurationLocked(); 369 updateSettingsLocked(); 370 mDirty |= DIRTY_BATTERY_STATE; 371 updatePowerStateLocked(); 372 } 373 } 374 375 private void readConfigurationLocked() { 376 final Resources resources = mContext.getResources(); 377 378 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 379 com.android.internal.R.bool.config_unplugTurnsOnScreen); 380 mDreamsSupportedConfig = resources.getBoolean( 381 com.android.internal.R.bool.config_enableDreams); 382 } 383 384 private void updateSettingsLocked() { 385 final ContentResolver resolver = mContext.getContentResolver(); 386 387 mDreamsEnabledSetting = (Settings.Secure.getInt(resolver, 388 Settings.Secure.SCREENSAVER_ENABLED, 0) != 0); 389 mScreenOffTimeoutSetting = Settings.System.getInt(resolver, 390 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT); 391 mStayOnWhilePluggedInSetting = Settings.System.getInt(resolver, 392 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 393 BatteryManager.BATTERY_PLUGGED_AC); 394 395 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 396 mScreenBrightnessSetting = Settings.System.getInt(resolver, 397 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault); 398 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 399 mTemporaryScreenBrightnessSettingOverride = -1; 400 } 401 402 final float oldScreenAutoBrightnessAdjustmentSetting = 403 mScreenAutoBrightnessAdjustmentSetting; 404 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloat(resolver, 405 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f); 406 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 407 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = -1; 408 } 409 410 mScreenBrightnessModeSetting = Settings.System.getInt(resolver, 411 Settings.System.SCREEN_BRIGHTNESS_MODE, 412 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); 413 414 mDirty |= DIRTY_SETTINGS; 415 } 416 417 private void handleSettingsChangedLocked() { 418 updateSettingsLocked(); 419 updatePowerStateLocked(); 420 } 421 422 @Override // Binder call 423 public void acquireWakeLock(IBinder lock, int flags, String tag, WorkSource ws) { 424 if (lock == null) { 425 throw new IllegalArgumentException("lock must not be null"); 426 } 427 PowerManager.validateWakeLockParameters(flags, tag); 428 429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 430 if (ws != null && ws.size() != 0) { 431 mContext.enforceCallingOrSelfPermission( 432 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 433 } else { 434 ws = null; 435 } 436 437 final int uid = Binder.getCallingUid(); 438 final int pid = Binder.getCallingPid(); 439 final long ident = Binder.clearCallingIdentity(); 440 try { 441 acquireWakeLockInternal(lock, flags, tag, ws, uid, pid); 442 } finally { 443 Binder.restoreCallingIdentity(ident); 444 } 445 } 446 447 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, WorkSource ws, 448 int uid, int pid) { 449 synchronized (mLock) { 450 if (DEBUG_SPEW) { 451 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 452 + ", flags=0x" + Integer.toHexString(flags) 453 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 454 } 455 456 WakeLock wakeLock; 457 int index = findWakeLockIndexLocked(lock); 458 if (index >= 0) { 459 wakeLock = mWakeLocks.get(index); 460 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 461 // Update existing wake lock. This shouldn't happen but is harmless. 462 notifyWakeLockReleasedLocked(wakeLock); 463 wakeLock.updateProperties(flags, tag, ws, uid, pid); 464 notifyWakeLockAcquiredLocked(wakeLock); 465 } 466 } else { 467 wakeLock = new WakeLock(lock, flags, tag, ws, uid, pid); 468 try { 469 lock.linkToDeath(wakeLock, 0); 470 } catch (RemoteException ex) { 471 throw new IllegalArgumentException("Wake lock is already dead."); 472 } 473 notifyWakeLockAcquiredLocked(wakeLock); 474 mWakeLocks.add(wakeLock); 475 } 476 477 applyWakeLockFlagsOnAcquireLocked(wakeLock); 478 mDirty |= DIRTY_WAKE_LOCKS; 479 updatePowerStateLocked(); 480 } 481 } 482 483 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) { 484 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 485 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 486 } 487 } 488 489 @Override // Binder call 490 public void releaseWakeLock(IBinder lock, int flags) { 491 if (lock == null) { 492 throw new IllegalArgumentException("lock must not be null"); 493 } 494 495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 496 497 final long ident = Binder.clearCallingIdentity(); 498 try { 499 releaseWakeLockInternal(lock, flags); 500 } finally { 501 Binder.restoreCallingIdentity(ident); 502 } 503 } 504 505 private void releaseWakeLockInternal(IBinder lock, int flags) { 506 synchronized (mLock) { 507 if (DEBUG_SPEW) { 508 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 509 + ", flags=0x" + Integer.toHexString(flags)); 510 } 511 512 int index = findWakeLockIndexLocked(lock); 513 if (index < 0) { 514 return; 515 } 516 517 WakeLock wakeLock = mWakeLocks.get(index); 518 mWakeLocks.remove(index); 519 notifyWakeLockReleasedLocked(wakeLock); 520 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 521 522 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) { 523 mRequestWaitForNegativeProximity = true; 524 } 525 526 applyWakeLockFlagsOnReleaseLocked(wakeLock); 527 mDirty |= DIRTY_WAKE_LOCKS; 528 updatePowerStateLocked(); 529 } 530 } 531 532 private void handleWakeLockDeath(WakeLock wakeLock) { 533 synchronized (mLock) { 534 if (DEBUG_SPEW) { 535 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)); 536 } 537 538 int index = mWakeLocks.indexOf(wakeLock); 539 if (index < 0) { 540 return; 541 } 542 543 mWakeLocks.remove(index); 544 notifyWakeLockReleasedLocked(wakeLock); 545 546 applyWakeLockFlagsOnReleaseLocked(wakeLock); 547 mDirty |= DIRTY_WAKE_LOCKS; 548 updatePowerStateLocked(); 549 } 550 } 551 552 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 553 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 554 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 555 PowerManager.USER_ACTIVITY_EVENT_OTHER, 556 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 557 wakeLock.mOwnerUid); 558 } 559 } 560 561 @Override // Binder call 562 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) { 563 if (lock == null) { 564 throw new IllegalArgumentException("lock must not be null"); 565 } 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 long ident = Binder.clearCallingIdentity(); 576 try { 577 updateWakeLockWorkSourceInternal(lock, ws); 578 } finally { 579 Binder.restoreCallingIdentity(ident); 580 } 581 } 582 583 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws) { 584 synchronized (mLock) { 585 int index = findWakeLockIndexLocked(lock); 586 if (index < 0) { 587 throw new IllegalArgumentException("Wake lock not active"); 588 } 589 590 WakeLock wakeLock = mWakeLocks.get(index); 591 if (!wakeLock.hasSameWorkSource(ws)) { 592 notifyWakeLockReleasedLocked(wakeLock); 593 wakeLock.updateWorkSource(ws); 594 notifyWakeLockAcquiredLocked(wakeLock); 595 } 596 } 597 } 598 599 private int findWakeLockIndexLocked(IBinder lock) { 600 final int count = mWakeLocks.size(); 601 for (int i = 0; i < count; i++) { 602 if (mWakeLocks.get(i).mLock == lock) { 603 return i; 604 } 605 } 606 return -1; 607 } 608 609 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 610 if (mSystemReady) { 611 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, 612 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 613 } 614 } 615 616 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 617 if (mSystemReady) { 618 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 619 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 620 } 621 } 622 623 @Override // Binder call 624 public boolean isWakeLockLevelSupported(int level) { 625 final long ident = Binder.clearCallingIdentity(); 626 try { 627 return isWakeLockLevelSupportedInternal(level); 628 } finally { 629 Binder.restoreCallingIdentity(ident); 630 } 631 } 632 633 private boolean isWakeLockLevelSupportedInternal(int level) { 634 synchronized (mLock) { 635 switch (level) { 636 case PowerManager.PARTIAL_WAKE_LOCK: 637 case PowerManager.SCREEN_DIM_WAKE_LOCK: 638 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 639 case PowerManager.FULL_WAKE_LOCK: 640 return true; 641 642 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 643 return mSystemReady && mDisplayPowerController.isProximitySensorAvailable(); 644 645 default: 646 return false; 647 } 648 } 649 } 650 651 @Override // Binder call 652 public void userActivity(long eventTime, int event, int flags) { 653 if (eventTime > SystemClock.uptimeMillis()) { 654 throw new IllegalArgumentException("event time must not be in the future"); 655 } 656 657 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 658 659 final int uid = Binder.getCallingUid(); 660 final long ident = Binder.clearCallingIdentity(); 661 try { 662 userActivityInternal(eventTime, event, flags, uid); 663 } finally { 664 Binder.restoreCallingIdentity(ident); 665 } 666 } 667 668 // Called from native code. 669 private void userActivityFromNative(long eventTime, int event, int flags) { 670 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 671 } 672 673 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 674 synchronized (mLock) { 675 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 676 updatePowerStateLocked(); 677 } 678 } 679 } 680 681 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 682 if (DEBUG_SPEW) { 683 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 684 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 685 + ", uid=" + uid); 686 } 687 688 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 689 || mWakefulness == WAKEFULNESS_ASLEEP || !mBootCompleted || !mSystemReady) { 690 return false; 691 } 692 693 mNotifier.onUserActivity(event, uid); 694 695 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 696 if (eventTime > mLastUserActivityTimeNoChangeLights 697 && eventTime > mLastUserActivityTime) { 698 mLastUserActivityTimeNoChangeLights = eventTime; 699 mDirty |= DIRTY_USER_ACTIVITY; 700 return true; 701 } 702 } else { 703 if (eventTime > mLastUserActivityTime) { 704 mLastUserActivityTime = eventTime; 705 mDirty |= DIRTY_USER_ACTIVITY; 706 return true; 707 } 708 } 709 return false; 710 } 711 712 @Override // Binder call 713 public void wakeUp(long eventTime) { 714 if (eventTime > SystemClock.uptimeMillis()) { 715 throw new IllegalArgumentException("event time must not be in the future"); 716 } 717 718 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 719 720 final long ident = Binder.clearCallingIdentity(); 721 try { 722 wakeUpInternal(eventTime); 723 } finally { 724 Binder.restoreCallingIdentity(ident); 725 } 726 } 727 728 // Called from native code. 729 private void wakeUpFromNative(long eventTime) { 730 wakeUpInternal(eventTime); 731 } 732 733 private void wakeUpInternal(long eventTime) { 734 synchronized (mLock) { 735 if (wakeUpNoUpdateLocked(eventTime)) { 736 updatePowerStateLocked(); 737 } 738 } 739 } 740 741 private boolean wakeUpNoUpdateLocked(long eventTime) { 742 if (DEBUG_SPEW) { 743 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime); 744 } 745 746 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 747 || !mBootCompleted || !mSystemReady) { 748 return false; 749 } 750 751 switch (mWakefulness) { 752 case WAKEFULNESS_ASLEEP: 753 Slog.i(TAG, "Waking up from sleep..."); 754 mNotifier.onWakeUpStarted(); 755 mSendWakeUpFinishedNotificationWhenReady = true; 756 mSendGoToSleepFinishedNotificationWhenReady = false; 757 break; 758 case WAKEFULNESS_DREAMING: 759 Slog.i(TAG, "Waking up from dream..."); 760 break; 761 case WAKEFULNESS_NAPPING: 762 Slog.i(TAG, "Waking up from nap..."); 763 break; 764 } 765 766 mLastWakeTime = eventTime; 767 mWakefulness = WAKEFULNESS_AWAKE; 768 mDirty |= DIRTY_WAKEFULNESS; 769 770 userActivityNoUpdateLocked( 771 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 772 return true; 773 } 774 775 @Override // Binder call 776 public void goToSleep(long eventTime, int reason) { 777 if (eventTime > SystemClock.uptimeMillis()) { 778 throw new IllegalArgumentException("event time must not be in the future"); 779 } 780 781 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 782 783 final long ident = Binder.clearCallingIdentity(); 784 try { 785 goToSleepInternal(eventTime, reason); 786 } finally { 787 Binder.restoreCallingIdentity(ident); 788 } 789 } 790 791 // Called from native code. 792 private void goToSleepFromNative(long eventTime, int reason) { 793 goToSleepInternal(eventTime, reason); 794 } 795 796 private void goToSleepInternal(long eventTime, int reason) { 797 synchronized (mLock) { 798 if (goToSleepNoUpdateLocked(eventTime, reason)) { 799 updatePowerStateLocked(); 800 } 801 } 802 } 803 804 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) { 805 if (DEBUG_SPEW) { 806 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason); 807 } 808 809 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 810 || !mBootCompleted || !mSystemReady) { 811 return false; 812 } 813 814 switch (reason) { 815 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 816 Slog.i(TAG, "Going to sleep due to device administration policy..."); 817 break; 818 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 819 Slog.i(TAG, "Going to sleep due to screen timeout..."); 820 break; 821 default: 822 Slog.i(TAG, "Going to sleep by user request..."); 823 reason = PowerManager.GO_TO_SLEEP_REASON_USER; 824 break; 825 } 826 827 mLastSleepTime = eventTime; 828 mDirty |= DIRTY_WAKEFULNESS; 829 mWakefulness = WAKEFULNESS_ASLEEP; 830 mNotifier.onGoToSleepStarted(reason); 831 mSendGoToSleepFinishedNotificationWhenReady = true; 832 mSendWakeUpFinishedNotificationWhenReady = false; 833 834 // Report the number of wake locks that will be cleared by going to sleep. 835 int numWakeLocksCleared = 0; 836 final int numWakeLocks = mWakeLocks.size(); 837 for (int i = 0; i < numWakeLocks; i++) { 838 final WakeLock wakeLock = mWakeLocks.get(i); 839 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 840 case PowerManager.FULL_WAKE_LOCK: 841 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 842 case PowerManager.SCREEN_DIM_WAKE_LOCK: 843 numWakeLocksCleared += 1; 844 break; 845 } 846 } 847 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 848 return true; 849 } 850 851 /** 852 * Updates the global power state based on dirty bits recorded in mDirty. 853 * 854 * This is the main function that performs power state transitions. 855 * We centralize them here so that we can recompute the power state completely 856 * each time something important changes, and ensure that we do it the same 857 * way each time. The point is to gather all of the transition logic here. 858 */ 859 private void updatePowerStateLocked() { 860 if (!mSystemReady || mDirty == 0) { 861 return; 862 } 863 864 // Phase 0: Basic state updates. 865 updateIsPoweredLocked(mDirty); 866 updateStayOnLocked(mDirty); 867 868 // Phase 1: Update wakefulness. 869 // Loop because the wake lock and user activity computations are influenced 870 // by changes in wakefulness. 871 final long now = SystemClock.uptimeMillis(); 872 int dirtyPhase2 = 0; 873 for (;;) { 874 int dirtyPhase1 = mDirty; 875 dirtyPhase2 |= dirtyPhase1; 876 mDirty = 0; 877 878 updateWakeLockSummaryLocked(dirtyPhase1); 879 updateUserActivitySummaryLocked(now, dirtyPhase1); 880 if (!updateWakefulnessLocked(dirtyPhase1)) { 881 break; 882 } 883 } 884 885 // Phase 2: Update dreams and display power state. 886 updateDreamLocked(dirtyPhase2); 887 updateDisplayPowerStateLocked(dirtyPhase2); 888 889 // Phase 3: Send notifications, if needed. 890 sendPendingNotificationsLocked(); 891 892 // Phase 4: Update suspend blocker. 893 // Because we might release the last suspend blocker here, we need to make sure 894 // we finished everything else first! 895 updateSuspendBlockerLocked(); 896 } 897 898 private void sendPendingNotificationsLocked() { 899 if (mDisplayReady) { 900 if (mSendWakeUpFinishedNotificationWhenReady) { 901 mSendWakeUpFinishedNotificationWhenReady = false; 902 mNotifier.onWakeUpFinished(); 903 } 904 if (mSendGoToSleepFinishedNotificationWhenReady) { 905 mSendGoToSleepFinishedNotificationWhenReady = false; 906 mNotifier.onGoToSleepFinished(); 907 } 908 } 909 } 910 911 /** 912 * Updates the value of mIsPowered. 913 * Sets DIRTY_IS_POWERED if a change occurred. 914 */ 915 private void updateIsPoweredLocked(int dirty) { 916 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 917 boolean wasPowered = mIsPowered; 918 mIsPowered = mBatteryService.isPowered(); 919 920 if (wasPowered != mIsPowered) { 921 mDirty |= DIRTY_IS_POWERED; 922 923 // Treat plugging and unplugging the devices as a user activity. 924 // Users find it disconcerting when they plug or unplug the device 925 // and it shuts off right away. 926 // Some devices also wake the device when plugged or unplugged because 927 // they don't have a charging LED. 928 final long now = SystemClock.uptimeMillis(); 929 if (mWakeUpWhenPluggedOrUnpluggedConfig) { 930 wakeUpNoUpdateLocked(now); 931 } 932 userActivityNoUpdateLocked( 933 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 934 } 935 } 936 } 937 938 /** 939 * Updates the value of mStayOn. 940 * Sets DIRTY_STAY_ON if a change occurred. 941 */ 942 private void updateStayOnLocked(int dirty) { 943 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 944 if (mStayOnWhilePluggedInSetting != 0 945 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 946 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting); 947 } else { 948 mStayOn = false; 949 } 950 } 951 } 952 953 /** 954 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 955 * Note that most wake-locks are ignored when the system is asleep. 956 * 957 * This function must have no other side-effects. 958 */ 959 private void updateWakeLockSummaryLocked(int dirty) { 960 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 961 mWakeLockSummary = 0; 962 963 final int numWakeLocks = mWakeLocks.size(); 964 for (int i = 0; i < numWakeLocks; i++) { 965 final WakeLock wakeLock = mWakeLocks.get(i); 966 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 967 case PowerManager.PARTIAL_WAKE_LOCK: 968 mWakeLockSummary |= WAKE_LOCK_CPU; 969 break; 970 case PowerManager.FULL_WAKE_LOCK: 971 if (mWakefulness != WAKEFULNESS_ASLEEP) { 972 mWakeLockSummary |= WAKE_LOCK_CPU 973 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 974 } 975 break; 976 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 977 if (mWakefulness != WAKEFULNESS_ASLEEP) { 978 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT; 979 } 980 break; 981 case PowerManager.SCREEN_DIM_WAKE_LOCK: 982 if (mWakefulness != WAKEFULNESS_ASLEEP) { 983 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM; 984 } 985 break; 986 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 987 if (mWakefulness != WAKEFULNESS_ASLEEP) { 988 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_PROXIMITY_SCREEN_OFF; 989 } 990 break; 991 } 992 } 993 994 if (DEBUG_SPEW) { 995 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 996 + wakefulnessToString(mWakefulness) 997 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 998 } 999 } 1000 } 1001 1002 /** 1003 * Updates the value of mUserActivitySummary to summarize the user requested 1004 * state of the system such as whether the screen should be bright or dim. 1005 * Note that user activity is ignored when the system is asleep. 1006 * 1007 * This function must have no other side-effects. 1008 */ 1009 private void updateUserActivitySummaryLocked(long now, int dirty) { 1010 // Update the status of the user activity timeout timer. 1011 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1012 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1013 1014 long nextTimeout = 0; 1015 if (mWakefulness != WAKEFULNESS_ASLEEP) { 1016 final int screenOffTimeout = getScreenOffTimeoutLocked(); 1017 final int screenDimDuration = getScreenDimDurationLocked(); 1018 1019 mUserActivitySummary = 0; 1020 if (mLastUserActivityTime >= mLastWakeTime) { 1021 nextTimeout = mLastUserActivityTime 1022 + screenOffTimeout - screenDimDuration; 1023 if (now < nextTimeout) { 1024 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT; 1025 } else { 1026 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1027 if (now < nextTimeout) { 1028 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM; 1029 } 1030 } 1031 } 1032 if (mUserActivitySummary == 0 1033 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1034 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1035 if (now < nextTimeout 1036 && mDisplayPowerRequest.screenState 1037 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1038 mUserActivitySummary = mDisplayPowerRequest.screenState 1039 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ? 1040 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM; 1041 } 1042 } 1043 if (mUserActivitySummary != 0) { 1044 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1045 msg.setAsynchronous(true); 1046 mHandler.sendMessageAtTime(msg, nextTimeout); 1047 } 1048 } else { 1049 mUserActivitySummary = 0; 1050 } 1051 1052 if (DEBUG_SPEW) { 1053 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1054 + wakefulnessToString(mWakefulness) 1055 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1056 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1057 } 1058 } 1059 } 1060 1061 /** 1062 * Called when a user activity timeout has occurred. 1063 * Simply indicates that something about user activity has changed so that the new 1064 * state can be recomputed when the power state is updated. 1065 * 1066 * This function must have no other side-effects besides setting the dirty 1067 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1068 */ 1069 private void handleUserActivityTimeout() { // runs on handler thread 1070 synchronized (mLock) { 1071 if (DEBUG_SPEW) { 1072 Slog.d(TAG, "handleUserActivityTimeout"); 1073 } 1074 1075 mDirty |= DIRTY_USER_ACTIVITY; 1076 updatePowerStateLocked(); 1077 } 1078 } 1079 1080 private int getScreenOffTimeoutLocked() { 1081 int timeout = mScreenOffTimeoutSetting; 1082 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1083 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1084 } 1085 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT); 1086 } 1087 1088 private int getScreenDimDurationLocked() { 1089 return SCREEN_DIM_DURATION; 1090 } 1091 1092 /** 1093 * Updates the wakefulness of the device. 1094 * 1095 * This is the function that decides whether the device should start napping 1096 * based on the current wake locks and user activity state. It may modify mDirty 1097 * if the wakefulness changes. 1098 * 1099 * Returns true if the wakefulness changed and we need to restart power state calculation. 1100 */ 1101 private boolean updateWakefulnessLocked(int dirty) { 1102 boolean changed = false; 1103 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1104 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON)) != 0) { 1105 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1106 if (DEBUG_SPEW) { 1107 Slog.d(TAG, "updateWakefulnessLocked: Nap time..."); 1108 } 1109 mWakefulness = WAKEFULNESS_NAPPING; 1110 mDirty |= DIRTY_WAKEFULNESS; 1111 changed = true; 1112 } 1113 } 1114 return changed; 1115 } 1116 1117 // Also used when exiting a dream to determine whether we should go back 1118 // to being fully awake or else go to sleep for good. 1119 private boolean isItBedTimeYetLocked() { 1120 return mBootCompleted && !mStayOn 1121 && (mWakeLockSummary 1122 & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) == 0 1123 && (mUserActivitySummary 1124 & (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) == 0; 1125 } 1126 1127 /** 1128 * Determines whether to post a message to the sandman to update the dream state. 1129 */ 1130 private void updateDreamLocked(int dirty) { 1131 if ((dirty & (DIRTY_WAKEFULNESS | DIRTY_SETTINGS 1132 | DIRTY_IS_POWERED | DIRTY_STAY_ON)) != 0) { 1133 scheduleSandmanLocked(); 1134 } 1135 } 1136 1137 private void scheduleSandmanLocked() { 1138 if (!mSandmanScheduled) { 1139 mSandmanScheduled = true; 1140 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1141 msg.setAsynchronous(true); 1142 mHandler.sendMessage(msg); 1143 } 1144 } 1145 1146 /** 1147 * Called when the device enters or exits a napping or dreaming state. 1148 * 1149 * We do this asynchronously because we must call out of the power manager to start 1150 * the dream and we don't want to hold our lock while doing so. There is a risk that 1151 * the device will wake or go to sleep in the meantime so we have to handle that case. 1152 */ 1153 private void handleSandman() { // runs on handler thread 1154 // Handle preconditions. 1155 boolean startDreaming = false; 1156 synchronized (mLock) { 1157 mSandmanScheduled = false; 1158 1159 if (DEBUG_SPEW) { 1160 Log.d(TAG, "handleSandman: canDream=" + canDreamLocked() 1161 + ", mWakefulness=" + wakefulnessToString(mWakefulness)); 1162 } 1163 1164 if (canDreamLocked() && mWakefulness == WAKEFULNESS_NAPPING) { 1165 startDreaming = true; 1166 } 1167 } 1168 1169 // Get the dream manager, if needed. 1170 if (startDreaming && mDreamManager == null) { 1171 mDreamManager = IDreamManager.Stub.asInterface( 1172 ServiceManager.checkService("dreams")); 1173 if (mDreamManager == null) { 1174 Slog.w(TAG, "Unable to find IDreamManager."); 1175 } 1176 } 1177 1178 // Start dreaming if needed. 1179 // We only control the dream on the handler thread, so we don't need to worry about 1180 // concurrent attempts to start or stop the dream. 1181 boolean isDreaming = false; 1182 if (mDreamManager != null) { 1183 try { 1184 isDreaming = mDreamManager.isDreaming(); 1185 if (startDreaming && !isDreaming) { 1186 Slog.i(TAG, "Entering dreamland."); 1187 mDreamManager.dream(); 1188 isDreaming = mDreamManager.isDreaming(); 1189 if (!isDreaming) { 1190 Slog.i(TAG, "Could not enter dreamland. Sleep will be dreamless."); 1191 } 1192 } 1193 } catch (RemoteException ex) { 1194 } 1195 } 1196 1197 // Update dream state. 1198 // We might need to stop the dream again if the preconditions changed. 1199 boolean continueDreaming = false; 1200 synchronized (mLock) { 1201 if (isDreaming && canDreamLocked()) { 1202 if (mWakefulness == WAKEFULNESS_NAPPING) { 1203 mWakefulness = WAKEFULNESS_DREAMING; 1204 mDirty |= DIRTY_WAKEFULNESS; 1205 updatePowerStateLocked(); 1206 continueDreaming = true; 1207 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1208 continueDreaming = true; 1209 } 1210 } 1211 if (!continueDreaming) { 1212 handleDreamFinishedLocked(); 1213 } 1214 1215 // Allow the sandman to detect when the dream has ended. 1216 // FIXME: The DreamManagerService should tell us explicitly. 1217 if (mWakefulness == WAKEFULNESS_DREAMING 1218 || mWakefulness == WAKEFULNESS_NAPPING) { 1219 if (!mSandmanScheduled) { 1220 mSandmanScheduled = true; 1221 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1222 msg.setAsynchronous(true); 1223 mHandler.sendMessageDelayed(msg, 1000); 1224 } 1225 } 1226 } 1227 1228 // Stop dreaming if needed. 1229 // It's possible that something else changed to make us need to start the dream again. 1230 // If so, then the power manager will have posted another message to the handler 1231 // to take care of it later. 1232 if (mDreamManager != null) { 1233 try { 1234 if (!continueDreaming && isDreaming) { 1235 Slog.i(TAG, "Leaving dreamland."); 1236 mDreamManager.awaken(); 1237 } 1238 } catch (RemoteException ex) { 1239 } 1240 } 1241 } 1242 1243 /** 1244 * Returns true if the device is allowed to dream in its current state, 1245 * assuming there has been no recent user activity and no wake locks are held. 1246 */ 1247 private boolean canDreamLocked() { 1248 return mIsPowered && mDreamsSupportedConfig && mDreamsEnabledSetting; 1249 } 1250 1251 /** 1252 * Called when a dream is ending to figure out what to do next. 1253 */ 1254 private void handleDreamFinishedLocked() { 1255 if (mWakefulness == WAKEFULNESS_NAPPING 1256 || mWakefulness == WAKEFULNESS_DREAMING) { 1257 if (isItBedTimeYetLocked()) { 1258 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1259 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1260 updatePowerStateLocked(); 1261 } else { 1262 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 1263 updatePowerStateLocked(); 1264 } 1265 } 1266 } 1267 1268 1269 /** 1270 * Updates the display power state asynchronously. 1271 * When the update is finished, mDisplayReady will be set to true. The display 1272 * controller posts a message to tell us when the actual display power state 1273 * has been updated so we come back here to double-check and finish up. 1274 * 1275 * This function recalculates the display power state each time. 1276 */ 1277 private void updateDisplayPowerStateLocked(int dirty) { 1278 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1279 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1280 | DIRTY_SETTINGS)) != 0) { 1281 int newScreenState = getDesiredScreenPowerState(); 1282 if (newScreenState != mDisplayPowerRequest.screenState) { 1283 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF 1284 && mDisplayPowerRequest.screenState 1285 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1286 mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime(); 1287 } 1288 1289 mDisplayPowerRequest.screenState = newScreenState; 1290 nativeSetPowerState( 1291 newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF, 1292 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT); 1293 } 1294 1295 int screenBrightness = mScreenBrightnessSettingDefault; 1296 float screenAutoBrightnessAdjustment = 0.0f; 1297 boolean autoBrightness = (mScreenBrightnessModeSetting == 1298 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1299 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1300 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1301 autoBrightness = false; 1302 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1303 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1304 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1305 screenBrightness = mScreenBrightnessSetting; 1306 } 1307 if (autoBrightness) { 1308 screenBrightness = mScreenBrightnessSettingDefault; 1309 if (isValidAutoBrightnessAdjustment( 1310 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1311 screenAutoBrightnessAdjustment = 1312 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1313 } else if (isValidAutoBrightnessAdjustment( 1314 mScreenAutoBrightnessAdjustmentSetting)) { 1315 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1316 } 1317 } 1318 screenBrightness = Math.max(Math.min(screenBrightness, 1319 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1320 screenAutoBrightnessAdjustment = Math.max(Math.min( 1321 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1322 mDisplayPowerRequest.screenBrightness = screenBrightness; 1323 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1324 screenAutoBrightnessAdjustment; 1325 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1326 1327 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1328 1329 mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest, 1330 mRequestWaitForNegativeProximity); 1331 mRequestWaitForNegativeProximity = false; 1332 1333 if (DEBUG_SPEW) { 1334 Slog.d(TAG, "updateScreenStateLocked: displayReady=" + mDisplayReady 1335 + ", newScreenState=" + newScreenState 1336 + ", mWakefulness=" + mWakefulness 1337 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1338 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1339 + ", mBootCompleted=" + mBootCompleted); 1340 } 1341 } 1342 } 1343 1344 private static boolean isValidBrightness(int value) { 1345 return value >= 0 && value <= 255; 1346 } 1347 1348 private static boolean isValidAutoBrightnessAdjustment(float value) { 1349 return !Float.isNaN(value); 1350 } 1351 1352 private int getDesiredScreenPowerState() { 1353 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1354 return DisplayPowerRequest.SCREEN_STATE_OFF; 1355 } 1356 1357 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1358 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1359 || !mBootCompleted) { 1360 return DisplayPowerRequest.SCREEN_STATE_BRIGHT; 1361 } 1362 1363 return DisplayPowerRequest.SCREEN_STATE_DIM; 1364 } 1365 1366 private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks = 1367 new DisplayPowerController.Callbacks() { 1368 @Override 1369 public void onStateChanged() { 1370 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1371 updatePowerStateLocked(); 1372 } 1373 1374 @Override 1375 public void onProximityNegative() { 1376 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1377 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1378 updatePowerStateLocked(); 1379 } 1380 }; 1381 1382 private boolean shouldUseProximitySensorLocked() { 1383 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 1384 } 1385 1386 /** 1387 * Updates the suspend blocker that keeps the CPU alive. 1388 * 1389 * This function must have no other side-effects. 1390 */ 1391 private void updateSuspendBlockerLocked() { 1392 boolean wantCpu = isCpuNeededLocked(); 1393 if (wantCpu != mHoldingWakeLockSuspendBlocker) { 1394 mHoldingWakeLockSuspendBlocker = wantCpu; 1395 if (wantCpu) { 1396 if (DEBUG) { 1397 Slog.d(TAG, "updateSuspendBlockerLocked: Acquiring suspend blocker."); 1398 } 1399 mWakeLockSuspendBlocker.acquire(); 1400 } else { 1401 if (DEBUG) { 1402 Slog.d(TAG, "updateSuspendBlockerLocked: Releasing suspend blocker."); 1403 } 1404 mWakeLockSuspendBlocker.release(); 1405 } 1406 } 1407 } 1408 1409 private boolean isCpuNeededLocked() { 1410 return !mBootCompleted 1411 || mWakeLockSummary != 0 1412 || mUserActivitySummary != 0 1413 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF 1414 || !mDisplayReady; 1415 } 1416 1417 @Override // Binder call 1418 public boolean isScreenOn() { 1419 final long ident = Binder.clearCallingIdentity(); 1420 try { 1421 return isScreenOnInternal(); 1422 } finally { 1423 Binder.restoreCallingIdentity(ident); 1424 } 1425 } 1426 1427 private boolean isScreenOnInternal() { 1428 synchronized (mLock) { 1429 return !mSystemReady 1430 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF; 1431 } 1432 } 1433 1434 private void handleBatteryStateChangedLocked() { 1435 mDirty |= DIRTY_BATTERY_STATE; 1436 updatePowerStateLocked(); 1437 } 1438 1439 private void handleBootCompletedLocked() { 1440 final long now = SystemClock.uptimeMillis(); 1441 mBootCompleted = true; 1442 mDirty |= DIRTY_BOOT_COMPLETED; 1443 userActivityNoUpdateLocked( 1444 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1445 updatePowerStateLocked(); 1446 } 1447 1448 private void handleDockStateChangedLocked(int dockState) { 1449 // TODO 1450 } 1451 1452 /** 1453 * Reboot the device immediately, passing 'reason' (may be null) 1454 * to the underlying __reboot system call. Should not return. 1455 */ 1456 @Override // Binder call 1457 public void reboot(String reason) { 1458 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1459 1460 final long ident = Binder.clearCallingIdentity(); 1461 try { 1462 rebootInternal(reason); 1463 } finally { 1464 Binder.restoreCallingIdentity(ident); 1465 } 1466 } 1467 1468 private void rebootInternal(final String reason) { 1469 if (mHandler == null || !mSystemReady) { 1470 throw new IllegalStateException("Too early to call reboot()"); 1471 } 1472 1473 Runnable runnable = new Runnable() { 1474 public void run() { 1475 synchronized (this) { 1476 ShutdownThread.reboot(mContext, reason, false); 1477 } 1478 } 1479 }; 1480 1481 // ShutdownThread must run on a looper capable of displaying the UI. 1482 Message msg = Message.obtain(mHandler, runnable); 1483 msg.setAsynchronous(true); 1484 mHandler.sendMessage(msg); 1485 1486 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 1487 synchronized (runnable) { 1488 while (true) { 1489 try { 1490 runnable.wait(); 1491 } catch (InterruptedException e) { 1492 } 1493 } 1494 } 1495 } 1496 1497 /** 1498 * Crash the runtime (causing a complete restart of the Android framework). 1499 * Requires REBOOT permission. Mostly for testing. Should not return. 1500 */ 1501 @Override // Binder call 1502 public void crash(String message) { 1503 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1504 1505 final long ident = Binder.clearCallingIdentity(); 1506 try { 1507 crashInternal(message); 1508 } finally { 1509 Binder.restoreCallingIdentity(ident); 1510 } 1511 } 1512 1513 private void crashInternal(final String message) { 1514 Thread t = new Thread("PowerManagerService.crash()") { 1515 public void run() { 1516 throw new RuntimeException(message); 1517 } 1518 }; 1519 try { 1520 t.start(); 1521 t.join(); 1522 } catch (InterruptedException e) { 1523 Log.wtf(TAG, e); 1524 } 1525 } 1526 1527 @Override // Binder call 1528 public void clearUserActivityTimeout(long now, long timeout) { 1529 // TODO Auto-generated method stub 1530 // Only used by phone app, delete this 1531 } 1532 1533 @Override // Binder call 1534 public void setPokeLock(int pokey, IBinder lock, String tag) { 1535 // TODO Auto-generated method stub 1536 // Only used by phone app, delete this 1537 } 1538 1539 /** 1540 * Set the setting that determines whether the device stays on when plugged in. 1541 * The argument is a bit string, with each bit specifying a power source that, 1542 * when the device is connected to that source, causes the device to stay on. 1543 * See {@link android.os.BatteryManager} for the list of power sources that 1544 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 1545 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 1546 * 1547 * Used by "adb shell svc power stayon ..." 1548 * 1549 * @param val an {@code int} containing the bits that specify which power sources 1550 * should cause the device to stay on. 1551 */ 1552 @Override // Binder call 1553 public void setStayOnSetting(int val) { 1554 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null); 1555 1556 final long ident = Binder.clearCallingIdentity(); 1557 try { 1558 setStayOnSettingInternal(val); 1559 } finally { 1560 Binder.restoreCallingIdentity(ident); 1561 } 1562 } 1563 1564 private void setStayOnSettingInternal(int val) { 1565 Settings.System.putInt(mContext.getContentResolver(), 1566 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val); 1567 } 1568 1569 /** 1570 * Used by device administration to set the maximum screen off timeout. 1571 * 1572 * This method must only be called by the device administration policy manager. 1573 */ 1574 @Override // Binder call 1575 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 1576 final long ident = Binder.clearCallingIdentity(); 1577 try { 1578 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 1579 } finally { 1580 Binder.restoreCallingIdentity(ident); 1581 } 1582 } 1583 1584 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 1585 synchronized (mLock) { 1586 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 1587 mDirty |= DIRTY_SETTINGS; 1588 updatePowerStateLocked(); 1589 } 1590 } 1591 1592 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 1593 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 1594 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 1595 } 1596 1597 @Override // Binder call 1598 public void preventScreenOn(boolean prevent) { 1599 // TODO Auto-generated method stub 1600 // Only used by phone app, delete this 1601 } 1602 1603 /** 1604 * Used by the phone application to make the attention LED flash when ringing. 1605 */ 1606 @Override // Binder call 1607 public void setAttentionLight(boolean on, int color) { 1608 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1609 1610 final long ident = Binder.clearCallingIdentity(); 1611 try { 1612 setAttentionLightInternal(on, color); 1613 } finally { 1614 Binder.restoreCallingIdentity(ident); 1615 } 1616 } 1617 1618 private void setAttentionLightInternal(boolean on, int color) { 1619 LightsService.Light light; 1620 synchronized (mLock) { 1621 if (!mSystemReady) { 1622 return; 1623 } 1624 light = mAttentionLight; 1625 } 1626 1627 // Control light outside of lock. 1628 light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 1629 } 1630 1631 /** 1632 * Used by the Watchdog. 1633 */ 1634 public long timeSinceScreenWasLastOn() { 1635 synchronized (mLock) { 1636 if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) { 1637 return 0; 1638 } 1639 return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime; 1640 } 1641 } 1642 1643 /** 1644 * Used by the window manager to override the screen brightness based on the 1645 * current foreground activity. 1646 * 1647 * This method must only be called by the window manager. 1648 * 1649 * @param brightness The overridden brightness, or -1 to disable the override. 1650 */ 1651 public void setScreenBrightnessOverrideFromWindowManager(int brightness) { 1652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1653 1654 final long ident = Binder.clearCallingIdentity(); 1655 try { 1656 setScreenBrightnessOverrideFromWindowManagerInternal(brightness); 1657 } finally { 1658 Binder.restoreCallingIdentity(ident); 1659 } 1660 } 1661 1662 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 1663 synchronized (mLock) { 1664 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 1665 mScreenBrightnessOverrideFromWindowManager = brightness; 1666 mDirty |= DIRTY_SETTINGS; 1667 updatePowerStateLocked(); 1668 } 1669 } 1670 } 1671 1672 /** 1673 * Used by the window manager to override the button brightness based on the 1674 * current foreground activity. 1675 * 1676 * This method must only be called by the window manager. 1677 * 1678 * @param brightness The overridden brightness, or -1 to disable the override. 1679 */ 1680 public void setButtonBrightnessOverrideFromWindowManager(int brightness) { 1681 // Do nothing. 1682 // Button lights are not currently supported in the new implementation. 1683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1684 } 1685 1686 /** 1687 * Used by the settings application and brightness control widgets to 1688 * temporarily override the current screen brightness setting so that the 1689 * user can observe the effect of an intended settings change without applying 1690 * it immediately. 1691 * 1692 * The override will be canceled when the setting value is next updated. 1693 * 1694 * @param brightness The overridden brightness. 1695 * 1696 * @see Settings.System#SCREEN_BRIGHTNESS 1697 */ 1698 @Override // Binder call 1699 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 1700 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1701 1702 final long ident = Binder.clearCallingIdentity(); 1703 try { 1704 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 1705 } finally { 1706 Binder.restoreCallingIdentity(ident); 1707 } 1708 } 1709 1710 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 1711 synchronized (mLock) { 1712 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 1713 mTemporaryScreenBrightnessSettingOverride = brightness; 1714 mDirty |= DIRTY_SETTINGS; 1715 updatePowerStateLocked(); 1716 } 1717 } 1718 } 1719 1720 /** 1721 * Used by the settings application and brightness control widgets to 1722 * temporarily override the current screen auto-brightness adjustment setting so that the 1723 * user can observe the effect of an intended settings change without applying 1724 * it immediately. 1725 * 1726 * The override will be canceled when the setting value is next updated. 1727 * 1728 * @param adj The overridden brightness, or Float.NaN to disable the override. 1729 * 1730 * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 1731 */ 1732 @Override // Binder call 1733 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 1734 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1735 1736 final long ident = Binder.clearCallingIdentity(); 1737 try { 1738 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 1739 } finally { 1740 Binder.restoreCallingIdentity(ident); 1741 } 1742 } 1743 1744 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 1745 synchronized (mLock) { 1746 // Note: This condition handles NaN because NaN is not equal to any other 1747 // value, including itself. 1748 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 1749 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 1750 mDirty |= DIRTY_SETTINGS; 1751 updatePowerStateLocked(); 1752 } 1753 } 1754 } 1755 1756 /** 1757 * Low-level function turn the device off immediately, without trying 1758 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 1759 */ 1760 public static void lowLevelShutdown() { 1761 nativeShutdown(); 1762 } 1763 1764 /** 1765 * Low-level function to reboot the device. 1766 * 1767 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 1768 * @throws IOException if reboot fails for some reason (eg, lack of 1769 * permission) 1770 */ 1771 public static void lowLevelReboot(String reason) throws IOException { 1772 nativeReboot(reason); 1773 } 1774 1775 @Override // Watchdog.Monitor implementation 1776 public void monitor() { 1777 // Grab and release lock for watchdog monitor to detect deadlocks. 1778 synchronized (mLock) { 1779 } 1780 } 1781 1782 @Override // Binder call 1783 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1784 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 1785 != PackageManager.PERMISSION_GRANTED) { 1786 pw.println("Permission Denial: can't dump PowerManager from from pid=" 1787 + Binder.getCallingPid() 1788 + ", uid=" + Binder.getCallingUid()); 1789 return; 1790 } 1791 1792 pw.println("POWER MANAGER (dumpsys power)\n"); 1793 1794 final DisplayPowerController dpc; 1795 synchronized (mLock) { 1796 pw.println("Power Manager State:"); 1797 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 1798 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness)); 1799 pw.println(" mIsPowered=" + mIsPowered); 1800 pw.println(" mStayOn=" + mStayOn); 1801 pw.println(" mBootCompleted=" + mBootCompleted); 1802 pw.println(" mSystemReady=" + mSystemReady); 1803 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1804 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 1805 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 1806 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 1807 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 1808 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 1809 pw.println(" mSendWakeUpFinishedNotificationWhenReady=" 1810 + mSendWakeUpFinishedNotificationWhenReady); 1811 pw.println(" mSendGoToSleepFinishedNotificationWhenReady=" 1812 + mSendGoToSleepFinishedNotificationWhenReady); 1813 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 1814 pw.println(" mLastUserActivityTimeNoChangeLights=" 1815 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 1816 pw.println(" mDisplayReady=" + mDisplayReady); 1817 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 1818 1819 pw.println(); 1820 pw.println("Settings and Configuration:"); 1821 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 1822 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 1823 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 1824 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 1825 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 1826 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 1827 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 1828 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 1829 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 1830 + mScreenAutoBrightnessAdjustmentSetting); 1831 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 1832 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 1833 + mScreenBrightnessOverrideFromWindowManager); 1834 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 1835 + mTemporaryScreenBrightnessSettingOverride); 1836 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 1837 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 1838 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 1839 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 1840 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 1841 1842 pw.println(); 1843 pw.println("Wake Locks: size=" + mWakeLocks.size()); 1844 for (WakeLock wl : mWakeLocks) { 1845 pw.println(" " + wl); 1846 } 1847 1848 pw.println(); 1849 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 1850 for (SuspendBlocker sb : mSuspendBlockers) { 1851 pw.println(" " + sb); 1852 } 1853 1854 dpc = mDisplayPowerController; 1855 } 1856 1857 if (dpc != null) { 1858 dpc.dump(pw); 1859 } 1860 } 1861 1862 private SuspendBlocker createSuspendBlockerLocked(String name) { 1863 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 1864 mSuspendBlockers.add(suspendBlocker); 1865 return suspendBlocker; 1866 } 1867 1868 private static String wakefulnessToString(int wakefulness) { 1869 switch (wakefulness) { 1870 case WAKEFULNESS_ASLEEP: 1871 return "Asleep"; 1872 case WAKEFULNESS_AWAKE: 1873 return "Awake"; 1874 case WAKEFULNESS_DREAMING: 1875 return "Dreaming"; 1876 case WAKEFULNESS_NAPPING: 1877 return "Napping"; 1878 default: 1879 return Integer.toString(wakefulness); 1880 } 1881 } 1882 1883 private static WorkSource copyWorkSource(WorkSource workSource) { 1884 return workSource != null ? new WorkSource(workSource) : null; 1885 } 1886 1887 private final class BatteryReceiver extends BroadcastReceiver { 1888 @Override 1889 public void onReceive(Context context, Intent intent) { 1890 synchronized (mLock) { 1891 handleBatteryStateChangedLocked(); 1892 } 1893 } 1894 } 1895 1896 private final class BootCompletedReceiver extends BroadcastReceiver { 1897 @Override 1898 public void onReceive(Context context, Intent intent) { 1899 synchronized (mLock) { 1900 handleBootCompletedLocked(); 1901 } 1902 } 1903 } 1904 1905 private final class DockReceiver extends BroadcastReceiver { 1906 @Override 1907 public void onReceive(Context context, Intent intent) { 1908 synchronized (mLock) { 1909 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 1910 Intent.EXTRA_DOCK_STATE_UNDOCKED); 1911 handleDockStateChangedLocked(dockState); 1912 } 1913 } 1914 } 1915 1916 private final class SettingsObserver extends ContentObserver { 1917 public SettingsObserver(Handler handler) { 1918 super(handler); 1919 } 1920 1921 @Override 1922 public void onChange(boolean selfChange, Uri uri) { 1923 synchronized (mLock) { 1924 handleSettingsChangedLocked(); 1925 } 1926 } 1927 } 1928 1929 private final WindowManagerPolicy.ScreenOnListener mScreenOnListener = 1930 new WindowManagerPolicy.ScreenOnListener() { 1931 @Override 1932 public void onScreenOn() { 1933 } 1934 }; 1935 1936 /** 1937 * Handler for asynchronous operations performed by the power manager. 1938 */ 1939 private final class PowerManagerHandler extends Handler { 1940 public PowerManagerHandler(Looper looper) { 1941 super(looper); 1942 } 1943 1944 @Override 1945 public void handleMessage(Message msg) { 1946 switch (msg.what) { 1947 case MSG_USER_ACTIVITY_TIMEOUT: 1948 handleUserActivityTimeout(); 1949 break; 1950 case MSG_SANDMAN: 1951 handleSandman(); 1952 break; 1953 } 1954 } 1955 } 1956 1957 /** 1958 * Represents a wake lock that has been acquired by an application. 1959 */ 1960 private final class WakeLock implements IBinder.DeathRecipient { 1961 public final IBinder mLock; 1962 public int mFlags; 1963 public String mTag; 1964 public WorkSource mWorkSource; 1965 public int mOwnerUid; 1966 public int mOwnerPid; 1967 1968 public WakeLock(IBinder lock, int flags, String tag, WorkSource workSource, 1969 int ownerUid, int ownerPid) { 1970 mLock = lock; 1971 mFlags = flags; 1972 mTag = tag; 1973 mWorkSource = copyWorkSource(workSource); 1974 mOwnerUid = ownerUid; 1975 mOwnerPid = ownerPid; 1976 } 1977 1978 @Override 1979 public void binderDied() { 1980 PowerManagerService.this.handleWakeLockDeath(this); 1981 } 1982 1983 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 1984 int ownerUid, int ownerPid) { 1985 return mFlags == flags 1986 && mTag.equals(tag) 1987 && hasSameWorkSource(workSource) 1988 && mOwnerUid == ownerUid 1989 && mOwnerPid == ownerPid; 1990 } 1991 1992 public void updateProperties(int flags, String tag, WorkSource workSource, 1993 int ownerUid, int ownerPid) { 1994 mFlags = flags; 1995 mTag = tag; 1996 updateWorkSource(workSource); 1997 mOwnerUid = ownerUid; 1998 mOwnerPid = ownerPid; 1999 } 2000 2001 public boolean hasSameWorkSource(WorkSource workSource) { 2002 return Objects.equal(mWorkSource, workSource); 2003 } 2004 2005 public void updateWorkSource(WorkSource workSource) { 2006 mWorkSource = copyWorkSource(workSource); 2007 } 2008 2009 @Override 2010 public String toString() { 2011 return getLockLevelString() 2012 + " '" + mTag + "'" + getLockFlagsString() 2013 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2014 } 2015 2016 private String getLockLevelString() { 2017 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2018 case PowerManager.FULL_WAKE_LOCK: 2019 return "FULL_WAKE_LOCK "; 2020 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2021 return "SCREEN_BRIGHT_WAKE_LOCK "; 2022 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2023 return "SCREEN_DIM_WAKE_LOCK "; 2024 case PowerManager.PARTIAL_WAKE_LOCK: 2025 return "PARTIAL_WAKE_LOCK "; 2026 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2027 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2028 default: 2029 return "??? "; 2030 } 2031 } 2032 2033 private String getLockFlagsString() { 2034 String result = ""; 2035 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2036 result += " ACQUIRE_CAUSES_WAKEUP"; 2037 } 2038 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2039 result += " ON_AFTER_RELEASE"; 2040 } 2041 return result; 2042 } 2043 } 2044 2045 private final class SuspendBlockerImpl implements SuspendBlocker { 2046 private final String mName; 2047 private int mReferenceCount; 2048 2049 public SuspendBlockerImpl(String name) { 2050 mName = name; 2051 } 2052 2053 @Override 2054 protected void finalize() throws Throwable { 2055 try { 2056 if (mReferenceCount != 0) { 2057 Log.wtf(TAG, "Suspend blocker \"" + mName 2058 + "\" was finalized without being released!"); 2059 mReferenceCount = 0; 2060 nativeReleaseSuspendBlocker(mName); 2061 } 2062 } finally { 2063 super.finalize(); 2064 } 2065 } 2066 2067 @Override 2068 public void acquire() { 2069 synchronized (this) { 2070 mReferenceCount += 1; 2071 if (mReferenceCount == 1) { 2072 nativeAcquireSuspendBlocker(mName); 2073 } 2074 } 2075 } 2076 2077 @Override 2078 public void release() { 2079 synchronized (this) { 2080 mReferenceCount -= 1; 2081 if (mReferenceCount == 0) { 2082 nativeReleaseSuspendBlocker(mName); 2083 } else if (mReferenceCount < 0) { 2084 Log.wtf(TAG, "Suspend blocker \"" + mName 2085 + "\" was released without being acquired!", new Throwable()); 2086 mReferenceCount = 0; 2087 } 2088 } 2089 } 2090 2091 @Override 2092 public String toString() { 2093 synchronized (this) { 2094 return mName + ": ref count=" + mReferenceCount; 2095 } 2096 } 2097 } 2098} 2099