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