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