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