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