PowerManagerService.java revision c2932a1be3e320679034212698aff376d5104dbe
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.internal.os.BackgroundThread; 22import com.android.server.EventLogTags; 23import com.android.server.ServiceThread; 24import com.android.server.SystemService; 25import com.android.server.am.BatteryStatsService; 26import com.android.server.lights.Light; 27import com.android.server.lights.LightsManager; 28import com.android.server.Watchdog; 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.hardware.display.DisplayManagerInternal.DisplayPowerRequest; 43import android.net.Uri; 44import android.os.BatteryManager; 45import android.os.BatteryManagerInternal; 46import android.os.Binder; 47import android.os.Handler; 48import android.os.IBinder; 49import android.os.IPowerManager; 50import android.os.Looper; 51import android.os.Message; 52import android.os.PowerManager; 53import android.os.PowerManagerInternal; 54import android.os.Process; 55import android.os.RemoteException; 56import android.os.SystemClock; 57import android.os.SystemProperties; 58import android.os.Trace; 59import android.os.UserHandle; 60import android.os.WorkSource; 61import android.provider.Settings; 62import android.service.dreams.DreamManagerInternal; 63import android.util.EventLog; 64import android.util.Slog; 65import android.util.TimeUtils; 66import android.view.Display; 67import android.view.WindowManagerPolicy; 68 69import java.io.FileDescriptor; 70import java.io.PrintWriter; 71import java.util.ArrayList; 72 73import libcore.util.Objects; 74 75import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP; 76import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE; 77import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING; 78import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING; 79 80/** 81 * The power manager service is responsible for coordinating power management 82 * functions on the device. 83 */ 84public final class PowerManagerService extends SystemService 85 implements Watchdog.Monitor { 86 private static final String TAG = "PowerManagerService"; 87 88 private static final boolean DEBUG = false; 89 private static final boolean DEBUG_SPEW = DEBUG && true; 90 91 // Message: Sent when a user activity timeout occurs to update the power state. 92 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 93 // Message: Sent when the device enters or exits a dreaming or dozing state. 94 private static final int MSG_SANDMAN = 2; 95 // Message: Sent when the screen brightness boost expires. 96 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3; 97 98 // Dirty bit: mWakeLocks changed 99 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 100 // Dirty bit: mWakefulness changed 101 private static final int DIRTY_WAKEFULNESS = 1 << 1; 102 // Dirty bit: user activity was poked or may have timed out 103 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 104 // Dirty bit: actual display power state was updated asynchronously 105 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 106 // Dirty bit: mBootCompleted changed 107 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 108 // Dirty bit: settings changed 109 private static final int DIRTY_SETTINGS = 1 << 5; 110 // Dirty bit: mIsPowered changed 111 private static final int DIRTY_IS_POWERED = 1 << 6; 112 // Dirty bit: mStayOn changed 113 private static final int DIRTY_STAY_ON = 1 << 7; 114 // Dirty bit: battery state changed 115 private static final int DIRTY_BATTERY_STATE = 1 << 8; 116 // Dirty bit: proximity state changed 117 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9; 118 // Dirty bit: dock state changed 119 private static final int DIRTY_DOCK_STATE = 1 << 10; 120 // Dirty bit: brightness boost changed 121 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11; 122 123 // Summarizes the state of all active wakelocks. 124 private static final int WAKE_LOCK_CPU = 1 << 0; 125 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 126 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 127 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 128 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 129 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake 130 private static final int WAKE_LOCK_DOZE = 1 << 6; 131 private static final int WAKE_LOCK_DRAW = 1 << 7; 132 133 // Summarizes the user activity state. 134 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 135 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 136 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2; 137 138 // Default timeout in milliseconds. This is only used until the settings 139 // provider populates the actual default value (R.integer.def_screen_off_timeout). 140 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 141 private static final int DEFAULT_SLEEP_TIMEOUT = -1; 142 143 // Screen brightness boost timeout. 144 // Hardcoded for now until we decide what the right policy should be. 145 // This should perhaps be a setting. 146 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000; 147 148 // Power hints defined in hardware/libhardware/include/hardware/power.h. 149 private static final int POWER_HINT_INTERACTION = 2; 150 private static final int POWER_HINT_LOW_POWER = 5; 151 152 private final Context mContext; 153 private final ServiceThread mHandlerThread; 154 private final PowerManagerHandler mHandler; 155 156 private LightsManager mLightsManager; 157 private BatteryManagerInternal mBatteryManagerInternal; 158 private DisplayManagerInternal mDisplayManagerInternal; 159 private IBatteryStats mBatteryStats; 160 private IAppOpsService mAppOps; 161 private WindowManagerPolicy mPolicy; 162 private Notifier mNotifier; 163 private WirelessChargerDetector mWirelessChargerDetector; 164 private SettingsObserver mSettingsObserver; 165 private DreamManagerInternal mDreamManager; 166 private Light mAttentionLight; 167 168 private final Object mLock = new Object(); 169 170 // A bitfield that indicates what parts of the power state have 171 // changed and need to be recalculated. 172 private int mDirty; 173 174 // Indicates whether the device is awake or asleep or somewhere in between. 175 // This is distinct from the screen power state, which is managed separately. 176 private int mWakefulness; 177 private boolean mWakefulnessChanging; 178 179 // True if the sandman has just been summoned for the first time since entering the 180 // dreaming or dozing state. Indicates whether a new dream should begin. 181 private boolean mSandmanSummoned; 182 183 // True if MSG_SANDMAN has been scheduled. 184 private boolean mSandmanScheduled; 185 186 // Table of all suspend blockers. 187 // There should only be a few of these. 188 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 189 190 // Table of all wake locks acquired by applications. 191 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 192 193 // A bitfield that summarizes the state of all active wakelocks. 194 private int mWakeLockSummary; 195 196 // If true, instructs the display controller to wait for the proximity sensor to 197 // go negative before turning the screen on. 198 private boolean mRequestWaitForNegativeProximity; 199 200 // Timestamp of the last time the device was awoken or put to sleep. 201 private long mLastWakeTime; 202 private long mLastSleepTime; 203 204 // Timestamp of the last call to user activity. 205 private long mLastUserActivityTime; 206 private long mLastUserActivityTimeNoChangeLights; 207 208 // Timestamp of last interactive power hint. 209 private long mLastInteractivePowerHintTime; 210 211 // Timestamp of the last screen brightness boost. 212 private long mLastScreenBrightnessBoostTime; 213 private boolean mScreenBrightnessBoostInProgress; 214 215 // A bitfield that summarizes the effect of the user activity timer. 216 private int mUserActivitySummary; 217 218 // The desired display power state. The actual state may lag behind the 219 // requested because it is updated asynchronously by the display power controller. 220 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 221 222 // True if the display power state has been fully applied, which means the display 223 // is actually on or actually off or whatever was requested. 224 private boolean mDisplayReady; 225 226 // The suspend blocker used to keep the CPU alive when an application has acquired 227 // a wake lock. 228 private final SuspendBlocker mWakeLockSuspendBlocker; 229 230 // True if the wake lock suspend blocker has been acquired. 231 private boolean mHoldingWakeLockSuspendBlocker; 232 233 // The suspend blocker used to keep the CPU alive when the display is on, the 234 // display is getting ready or there is user activity (in which case the display 235 // must be on). 236 private final SuspendBlocker mDisplaySuspendBlocker; 237 238 // True if the display suspend blocker has been acquired. 239 private boolean mHoldingDisplaySuspendBlocker; 240 241 // True if systemReady() has been called. 242 private boolean mSystemReady; 243 244 // True if boot completed occurred. We keep the screen on until this happens. 245 private boolean mBootCompleted; 246 247 // True if auto-suspend mode is enabled. 248 // Refer to autosuspend.h. 249 private boolean mHalAutoSuspendModeEnabled; 250 251 // True if interactive mode is enabled. 252 // Refer to power.h. 253 private boolean mHalInteractiveModeEnabled; 254 255 // True if the device is plugged into a power source. 256 private boolean mIsPowered; 257 258 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS. 259 private int mPlugType; 260 261 // The current battery level percentage. 262 private int mBatteryLevel; 263 264 // The battery level percentage at the time the dream started. 265 // This is used to terminate a dream and go to sleep if the battery is 266 // draining faster than it is charging and the user activity timeout has expired. 267 private int mBatteryLevelWhenDreamStarted; 268 269 // The current dock state. 270 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; 271 272 // True to decouple auto-suspend mode from the display state. 273 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig; 274 275 // True to decouple interactive mode from the display state. 276 private boolean mDecoupleHalInteractiveModeFromDisplayConfig; 277 278 // True if the device should wake up when plugged or unplugged. 279 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 280 281 // True if the device should wake up when plugged or unplugged in theater mode. 282 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig; 283 284 // True if the device should suspend when the screen is off due to proximity. 285 private boolean mSuspendWhenScreenOffDueToProximityConfig; 286 287 // True if dreams are supported on this device. 288 private boolean mDreamsSupportedConfig; 289 290 // Default value for dreams enabled 291 private boolean mDreamsEnabledByDefaultConfig; 292 293 // Default value for dreams activate-on-sleep 294 private boolean mDreamsActivatedOnSleepByDefaultConfig; 295 296 // Default value for dreams activate-on-dock 297 private boolean mDreamsActivatedOnDockByDefaultConfig; 298 299 // True if dreams can run while not plugged in. 300 private boolean mDreamsEnabledOnBatteryConfig; 301 302 // Minimum battery level to allow dreaming when powered. 303 // Use -1 to disable this safety feature. 304 private int mDreamsBatteryLevelMinimumWhenPoweredConfig; 305 306 // Minimum battery level to allow dreaming when not powered. 307 // Use -1 to disable this safety feature. 308 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig; 309 310 // If the battery level drops by this percentage and the user activity timeout 311 // has expired, then assume the device is receiving insufficient current to charge 312 // effectively and terminate the dream. Use -1 to disable this safety feature. 313 private int mDreamsBatteryLevelDrainCutoffConfig; 314 315 // True if dreams are enabled by the user. 316 private boolean mDreamsEnabledSetting; 317 318 // True if dreams should be activated on sleep. 319 private boolean mDreamsActivateOnSleepSetting; 320 321 // True if dreams should be activated on dock. 322 private boolean mDreamsActivateOnDockSetting; 323 324 // True if doze should not be started until after the screen off transition. 325 private boolean mDozeAfterScreenOffConfig; 326 327 // The minimum screen off timeout, in milliseconds. 328 private int mMinimumScreenOffTimeoutConfig; 329 330 // The screen dim duration, in milliseconds. 331 // This is subtracted from the end of the screen off timeout so the 332 // minimum screen off timeout should be longer than this. 333 private int mMaximumScreenDimDurationConfig; 334 335 // The maximum screen dim time expressed as a ratio relative to the screen 336 // off timeout. If the screen off timeout is very short then we want the 337 // dim timeout to also be quite short so that most of the time is spent on. 338 // Otherwise the user won't get much screen on time before dimming occurs. 339 private float mMaximumScreenDimRatioConfig; 340 341 // The screen off timeout setting value in milliseconds. 342 private int mScreenOffTimeoutSetting; 343 344 // The sleep timeout setting value in milliseconds. 345 private int mSleepTimeoutSetting; 346 347 // The maximum allowable screen off timeout according to the device 348 // administration policy. Overrides other settings. 349 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 350 351 // The stay on while plugged in setting. 352 // A bitfield of battery conditions under which to make the screen stay on. 353 private int mStayOnWhilePluggedInSetting; 354 355 // True if the device should stay on. 356 private boolean mStayOn; 357 358 // True if the proximity sensor reads a positive result. 359 private boolean mProximityPositive; 360 361 // Screen brightness setting limits. 362 private int mScreenBrightnessSettingMinimum; 363 private int mScreenBrightnessSettingMaximum; 364 private int mScreenBrightnessSettingDefault; 365 366 // The screen brightness setting, from 0 to 255. 367 // Use -1 if no value has been set. 368 private int mScreenBrightnessSetting; 369 370 // The screen auto-brightness adjustment setting, from -1 to 1. 371 // Use 0 if there is no adjustment. 372 private float mScreenAutoBrightnessAdjustmentSetting; 373 374 // The screen brightness mode. 375 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 376 private int mScreenBrightnessModeSetting; 377 378 // The screen brightness setting override from the window manager 379 // to allow the current foreground activity to override the brightness. 380 // Use -1 to disable. 381 private int mScreenBrightnessOverrideFromWindowManager = -1; 382 383 // The user activity timeout override from the window manager 384 // to allow the current foreground activity to override the user activity timeout. 385 // Use -1 to disable. 386 private long mUserActivityTimeoutOverrideFromWindowManager = -1; 387 388 // The screen brightness setting override from the settings application 389 // to temporarily adjust the brightness until next updated, 390 // Use -1 to disable. 391 private int mTemporaryScreenBrightnessSettingOverride = -1; 392 393 // The screen brightness adjustment setting override from the settings 394 // application to temporarily adjust the auto-brightness adjustment factor 395 // until next updated, in the range -1..1. 396 // Use NaN to disable. 397 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 398 399 // The screen state to use while dozing. 400 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN; 401 402 // The screen brightness to use while dozing. 403 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT; 404 405 // Time when we last logged a warning about calling userActivity() without permission. 406 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE; 407 408 // If true, the device is in low power mode. 409 private boolean mLowPowerModeEnabled; 410 411 // Current state of the low power mode setting. 412 private boolean mLowPowerModeSetting; 413 414 // Current state of whether the settings are allowing auto low power mode. 415 private boolean mAutoLowPowerModeConfigured; 416 417 // The user turned off low power mode below the trigger level 418 private boolean mAutoLowPowerModeSnoozing; 419 420 // True if the battery level is currently considered low. 421 private boolean mBatteryLevelLow; 422 423 // True if theater mode is enabled 424 private boolean mTheaterModeEnabled; 425 426 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners 427 = new ArrayList<PowerManagerInternal.LowPowerModeListener>(); 428 429 private native void nativeInit(); 430 431 private static native void nativeAcquireSuspendBlocker(String name); 432 private static native void nativeReleaseSuspendBlocker(String name); 433 private static native void nativeSetInteractive(boolean enable); 434 private static native void nativeSetAutoSuspend(boolean enable); 435 private static native void nativeSendPowerHint(int hintId, int data); 436 437 public PowerManagerService(Context context) { 438 super(context); 439 mContext = context; 440 mHandlerThread = new ServiceThread(TAG, 441 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/); 442 mHandlerThread.start(); 443 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 444 445 synchronized (mLock) { 446 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks"); 447 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display"); 448 mDisplaySuspendBlocker.acquire(); 449 mHoldingDisplaySuspendBlocker = true; 450 mHalAutoSuspendModeEnabled = false; 451 mHalInteractiveModeEnabled = true; 452 453 mWakefulness = WAKEFULNESS_AWAKE; 454 455 nativeInit(); 456 nativeSetAutoSuspend(false); 457 nativeSetInteractive(true); 458 } 459 } 460 461 @Override 462 public void onStart() { 463 publishBinderService(Context.POWER_SERVICE, new BinderService()); 464 publishLocalService(PowerManagerInternal.class, new LocalService()); 465 466 Watchdog.getInstance().addMonitor(this); 467 Watchdog.getInstance().addThread(mHandler); 468 } 469 470 @Override 471 public void onBootPhase(int phase) { 472 synchronized (mLock) { 473 if (phase == PHASE_BOOT_COMPLETED) { 474 final long now = SystemClock.uptimeMillis(); 475 mBootCompleted = true; 476 mDirty |= DIRTY_BOOT_COMPLETED; 477 userActivityNoUpdateLocked( 478 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 479 updatePowerStateLocked(); 480 } 481 } 482 } 483 484 public void systemReady(IAppOpsService appOps) { 485 synchronized (mLock) { 486 mSystemReady = true; 487 mAppOps = appOps; 488 mDreamManager = getLocalService(DreamManagerInternal.class); 489 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class); 490 mPolicy = getLocalService(WindowManagerPolicy.class); 491 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class); 492 493 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 494 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 495 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 496 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 497 498 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper()); 499 500 // The notifier runs on the system server's main looper so as not to interfere 501 // with the animations and other critical functions of the power manager. 502 mBatteryStats = BatteryStatsService.getService(); 503 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, 504 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 505 mPolicy); 506 507 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager, 508 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"), 509 mHandler); 510 mSettingsObserver = new SettingsObserver(mHandler); 511 512 mLightsManager = getLocalService(LightsManager.class); 513 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION); 514 515 // Initialize display power management. 516 mDisplayManagerInternal.initPowerManagement( 517 mDisplayPowerCallbacks, mHandler, sensorManager); 518 519 // Register for broadcasts from other components of the system. 520 IntentFilter filter = new IntentFilter(); 521 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 522 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 523 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler); 524 525 filter = new IntentFilter(); 526 filter.addAction(Intent.ACTION_DREAMING_STARTED); 527 filter.addAction(Intent.ACTION_DREAMING_STOPPED); 528 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler); 529 530 filter = new IntentFilter(); 531 filter.addAction(Intent.ACTION_USER_SWITCHED); 532 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler); 533 534 filter = new IntentFilter(); 535 filter.addAction(Intent.ACTION_DOCK_EVENT); 536 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler); 537 538 // Register for settings changes. 539 final ContentResolver resolver = mContext.getContentResolver(); 540 resolver.registerContentObserver(Settings.Secure.getUriFor( 541 Settings.Secure.SCREENSAVER_ENABLED), 542 false, mSettingsObserver, UserHandle.USER_ALL); 543 resolver.registerContentObserver(Settings.Secure.getUriFor( 544 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), 545 false, mSettingsObserver, UserHandle.USER_ALL); 546 resolver.registerContentObserver(Settings.Secure.getUriFor( 547 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), 548 false, mSettingsObserver, UserHandle.USER_ALL); 549 resolver.registerContentObserver(Settings.System.getUriFor( 550 Settings.System.SCREEN_OFF_TIMEOUT), 551 false, mSettingsObserver, UserHandle.USER_ALL); 552 resolver.registerContentObserver(Settings.Secure.getUriFor( 553 Settings.Secure.SLEEP_TIMEOUT), 554 false, mSettingsObserver, UserHandle.USER_ALL); 555 resolver.registerContentObserver(Settings.Global.getUriFor( 556 Settings.Global.STAY_ON_WHILE_PLUGGED_IN), 557 false, mSettingsObserver, UserHandle.USER_ALL); 558 resolver.registerContentObserver(Settings.System.getUriFor( 559 Settings.System.SCREEN_BRIGHTNESS), 560 false, mSettingsObserver, UserHandle.USER_ALL); 561 resolver.registerContentObserver(Settings.System.getUriFor( 562 Settings.System.SCREEN_BRIGHTNESS_MODE), 563 false, mSettingsObserver, UserHandle.USER_ALL); 564 resolver.registerContentObserver(Settings.System.getUriFor( 565 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ), 566 false, mSettingsObserver, UserHandle.USER_ALL); 567 resolver.registerContentObserver(Settings.Global.getUriFor( 568 Settings.Global.LOW_POWER_MODE), 569 false, mSettingsObserver, UserHandle.USER_ALL); 570 resolver.registerContentObserver(Settings.Global.getUriFor( 571 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL), 572 false, mSettingsObserver, UserHandle.USER_ALL); 573 resolver.registerContentObserver(Settings.Global.getUriFor( 574 Settings.Global.THEATER_MODE_ON), 575 false, mSettingsObserver, UserHandle.USER_ALL); 576 // Go. 577 readConfigurationLocked(); 578 updateSettingsLocked(); 579 mDirty |= DIRTY_BATTERY_STATE; 580 updatePowerStateLocked(); 581 } 582 } 583 584 private void readConfigurationLocked() { 585 final Resources resources = mContext.getResources(); 586 587 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean( 588 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay); 589 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean( 590 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay); 591 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 592 com.android.internal.R.bool.config_unplugTurnsOnScreen); 593 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean( 594 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug); 595 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean( 596 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity); 597 mDreamsSupportedConfig = resources.getBoolean( 598 com.android.internal.R.bool.config_dreamsSupported); 599 mDreamsEnabledByDefaultConfig = resources.getBoolean( 600 com.android.internal.R.bool.config_dreamsEnabledByDefault); 601 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean( 602 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault); 603 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean( 604 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault); 605 mDreamsEnabledOnBatteryConfig = resources.getBoolean( 606 com.android.internal.R.bool.config_dreamsEnabledOnBattery); 607 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger( 608 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered); 609 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger( 610 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered); 611 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger( 612 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff); 613 mDozeAfterScreenOffConfig = resources.getBoolean( 614 com.android.internal.R.bool.config_dozeAfterScreenOff); 615 mMinimumScreenOffTimeoutConfig = resources.getInteger( 616 com.android.internal.R.integer.config_minimumScreenOffTimeout); 617 mMaximumScreenDimDurationConfig = resources.getInteger( 618 com.android.internal.R.integer.config_maximumScreenDimDuration); 619 mMaximumScreenDimRatioConfig = resources.getFraction( 620 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1); 621 } 622 623 private void updateSettingsLocked() { 624 final ContentResolver resolver = mContext.getContentResolver(); 625 626 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver, 627 Settings.Secure.SCREENSAVER_ENABLED, 628 mDreamsEnabledByDefaultConfig ? 1 : 0, 629 UserHandle.USER_CURRENT) != 0); 630 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver, 631 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 632 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0, 633 UserHandle.USER_CURRENT) != 0); 634 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver, 635 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK, 636 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0, 637 UserHandle.USER_CURRENT) != 0); 638 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver, 639 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT, 640 UserHandle.USER_CURRENT); 641 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver, 642 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT, 643 UserHandle.USER_CURRENT); 644 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver, 645 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC); 646 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(), 647 Settings.Global.THEATER_MODE_ON, 0) == 1; 648 649 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 650 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver, 651 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault, 652 UserHandle.USER_CURRENT); 653 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 654 mTemporaryScreenBrightnessSettingOverride = -1; 655 } 656 657 final float oldScreenAutoBrightnessAdjustmentSetting = 658 mScreenAutoBrightnessAdjustmentSetting; 659 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver, 660 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, 661 UserHandle.USER_CURRENT); 662 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 663 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 664 } 665 666 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver, 667 Settings.System.SCREEN_BRIGHTNESS_MODE, 668 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT); 669 670 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver, 671 Settings.Global.LOW_POWER_MODE, 0) != 0; 672 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver, 673 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0; 674 if (lowPowerModeEnabled != mLowPowerModeSetting 675 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) { 676 mLowPowerModeSetting = lowPowerModeEnabled; 677 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured; 678 updateLowPowerModeLocked(); 679 } 680 681 mDirty |= DIRTY_SETTINGS; 682 } 683 684 void updateLowPowerModeLocked() { 685 if (mIsPowered && mLowPowerModeSetting) { 686 if (DEBUG_SPEW) { 687 Slog.d(TAG, "updateLowPowerModeLocked: powered, turning setting off"); 688 } 689 // Turn setting off if powered 690 Settings.Global.putInt(mContext.getContentResolver(), 691 Settings.Global.LOW_POWER_MODE, 0); 692 mLowPowerModeSetting = false; 693 } 694 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured 695 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow; 696 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled; 697 698 if (mLowPowerModeEnabled != lowPowerModeEnabled) { 699 mLowPowerModeEnabled = lowPowerModeEnabled; 700 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0); 701 BackgroundThread.getHandler().post(new Runnable() { 702 @Override 703 public void run() { 704 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING) 705 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled) 706 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 707 mContext.sendBroadcast(intent); 708 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners; 709 synchronized (mLock) { 710 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>( 711 mLowPowerModeListeners); 712 } 713 for (int i=0; i<listeners.size(); i++) { 714 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled); 715 } 716 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); 717 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 718 mContext.sendBroadcast(intent); 719 } 720 }); 721 } 722 } 723 724 private void handleSettingsChangedLocked() { 725 updateSettingsLocked(); 726 updatePowerStateLocked(); 727 } 728 729 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName, 730 WorkSource ws, String historyTag, int uid, int pid) { 731 synchronized (mLock) { 732 if (DEBUG_SPEW) { 733 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 734 + ", flags=0x" + Integer.toHexString(flags) 735 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 736 } 737 738 WakeLock wakeLock; 739 int index = findWakeLockIndexLocked(lock); 740 boolean notifyAcquire; 741 if (index >= 0) { 742 wakeLock = mWakeLocks.get(index); 743 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 744 // Update existing wake lock. This shouldn't happen but is harmless. 745 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName, 746 uid, pid, ws, historyTag); 747 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid); 748 } 749 notifyAcquire = false; 750 } else { 751 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid); 752 try { 753 lock.linkToDeath(wakeLock, 0); 754 } catch (RemoteException ex) { 755 throw new IllegalArgumentException("Wake lock is already dead."); 756 } 757 mWakeLocks.add(wakeLock); 758 notifyAcquire = true; 759 } 760 761 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid); 762 mDirty |= DIRTY_WAKE_LOCKS; 763 updatePowerStateLocked(); 764 if (notifyAcquire) { 765 // This needs to be done last so we are sure we have acquired the 766 // kernel wake lock. Otherwise we have a race where the system may 767 // go to sleep between the time we start the accounting in battery 768 // stats and when we actually get around to telling the kernel to 769 // stay awake. 770 notifyWakeLockAcquiredLocked(wakeLock); 771 } 772 } 773 } 774 775 @SuppressWarnings("deprecation") 776 private static boolean isScreenLock(final WakeLock wakeLock) { 777 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 778 case PowerManager.FULL_WAKE_LOCK: 779 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 780 case PowerManager.SCREEN_DIM_WAKE_LOCK: 781 return true; 782 } 783 return false; 784 } 785 786 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) { 787 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0 788 && isScreenLock(wakeLock)) { 789 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), uid); 790 } 791 } 792 793 private void releaseWakeLockInternal(IBinder lock, int flags) { 794 synchronized (mLock) { 795 int index = findWakeLockIndexLocked(lock); 796 if (index < 0) { 797 if (DEBUG_SPEW) { 798 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 799 + " [not found], flags=0x" + Integer.toHexString(flags)); 800 } 801 return; 802 } 803 804 WakeLock wakeLock = mWakeLocks.get(index); 805 if (DEBUG_SPEW) { 806 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 807 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags)); 808 } 809 810 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) { 811 mRequestWaitForNegativeProximity = true; 812 } 813 814 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 815 removeWakeLockLocked(wakeLock, index); 816 } 817 } 818 819 private void handleWakeLockDeath(WakeLock wakeLock) { 820 synchronized (mLock) { 821 if (DEBUG_SPEW) { 822 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock) 823 + " [" + wakeLock.mTag + "]"); 824 } 825 826 int index = mWakeLocks.indexOf(wakeLock); 827 if (index < 0) { 828 return; 829 } 830 831 removeWakeLockLocked(wakeLock, index); 832 } 833 } 834 835 private void removeWakeLockLocked(WakeLock wakeLock, int index) { 836 mWakeLocks.remove(index); 837 notifyWakeLockReleasedLocked(wakeLock); 838 839 applyWakeLockFlagsOnReleaseLocked(wakeLock); 840 mDirty |= DIRTY_WAKE_LOCKS; 841 updatePowerStateLocked(); 842 } 843 844 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 845 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0 846 && isScreenLock(wakeLock)) { 847 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 848 PowerManager.USER_ACTIVITY_EVENT_OTHER, 849 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 850 wakeLock.mOwnerUid); 851 } 852 } 853 854 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag, 855 int callingUid) { 856 synchronized (mLock) { 857 int index = findWakeLockIndexLocked(lock); 858 if (index < 0) { 859 if (DEBUG_SPEW) { 860 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 861 + " [not found], ws=" + ws); 862 } 863 throw new IllegalArgumentException("Wake lock not active: " + lock 864 + " from uid " + callingUid); 865 } 866 867 WakeLock wakeLock = mWakeLocks.get(index); 868 if (DEBUG_SPEW) { 869 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 870 + " [" + wakeLock.mTag + "], ws=" + ws); 871 } 872 873 if (!wakeLock.hasSameWorkSource(ws)) { 874 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag, 875 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 876 ws, historyTag); 877 wakeLock.mHistoryTag = historyTag; 878 wakeLock.updateWorkSource(ws); 879 } 880 } 881 } 882 883 private int findWakeLockIndexLocked(IBinder lock) { 884 final int count = mWakeLocks.size(); 885 for (int i = 0; i < count; i++) { 886 if (mWakeLocks.get(i).mLock == lock) { 887 return i; 888 } 889 } 890 return -1; 891 } 892 893 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 894 if (mSystemReady) { 895 wakeLock.mNotifiedAcquired = true; 896 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 897 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 898 wakeLock.mHistoryTag); 899 } 900 } 901 902 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag, 903 String packageName, int uid, int pid, WorkSource ws, String historyTag) { 904 if (mSystemReady && wakeLock.mNotifiedAcquired) { 905 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 906 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 907 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag); 908 } 909 } 910 911 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 912 if (mSystemReady && wakeLock.mNotifiedAcquired) { 913 wakeLock.mNotifiedAcquired = false; 914 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 915 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 916 wakeLock.mWorkSource, wakeLock.mHistoryTag); 917 } 918 } 919 920 @SuppressWarnings("deprecation") 921 private boolean isWakeLockLevelSupportedInternal(int level) { 922 synchronized (mLock) { 923 switch (level) { 924 case PowerManager.PARTIAL_WAKE_LOCK: 925 case PowerManager.SCREEN_DIM_WAKE_LOCK: 926 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 927 case PowerManager.FULL_WAKE_LOCK: 928 case PowerManager.DOZE_WAKE_LOCK: 929 return true; 930 931 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 932 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable(); 933 934 default: 935 return false; 936 } 937 } 938 } 939 940 // Called from native code. 941 private void userActivityFromNative(long eventTime, int event, int flags) { 942 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 943 } 944 945 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 946 synchronized (mLock) { 947 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 948 updatePowerStateLocked(); 949 } 950 } 951 } 952 953 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 954 if (DEBUG_SPEW) { 955 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 956 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 957 + ", uid=" + uid); 958 } 959 960 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 961 || !mBootCompleted || !mSystemReady) { 962 return false; 963 } 964 965 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity"); 966 try { 967 if (eventTime > mLastInteractivePowerHintTime) { 968 powerHintInternal(POWER_HINT_INTERACTION, 0); 969 mLastInteractivePowerHintTime = eventTime; 970 } 971 972 mNotifier.onUserActivity(event, uid); 973 974 if (mWakefulness == WAKEFULNESS_ASLEEP 975 || mWakefulness == WAKEFULNESS_DOZING 976 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) { 977 return false; 978 } 979 980 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 981 if (eventTime > mLastUserActivityTimeNoChangeLights 982 && eventTime > mLastUserActivityTime) { 983 mLastUserActivityTimeNoChangeLights = eventTime; 984 mDirty |= DIRTY_USER_ACTIVITY; 985 return true; 986 } 987 } else { 988 if (eventTime > mLastUserActivityTime) { 989 mLastUserActivityTime = eventTime; 990 mDirty |= DIRTY_USER_ACTIVITY; 991 return true; 992 } 993 } 994 } finally { 995 Trace.traceEnd(Trace.TRACE_TAG_POWER); 996 } 997 return false; 998 } 999 1000 private void wakeUpInternal(long eventTime, int uid) { 1001 synchronized (mLock) { 1002 if (wakeUpNoUpdateLocked(eventTime, uid)) { 1003 updatePowerStateLocked(); 1004 } 1005 } 1006 } 1007 1008 private boolean wakeUpNoUpdateLocked(long eventTime, int uid) { 1009 if (DEBUG_SPEW) { 1010 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid); 1011 } 1012 1013 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 1014 || !mBootCompleted || !mSystemReady) { 1015 return false; 1016 } 1017 1018 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp"); 1019 try { 1020 switch (mWakefulness) { 1021 case WAKEFULNESS_ASLEEP: 1022 Slog.i(TAG, "Waking up from sleep (uid " + uid +")..."); 1023 break; 1024 case WAKEFULNESS_DREAMING: 1025 Slog.i(TAG, "Waking up from dream (uid " + uid +")..."); 1026 break; 1027 case WAKEFULNESS_DOZING: 1028 Slog.i(TAG, "Waking up from dozing (uid " + uid +")..."); 1029 break; 1030 } 1031 1032 mLastWakeTime = eventTime; 1033 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0); 1034 1035 userActivityNoUpdateLocked( 1036 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid); 1037 } finally { 1038 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1039 } 1040 return true; 1041 } 1042 1043 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) { 1044 synchronized (mLock) { 1045 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) { 1046 updatePowerStateLocked(); 1047 } 1048 } 1049 } 1050 1051 // This method is called goToSleep for historical reasons but we actually start 1052 // dozing before really going to sleep. 1053 @SuppressWarnings("deprecation") 1054 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) { 1055 if (DEBUG_SPEW) { 1056 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime 1057 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid); 1058 } 1059 1060 if (eventTime < mLastWakeTime 1061 || mWakefulness == WAKEFULNESS_ASLEEP 1062 || mWakefulness == WAKEFULNESS_DOZING 1063 || !mBootCompleted || !mSystemReady) { 1064 return false; 1065 } 1066 1067 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep"); 1068 try { 1069 switch (reason) { 1070 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 1071 Slog.i(TAG, "Going to sleep due to device administration policy " 1072 + "(uid " + uid +")..."); 1073 break; 1074 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 1075 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")..."); 1076 break; 1077 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH: 1078 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")..."); 1079 break; 1080 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON: 1081 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")..."); 1082 break; 1083 case PowerManager.GO_TO_SLEEP_REASON_HDMI: 1084 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")..."); 1085 break; 1086 default: 1087 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")..."); 1088 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION; 1089 break; 1090 } 1091 1092 mLastSleepTime = eventTime; 1093 mSandmanSummoned = true; 1094 setWakefulnessLocked(WAKEFULNESS_DOZING, reason); 1095 1096 // Report the number of wake locks that will be cleared by going to sleep. 1097 int numWakeLocksCleared = 0; 1098 final int numWakeLocks = mWakeLocks.size(); 1099 for (int i = 0; i < numWakeLocks; i++) { 1100 final WakeLock wakeLock = mWakeLocks.get(i); 1101 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1102 case PowerManager.FULL_WAKE_LOCK: 1103 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1104 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1105 numWakeLocksCleared += 1; 1106 break; 1107 } 1108 } 1109 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 1110 1111 // Skip dozing if requested. 1112 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) { 1113 reallyGoToSleepNoUpdateLocked(eventTime, uid); 1114 } 1115 } finally { 1116 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1117 } 1118 return true; 1119 } 1120 1121 private void napInternal(long eventTime, int uid) { 1122 synchronized (mLock) { 1123 if (napNoUpdateLocked(eventTime, uid)) { 1124 updatePowerStateLocked(); 1125 } 1126 } 1127 } 1128 1129 private boolean napNoUpdateLocked(long eventTime, int uid) { 1130 if (DEBUG_SPEW) { 1131 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid); 1132 } 1133 1134 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE 1135 || !mBootCompleted || !mSystemReady) { 1136 return false; 1137 } 1138 1139 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap"); 1140 try { 1141 Slog.i(TAG, "Nap time (uid " + uid +")..."); 1142 1143 mSandmanSummoned = true; 1144 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0); 1145 } finally { 1146 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1147 } 1148 return true; 1149 } 1150 1151 // Done dozing, drop everything and go to sleep. 1152 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) { 1153 if (DEBUG_SPEW) { 1154 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime 1155 + ", uid=" + uid); 1156 } 1157 1158 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 1159 || !mBootCompleted || !mSystemReady) { 1160 return false; 1161 } 1162 1163 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep"); 1164 try { 1165 Slog.i(TAG, "Sleeping (uid " + uid +")..."); 1166 1167 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1168 } finally { 1169 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1170 } 1171 return true; 1172 } 1173 1174 private void setWakefulnessLocked(int wakefulness, int reason) { 1175 if (mWakefulness != wakefulness) { 1176 finishWakefulnessChangeLocked(); 1177 1178 mWakefulness = wakefulness; 1179 mWakefulnessChanging = true; 1180 mDirty |= DIRTY_WAKEFULNESS; 1181 mNotifier.onWakefulnessChangeStarted(wakefulness, reason); 1182 } 1183 } 1184 1185 private void finishWakefulnessChangeLocked() { 1186 if (mWakefulnessChanging) { 1187 mNotifier.onWakefulnessChangeFinished(mWakefulness); 1188 mWakefulnessChanging = false; 1189 } 1190 } 1191 1192 /** 1193 * Updates the global power state based on dirty bits recorded in mDirty. 1194 * 1195 * This is the main function that performs power state transitions. 1196 * We centralize them here so that we can recompute the power state completely 1197 * each time something important changes, and ensure that we do it the same 1198 * way each time. The point is to gather all of the transition logic here. 1199 */ 1200 private void updatePowerStateLocked() { 1201 if (!mSystemReady || mDirty == 0) { 1202 return; 1203 } 1204 if (!Thread.holdsLock(mLock)) { 1205 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked"); 1206 } 1207 1208 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState"); 1209 try { 1210 // Phase 0: Basic state updates. 1211 updateIsPoweredLocked(mDirty); 1212 updateStayOnLocked(mDirty); 1213 updateScreenBrightnessBoostLocked(mDirty); 1214 1215 // Phase 1: Update wakefulness. 1216 // Loop because the wake lock and user activity computations are influenced 1217 // by changes in wakefulness. 1218 final long now = SystemClock.uptimeMillis(); 1219 int dirtyPhase2 = 0; 1220 for (;;) { 1221 int dirtyPhase1 = mDirty; 1222 dirtyPhase2 |= dirtyPhase1; 1223 mDirty = 0; 1224 1225 updateWakeLockSummaryLocked(dirtyPhase1); 1226 updateUserActivitySummaryLocked(now, dirtyPhase1); 1227 if (!updateWakefulnessLocked(dirtyPhase1)) { 1228 break; 1229 } 1230 } 1231 1232 // Phase 2: Update display power state. 1233 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2); 1234 1235 // Phase 3: Update dream state (depends on display ready signal). 1236 updateDreamLocked(dirtyPhase2, displayBecameReady); 1237 1238 // Phase 4: Send notifications, if needed. 1239 if (mDisplayReady) { 1240 finishWakefulnessChangeLocked(); 1241 } 1242 1243 // Phase 5: Update suspend blocker. 1244 // Because we might release the last suspend blocker here, we need to make sure 1245 // we finished everything else first! 1246 updateSuspendBlockerLocked(); 1247 } finally { 1248 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1249 } 1250 } 1251 1252 /** 1253 * Updates the value of mIsPowered. 1254 * Sets DIRTY_IS_POWERED if a change occurred. 1255 */ 1256 private void updateIsPoweredLocked(int dirty) { 1257 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 1258 final boolean wasPowered = mIsPowered; 1259 final int oldPlugType = mPlugType; 1260 final boolean oldLevelLow = mBatteryLevelLow; 1261 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY); 1262 mPlugType = mBatteryManagerInternal.getPlugType(); 1263 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel(); 1264 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow(); 1265 1266 if (DEBUG_SPEW) { 1267 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered 1268 + ", mIsPowered=" + mIsPowered 1269 + ", oldPlugType=" + oldPlugType 1270 + ", mPlugType=" + mPlugType 1271 + ", mBatteryLevel=" + mBatteryLevel); 1272 } 1273 1274 if (wasPowered != mIsPowered || oldPlugType != mPlugType) { 1275 mDirty |= DIRTY_IS_POWERED; 1276 1277 // Update wireless dock detection state. 1278 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update( 1279 mIsPowered, mPlugType, mBatteryLevel); 1280 1281 // Treat plugging and unplugging the devices as a user activity. 1282 // Users find it disconcerting when they plug or unplug the device 1283 // and it shuts off right away. 1284 // Some devices also wake the device when plugged or unplugged because 1285 // they don't have a charging LED. 1286 final long now = SystemClock.uptimeMillis(); 1287 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType, 1288 dockedOnWirelessCharger)) { 1289 wakeUpNoUpdateLocked(now, Process.SYSTEM_UID); 1290 } 1291 userActivityNoUpdateLocked( 1292 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1293 1294 // Tell the notifier whether wireless charging has started so that 1295 // it can provide feedback to the user. 1296 if (dockedOnWirelessCharger) { 1297 mNotifier.onWirelessChargingStarted(); 1298 } 1299 } 1300 1301 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) { 1302 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) { 1303 if (DEBUG_SPEW) { 1304 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze"); 1305 } 1306 mAutoLowPowerModeSnoozing = false; 1307 } 1308 updateLowPowerModeLocked(); 1309 } 1310 } 1311 } 1312 1313 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked( 1314 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) { 1315 // Don't wake when powered unless configured to do so. 1316 if (!mWakeUpWhenPluggedOrUnpluggedConfig) { 1317 return false; 1318 } 1319 1320 // Don't wake when undocked from wireless charger. 1321 // See WirelessChargerDetector for justification. 1322 if (wasPowered && !mIsPowered 1323 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 1324 return false; 1325 } 1326 1327 // Don't wake when docked on wireless charger unless we are certain of it. 1328 // See WirelessChargerDetector for justification. 1329 if (!wasPowered && mIsPowered 1330 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS 1331 && !dockedOnWirelessCharger) { 1332 return false; 1333 } 1334 1335 // If already dreaming and becoming powered, then don't wake. 1336 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) { 1337 return false; 1338 } 1339 1340 // Don't wake while theater mode is enabled. 1341 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) { 1342 return false; 1343 } 1344 1345 // Otherwise wake up! 1346 return true; 1347 } 1348 1349 /** 1350 * Updates the value of mStayOn. 1351 * Sets DIRTY_STAY_ON if a change occurred. 1352 */ 1353 private void updateStayOnLocked(int dirty) { 1354 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 1355 final boolean wasStayOn = mStayOn; 1356 if (mStayOnWhilePluggedInSetting != 0 1357 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1358 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting); 1359 } else { 1360 mStayOn = false; 1361 } 1362 1363 if (mStayOn != wasStayOn) { 1364 mDirty |= DIRTY_STAY_ON; 1365 } 1366 } 1367 } 1368 1369 /** 1370 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 1371 * Note that most wake-locks are ignored when the system is asleep. 1372 * 1373 * This function must have no other side-effects. 1374 */ 1375 @SuppressWarnings("deprecation") 1376 private void updateWakeLockSummaryLocked(int dirty) { 1377 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 1378 mWakeLockSummary = 0; 1379 1380 final int numWakeLocks = mWakeLocks.size(); 1381 for (int i = 0; i < numWakeLocks; i++) { 1382 final WakeLock wakeLock = mWakeLocks.get(i); 1383 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1384 case PowerManager.PARTIAL_WAKE_LOCK: 1385 mWakeLockSummary |= WAKE_LOCK_CPU; 1386 break; 1387 case PowerManager.FULL_WAKE_LOCK: 1388 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 1389 break; 1390 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1391 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT; 1392 break; 1393 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1394 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM; 1395 break; 1396 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1397 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1398 break; 1399 case PowerManager.DOZE_WAKE_LOCK: 1400 mWakeLockSummary |= WAKE_LOCK_DOZE; 1401 break; 1402 case PowerManager.DRAW_WAKE_LOCK: 1403 mWakeLockSummary |= WAKE_LOCK_DRAW; 1404 break; 1405 } 1406 } 1407 1408 // Cancel wake locks that make no sense based on the current state. 1409 if (mWakefulness != WAKEFULNESS_DOZING) { 1410 mWakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW); 1411 } 1412 if (mWakefulness == WAKEFULNESS_ASLEEP 1413 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 1414 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM 1415 | WAKE_LOCK_BUTTON_BRIGHT); 1416 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1417 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1418 } 1419 } 1420 1421 // Infer implied wake locks where necessary based on the current state. 1422 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) { 1423 if (mWakefulness == WAKEFULNESS_AWAKE) { 1424 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE; 1425 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1426 mWakeLockSummary |= WAKE_LOCK_CPU; 1427 } 1428 } 1429 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 1430 mWakeLockSummary |= WAKE_LOCK_CPU; 1431 } 1432 1433 if (DEBUG_SPEW) { 1434 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1435 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1436 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1437 } 1438 } 1439 } 1440 1441 /** 1442 * Updates the value of mUserActivitySummary to summarize the user requested 1443 * state of the system such as whether the screen should be bright or dim. 1444 * Note that user activity is ignored when the system is asleep. 1445 * 1446 * This function must have no other side-effects. 1447 */ 1448 private void updateUserActivitySummaryLocked(long now, int dirty) { 1449 // Update the status of the user activity timeout timer. 1450 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY 1451 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1452 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1453 1454 long nextTimeout = 0; 1455 if (mWakefulness == WAKEFULNESS_AWAKE 1456 || mWakefulness == WAKEFULNESS_DREAMING 1457 || mWakefulness == WAKEFULNESS_DOZING) { 1458 final int sleepTimeout = getSleepTimeoutLocked(); 1459 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 1460 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1461 1462 mUserActivitySummary = 0; 1463 if (mLastUserActivityTime >= mLastWakeTime) { 1464 nextTimeout = mLastUserActivityTime 1465 + screenOffTimeout - screenDimDuration; 1466 if (now < nextTimeout) { 1467 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1468 } else { 1469 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1470 if (now < nextTimeout) { 1471 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1472 } 1473 } 1474 } 1475 if (mUserActivitySummary == 0 1476 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1477 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1478 if (now < nextTimeout) { 1479 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) { 1480 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1481 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) { 1482 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1483 } 1484 } 1485 } 1486 if (mUserActivitySummary == 0) { 1487 if (sleepTimeout >= 0) { 1488 final long anyUserActivity = Math.max(mLastUserActivityTime, 1489 mLastUserActivityTimeNoChangeLights); 1490 if (anyUserActivity >= mLastWakeTime) { 1491 nextTimeout = anyUserActivity + sleepTimeout; 1492 if (now < nextTimeout) { 1493 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1494 } 1495 } 1496 } else { 1497 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1498 nextTimeout = -1; 1499 } 1500 } 1501 if (mUserActivitySummary != 0 && nextTimeout >= 0) { 1502 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1503 msg.setAsynchronous(true); 1504 mHandler.sendMessageAtTime(msg, nextTimeout); 1505 } 1506 } else { 1507 mUserActivitySummary = 0; 1508 } 1509 1510 if (DEBUG_SPEW) { 1511 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1512 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1513 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1514 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1515 } 1516 } 1517 } 1518 1519 /** 1520 * Called when a user activity timeout has occurred. 1521 * Simply indicates that something about user activity has changed so that the new 1522 * state can be recomputed when the power state is updated. 1523 * 1524 * This function must have no other side-effects besides setting the dirty 1525 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1526 */ 1527 private void handleUserActivityTimeout() { // runs on handler thread 1528 synchronized (mLock) { 1529 if (DEBUG_SPEW) { 1530 Slog.d(TAG, "handleUserActivityTimeout"); 1531 } 1532 1533 mDirty |= DIRTY_USER_ACTIVITY; 1534 updatePowerStateLocked(); 1535 } 1536 } 1537 1538 private int getSleepTimeoutLocked() { 1539 int timeout = mSleepTimeoutSetting; 1540 if (timeout <= 0) { 1541 return -1; 1542 } 1543 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1544 } 1545 1546 private int getScreenOffTimeoutLocked(int sleepTimeout) { 1547 int timeout = mScreenOffTimeoutSetting; 1548 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1549 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1550 } 1551 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) { 1552 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager); 1553 } 1554 if (sleepTimeout >= 0) { 1555 timeout = Math.min(timeout, sleepTimeout); 1556 } 1557 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1558 } 1559 1560 private int getScreenDimDurationLocked(int screenOffTimeout) { 1561 return Math.min(mMaximumScreenDimDurationConfig, 1562 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig)); 1563 } 1564 1565 /** 1566 * Updates the wakefulness of the device. 1567 * 1568 * This is the function that decides whether the device should start dreaming 1569 * based on the current wake locks and user activity state. It may modify mDirty 1570 * if the wakefulness changes. 1571 * 1572 * Returns true if the wakefulness changed and we need to restart power state calculation. 1573 */ 1574 private boolean updateWakefulnessLocked(int dirty) { 1575 boolean changed = false; 1576 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1577 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE 1578 | DIRTY_DOCK_STATE)) != 0) { 1579 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1580 if (DEBUG_SPEW) { 1581 Slog.d(TAG, "updateWakefulnessLocked: Bed time..."); 1582 } 1583 final long time = SystemClock.uptimeMillis(); 1584 if (shouldNapAtBedTimeLocked()) { 1585 changed = napNoUpdateLocked(time, Process.SYSTEM_UID); 1586 } else { 1587 changed = goToSleepNoUpdateLocked(time, 1588 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1589 } 1590 } 1591 } 1592 return changed; 1593 } 1594 1595 /** 1596 * Returns true if the device should automatically nap and start dreaming when the user 1597 * activity timeout has expired and it's bedtime. 1598 */ 1599 private boolean shouldNapAtBedTimeLocked() { 1600 return mDreamsActivateOnSleepSetting 1601 || (mDreamsActivateOnDockSetting 1602 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED); 1603 } 1604 1605 /** 1606 * Returns true if the device should go to sleep now. 1607 * Also used when exiting a dream to determine whether we should go back 1608 * to being fully awake or else go to sleep for good. 1609 */ 1610 private boolean isItBedTimeYetLocked() { 1611 return mBootCompleted && !isBeingKeptAwakeLocked(); 1612 } 1613 1614 /** 1615 * Returns true if the device is being kept awake by a wake lock, user activity 1616 * or the stay on while powered setting. We also keep the phone awake when 1617 * the proximity sensor returns a positive result so that the device does not 1618 * lock while in a phone call. This function only controls whether the device 1619 * will go to sleep or dream which is independent of whether it will be allowed 1620 * to suspend. 1621 */ 1622 private boolean isBeingKeptAwakeLocked() { 1623 return mStayOn 1624 || mProximityPositive 1625 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0 1626 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1627 | USER_ACTIVITY_SCREEN_DIM)) != 0 1628 || mScreenBrightnessBoostInProgress; 1629 } 1630 1631 /** 1632 * Determines whether to post a message to the sandman to update the dream state. 1633 */ 1634 private void updateDreamLocked(int dirty, boolean displayBecameReady) { 1635 if ((dirty & (DIRTY_WAKEFULNESS 1636 | DIRTY_USER_ACTIVITY 1637 | DIRTY_WAKE_LOCKS 1638 | DIRTY_BOOT_COMPLETED 1639 | DIRTY_SETTINGS 1640 | DIRTY_IS_POWERED 1641 | DIRTY_STAY_ON 1642 | DIRTY_PROXIMITY_POSITIVE 1643 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) { 1644 if (mDisplayReady) { 1645 scheduleSandmanLocked(); 1646 } 1647 } 1648 } 1649 1650 private void scheduleSandmanLocked() { 1651 if (!mSandmanScheduled) { 1652 mSandmanScheduled = true; 1653 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1654 msg.setAsynchronous(true); 1655 mHandler.sendMessage(msg); 1656 } 1657 } 1658 1659 /** 1660 * Called when the device enters or exits a dreaming or dozing state. 1661 * 1662 * We do this asynchronously because we must call out of the power manager to start 1663 * the dream and we don't want to hold our lock while doing so. There is a risk that 1664 * the device will wake or go to sleep in the meantime so we have to handle that case. 1665 */ 1666 private void handleSandman() { // runs on handler thread 1667 // Handle preconditions. 1668 final boolean startDreaming; 1669 final int wakefulness; 1670 synchronized (mLock) { 1671 mSandmanScheduled = false; 1672 wakefulness = mWakefulness; 1673 if (mSandmanSummoned && mDisplayReady) { 1674 startDreaming = canDreamLocked() || canDozeLocked(); 1675 mSandmanSummoned = false; 1676 } else { 1677 startDreaming = false; 1678 } 1679 } 1680 1681 // Start dreaming if needed. 1682 // We only control the dream on the handler thread, so we don't need to worry about 1683 // concurrent attempts to start or stop the dream. 1684 final boolean isDreaming; 1685 if (mDreamManager != null) { 1686 // Restart the dream whenever the sandman is summoned. 1687 if (startDreaming) { 1688 mDreamManager.stopDream(false /*immediate*/); 1689 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING); 1690 } 1691 isDreaming = mDreamManager.isDreaming(); 1692 } else { 1693 isDreaming = false; 1694 } 1695 1696 // Update dream state. 1697 synchronized (mLock) { 1698 // Remember the initial battery level when the dream started. 1699 if (startDreaming && isDreaming) { 1700 mBatteryLevelWhenDreamStarted = mBatteryLevel; 1701 if (wakefulness == WAKEFULNESS_DOZING) { 1702 Slog.i(TAG, "Dozing..."); 1703 } else { 1704 Slog.i(TAG, "Dreaming..."); 1705 } 1706 } 1707 1708 // If preconditions changed, wait for the next iteration to determine 1709 // whether the dream should continue (or be restarted). 1710 if (mSandmanSummoned || mWakefulness != wakefulness) { 1711 return; // wait for next cycle 1712 } 1713 1714 // Determine whether the dream should continue. 1715 if (wakefulness == WAKEFULNESS_DREAMING) { 1716 if (isDreaming && canDreamLocked()) { 1717 if (mDreamsBatteryLevelDrainCutoffConfig >= 0 1718 && mBatteryLevel < mBatteryLevelWhenDreamStarted 1719 - mDreamsBatteryLevelDrainCutoffConfig 1720 && !isBeingKeptAwakeLocked()) { 1721 // If the user activity timeout expired and the battery appears 1722 // to be draining faster than it is charging then stop dreaming 1723 // and go to sleep. 1724 Slog.i(TAG, "Stopping dream because the battery appears to " 1725 + "be draining faster than it is charging. " 1726 + "Battery level when dream started: " 1727 + mBatteryLevelWhenDreamStarted + "%. " 1728 + "Battery level now: " + mBatteryLevel + "%."); 1729 } else { 1730 return; // continue dreaming 1731 } 1732 } 1733 1734 // Dream has ended or will be stopped. Update the power state. 1735 if (isItBedTimeYetLocked()) { 1736 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1737 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1738 updatePowerStateLocked(); 1739 } else { 1740 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID); 1741 updatePowerStateLocked(); 1742 } 1743 } else if (wakefulness == WAKEFULNESS_DOZING) { 1744 if (isDreaming) { 1745 return; // continue dozing 1746 } 1747 1748 // Doze has ended or will be stopped. Update the power state. 1749 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID); 1750 updatePowerStateLocked(); 1751 } 1752 } 1753 1754 // Stop dream. 1755 if (isDreaming) { 1756 mDreamManager.stopDream(false /*immediate*/); 1757 } 1758 } 1759 1760 /** 1761 * Returns true if the device is allowed to dream in its current state. 1762 */ 1763 private boolean canDreamLocked() { 1764 if (mWakefulness != WAKEFULNESS_DREAMING 1765 || !mDreamsSupportedConfig 1766 || !mDreamsEnabledSetting 1767 || !mDisplayPowerRequest.isBrightOrDim() 1768 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1769 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0 1770 || !mBootCompleted) { 1771 return false; 1772 } 1773 if (!isBeingKeptAwakeLocked()) { 1774 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) { 1775 return false; 1776 } 1777 if (!mIsPowered 1778 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0 1779 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) { 1780 return false; 1781 } 1782 if (mIsPowered 1783 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0 1784 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) { 1785 return false; 1786 } 1787 } 1788 return true; 1789 } 1790 1791 /** 1792 * Returns true if the device is allowed to doze in its current state. 1793 */ 1794 private boolean canDozeLocked() { 1795 return mWakefulness == WAKEFULNESS_DOZING; 1796 } 1797 1798 /** 1799 * Updates the display power state asynchronously. 1800 * When the update is finished, mDisplayReady will be set to true. The display 1801 * controller posts a message to tell us when the actual display power state 1802 * has been updated so we come back here to double-check and finish up. 1803 * 1804 * This function recalculates the display power state each time. 1805 * 1806 * @return True if the display became ready. 1807 */ 1808 private boolean updateDisplayPowerStateLocked(int dirty) { 1809 final boolean oldDisplayReady = mDisplayReady; 1810 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1811 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1812 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) { 1813 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked(); 1814 1815 // Determine appropriate screen brightness and auto-brightness adjustments. 1816 int screenBrightness = mScreenBrightnessSettingDefault; 1817 float screenAutoBrightnessAdjustment = 0.0f; 1818 boolean autoBrightness = (mScreenBrightnessModeSetting == 1819 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1820 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1821 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1822 autoBrightness = false; 1823 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1824 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1825 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1826 screenBrightness = mScreenBrightnessSetting; 1827 } 1828 if (autoBrightness) { 1829 screenBrightness = mScreenBrightnessSettingDefault; 1830 if (isValidAutoBrightnessAdjustment( 1831 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1832 screenAutoBrightnessAdjustment = 1833 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1834 } else if (isValidAutoBrightnessAdjustment( 1835 mScreenAutoBrightnessAdjustmentSetting)) { 1836 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1837 } 1838 } 1839 screenBrightness = Math.max(Math.min(screenBrightness, 1840 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1841 screenAutoBrightnessAdjustment = Math.max(Math.min( 1842 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1843 1844 // Update display power request. 1845 mDisplayPowerRequest.screenBrightness = screenBrightness; 1846 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1847 screenAutoBrightnessAdjustment; 1848 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1849 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1850 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled; 1851 mDisplayPowerRequest.boostScreenBrightness = mScreenBrightnessBoostInProgress; 1852 1853 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) { 1854 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager; 1855 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND 1856 && (mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 1857 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE; 1858 } 1859 mDisplayPowerRequest.dozeScreenBrightness = 1860 mDozeScreenBrightnessOverrideFromDreamManager; 1861 } else { 1862 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN; 1863 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 1864 } 1865 1866 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest, 1867 mRequestWaitForNegativeProximity); 1868 mRequestWaitForNegativeProximity = false; 1869 1870 if (DEBUG_SPEW) { 1871 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady 1872 + ", policy=" + mDisplayPowerRequest.policy 1873 + ", mWakefulness=" + mWakefulness 1874 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1875 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1876 + ", mBootCompleted=" + mBootCompleted 1877 + ", mScreenBrightnessBoostInProgress=" 1878 + mScreenBrightnessBoostInProgress); 1879 } 1880 } 1881 return mDisplayReady && !oldDisplayReady; 1882 } 1883 1884 private void updateScreenBrightnessBoostLocked(int dirty) { 1885 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) { 1886 if (mScreenBrightnessBoostInProgress) { 1887 final long now = SystemClock.uptimeMillis(); 1888 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 1889 if (mLastScreenBrightnessBoostTime > mLastSleepTime) { 1890 final long boostTimeout = mLastScreenBrightnessBoostTime + 1891 SCREEN_BRIGHTNESS_BOOST_TIMEOUT; 1892 if (boostTimeout > now) { 1893 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 1894 msg.setAsynchronous(true); 1895 mHandler.sendMessageAtTime(msg, boostTimeout); 1896 return; 1897 } 1898 } 1899 mScreenBrightnessBoostInProgress = false; 1900 userActivityNoUpdateLocked(now, 1901 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1902 } 1903 } 1904 } 1905 1906 private static boolean isValidBrightness(int value) { 1907 return value >= 0 && value <= 255; 1908 } 1909 1910 private static boolean isValidAutoBrightnessAdjustment(float value) { 1911 // Handles NaN by always returning false. 1912 return value >= -1.0f && value <= 1.0f; 1913 } 1914 1915 private int getDesiredScreenPolicyLocked() { 1916 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1917 return DisplayPowerRequest.POLICY_OFF; 1918 } 1919 1920 if (mWakefulness == WAKEFULNESS_DOZING) { 1921 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 1922 return DisplayPowerRequest.POLICY_DOZE; 1923 } 1924 if (mDozeAfterScreenOffConfig) { 1925 return DisplayPowerRequest.POLICY_OFF; 1926 } 1927 // Fall through and preserve the current screen policy if not configured to 1928 // doze after screen off. This causes the screen off transition to be skipped. 1929 } 1930 1931 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1932 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1933 || !mBootCompleted 1934 || mScreenBrightnessBoostInProgress) { 1935 return DisplayPowerRequest.POLICY_BRIGHT; 1936 } 1937 1938 return DisplayPowerRequest.POLICY_DIM; 1939 } 1940 1941 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks = 1942 new DisplayManagerInternal.DisplayPowerCallbacks() { 1943 private int mDisplayState = Display.STATE_UNKNOWN; 1944 1945 @Override 1946 public void onStateChanged() { 1947 synchronized (mLock) { 1948 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1949 updatePowerStateLocked(); 1950 } 1951 } 1952 1953 @Override 1954 public void onProximityPositive() { 1955 synchronized (mLock) { 1956 mProximityPositive = true; 1957 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1958 updatePowerStateLocked(); 1959 } 1960 } 1961 1962 @Override 1963 public void onProximityNegative() { 1964 synchronized (mLock) { 1965 mProximityPositive = false; 1966 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1967 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1968 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1969 updatePowerStateLocked(); 1970 } 1971 } 1972 1973 @Override 1974 public void onDisplayStateChange(int state) { 1975 // This method is only needed to support legacy display blanking behavior 1976 // where the display's power state is coupled to suspend or to the power HAL. 1977 // The order of operations matters here. 1978 synchronized (mLock) { 1979 if (mDisplayState != state) { 1980 mDisplayState = state; 1981 if (state == Display.STATE_OFF) { 1982 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 1983 setHalInteractiveModeLocked(false); 1984 } 1985 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 1986 setHalAutoSuspendModeLocked(true); 1987 } 1988 } else { 1989 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 1990 setHalAutoSuspendModeLocked(false); 1991 } 1992 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 1993 setHalInteractiveModeLocked(true); 1994 } 1995 } 1996 } 1997 } 1998 } 1999 2000 @Override 2001 public void acquireSuspendBlocker() { 2002 mDisplaySuspendBlocker.acquire(); 2003 } 2004 2005 @Override 2006 public void releaseSuspendBlocker() { 2007 mDisplaySuspendBlocker.release(); 2008 } 2009 2010 @Override 2011 public String toString() { 2012 synchronized (this) { 2013 return "state=" + Display.stateToString(mDisplayState); 2014 } 2015 } 2016 }; 2017 2018 private boolean shouldUseProximitySensorLocked() { 2019 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 2020 } 2021 2022 /** 2023 * Updates the suspend blocker that keeps the CPU alive. 2024 * 2025 * This function must have no other side-effects. 2026 */ 2027 private void updateSuspendBlockerLocked() { 2028 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0); 2029 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked(); 2030 final boolean autoSuspend = !needDisplaySuspendBlocker; 2031 final boolean interactive = mDisplayPowerRequest.isBrightOrDim(); 2032 2033 // Disable auto-suspend if needed. 2034 // FIXME We should consider just leaving auto-suspend enabled forever since 2035 // we already hold the necessary wakelocks. 2036 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2037 setHalAutoSuspendModeLocked(false); 2038 } 2039 2040 // First acquire suspend blockers if needed. 2041 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) { 2042 mWakeLockSuspendBlocker.acquire(); 2043 mHoldingWakeLockSuspendBlocker = true; 2044 } 2045 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) { 2046 mDisplaySuspendBlocker.acquire(); 2047 mHoldingDisplaySuspendBlocker = true; 2048 } 2049 2050 // Inform the power HAL about interactive mode. 2051 // Although we could set interactive strictly based on the wakefulness 2052 // as reported by isInteractive(), it is actually more desirable to track 2053 // the display policy state instead so that the interactive state observed 2054 // by the HAL more accurately tracks transitions between AWAKE and DOZING. 2055 // Refer to getDesiredScreenPolicyLocked() for details. 2056 if (mDecoupleHalInteractiveModeFromDisplayConfig) { 2057 // When becoming non-interactive, we want to defer sending this signal 2058 // until the display is actually ready so that all transitions have 2059 // completed. This is probably a good sign that things have gotten 2060 // too tangled over here... 2061 if (interactive || mDisplayReady) { 2062 setHalInteractiveModeLocked(interactive); 2063 } 2064 } 2065 2066 // Then release suspend blockers if needed. 2067 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) { 2068 mWakeLockSuspendBlocker.release(); 2069 mHoldingWakeLockSuspendBlocker = false; 2070 } 2071 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) { 2072 mDisplaySuspendBlocker.release(); 2073 mHoldingDisplaySuspendBlocker = false; 2074 } 2075 2076 // Enable auto-suspend if needed. 2077 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2078 setHalAutoSuspendModeLocked(true); 2079 } 2080 } 2081 2082 /** 2083 * Return true if we must keep a suspend blocker active on behalf of the display. 2084 * We do so if the screen is on or is in transition between states. 2085 */ 2086 private boolean needDisplaySuspendBlockerLocked() { 2087 if (!mDisplayReady) { 2088 return true; 2089 } 2090 if (mDisplayPowerRequest.isBrightOrDim()) { 2091 // If we asked for the screen to be on but it is off due to the proximity 2092 // sensor then we may suspend but only if the configuration allows it. 2093 // On some hardware it may not be safe to suspend because the proximity 2094 // sensor may not be correctly configured as a wake-up source. 2095 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive 2096 || !mSuspendWhenScreenOffDueToProximityConfig) { 2097 return true; 2098 } 2099 } 2100 if (mScreenBrightnessBoostInProgress) { 2101 return true; 2102 } 2103 // Let the system suspend if the screen is off or dozing. 2104 return false; 2105 } 2106 2107 private void setHalAutoSuspendModeLocked(boolean enable) { 2108 if (enable != mHalAutoSuspendModeEnabled) { 2109 if (DEBUG) { 2110 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable); 2111 } 2112 mHalAutoSuspendModeEnabled = enable; 2113 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")"); 2114 try { 2115 nativeSetAutoSuspend(enable); 2116 } finally { 2117 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2118 } 2119 } 2120 } 2121 2122 private void setHalInteractiveModeLocked(boolean enable) { 2123 if (enable != mHalInteractiveModeEnabled) { 2124 if (DEBUG) { 2125 Slog.d(TAG, "Setting HAL interactive mode to " + enable); 2126 } 2127 mHalInteractiveModeEnabled = enable; 2128 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")"); 2129 try { 2130 nativeSetInteractive(enable); 2131 } finally { 2132 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2133 } 2134 } 2135 } 2136 2137 private boolean isInteractiveInternal() { 2138 synchronized (mLock) { 2139 return PowerManagerInternal.isInteractive(mWakefulness); 2140 } 2141 } 2142 2143 private boolean isLowPowerModeInternal() { 2144 synchronized (mLock) { 2145 return mLowPowerModeEnabled; 2146 } 2147 } 2148 2149 private boolean setLowPowerModeInternal(boolean mode) { 2150 synchronized (mLock) { 2151 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered); 2152 if (mIsPowered) { 2153 return false; 2154 } 2155 Settings.Global.putInt(mContext.getContentResolver(), 2156 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0); 2157 mLowPowerModeSetting = mode; 2158 2159 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) { 2160 if (mode && mAutoLowPowerModeSnoozing) { 2161 if (DEBUG_SPEW) { 2162 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze"); 2163 } 2164 mAutoLowPowerModeSnoozing = false; 2165 } else if (!mode && !mAutoLowPowerModeSnoozing) { 2166 if (DEBUG_SPEW) { 2167 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode"); 2168 } 2169 mAutoLowPowerModeSnoozing = true; 2170 } 2171 } 2172 2173 updateLowPowerModeLocked(); 2174 return true; 2175 } 2176 } 2177 2178 private void handleBatteryStateChangedLocked() { 2179 mDirty |= DIRTY_BATTERY_STATE; 2180 updatePowerStateLocked(); 2181 } 2182 2183 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm, 2184 final String reason, boolean wait) { 2185 if (mHandler == null || !mSystemReady) { 2186 throw new IllegalStateException("Too early to call shutdown() or reboot()"); 2187 } 2188 2189 Runnable runnable = new Runnable() { 2190 @Override 2191 public void run() { 2192 synchronized (this) { 2193 if (shutdown) { 2194 ShutdownThread.shutdown(mContext, confirm); 2195 } else { 2196 ShutdownThread.reboot(mContext, reason, confirm); 2197 } 2198 } 2199 } 2200 }; 2201 2202 // ShutdownThread must run on a looper capable of displaying the UI. 2203 Message msg = Message.obtain(mHandler, runnable); 2204 msg.setAsynchronous(true); 2205 mHandler.sendMessage(msg); 2206 2207 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 2208 if (wait) { 2209 synchronized (runnable) { 2210 while (true) { 2211 try { 2212 runnable.wait(); 2213 } catch (InterruptedException e) { 2214 } 2215 } 2216 } 2217 } 2218 } 2219 2220 private void crashInternal(final String message) { 2221 Thread t = new Thread("PowerManagerService.crash()") { 2222 @Override 2223 public void run() { 2224 throw new RuntimeException(message); 2225 } 2226 }; 2227 try { 2228 t.start(); 2229 t.join(); 2230 } catch (InterruptedException e) { 2231 Slog.wtf(TAG, e); 2232 } 2233 } 2234 2235 private void setStayOnSettingInternal(int val) { 2236 Settings.Global.putInt(mContext.getContentResolver(), 2237 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 2238 } 2239 2240 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 2241 synchronized (mLock) { 2242 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 2243 mDirty |= DIRTY_SETTINGS; 2244 updatePowerStateLocked(); 2245 } 2246 } 2247 2248 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 2249 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 2250 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 2251 } 2252 2253 private void setAttentionLightInternal(boolean on, int color) { 2254 Light light; 2255 synchronized (mLock) { 2256 if (!mSystemReady) { 2257 return; 2258 } 2259 light = mAttentionLight; 2260 } 2261 2262 // Control light outside of lock. 2263 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 2264 } 2265 2266 private void boostScreenBrightnessInternal(long eventTime, int uid) { 2267 synchronized (mLock) { 2268 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP 2269 || eventTime < mLastScreenBrightnessBoostTime) { 2270 return; 2271 } 2272 2273 Slog.i(TAG, "Brightness boost activated (uid " + uid +")..."); 2274 mLastScreenBrightnessBoostTime = eventTime; 2275 mScreenBrightnessBoostInProgress = true; 2276 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2277 2278 userActivityNoUpdateLocked(eventTime, 2279 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid); 2280 updatePowerStateLocked(); 2281 } 2282 } 2283 2284 /** 2285 * Called when a screen brightness boost timeout has occurred. 2286 * 2287 * This function must have no other side-effects besides setting the dirty 2288 * bit and calling update power state. 2289 */ 2290 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread 2291 synchronized (mLock) { 2292 if (DEBUG_SPEW) { 2293 Slog.d(TAG, "handleScreenBrightnessBoostTimeout"); 2294 } 2295 2296 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2297 updatePowerStateLocked(); 2298 } 2299 } 2300 2301 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 2302 synchronized (mLock) { 2303 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 2304 mScreenBrightnessOverrideFromWindowManager = brightness; 2305 mDirty |= DIRTY_SETTINGS; 2306 updatePowerStateLocked(); 2307 } 2308 } 2309 } 2310 2311 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 2312 synchronized (mLock) { 2313 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 2314 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 2315 mDirty |= DIRTY_SETTINGS; 2316 updatePowerStateLocked(); 2317 } 2318 } 2319 } 2320 2321 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 2322 synchronized (mLock) { 2323 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 2324 mTemporaryScreenBrightnessSettingOverride = brightness; 2325 mDirty |= DIRTY_SETTINGS; 2326 updatePowerStateLocked(); 2327 } 2328 } 2329 } 2330 2331 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 2332 synchronized (mLock) { 2333 // Note: This condition handles NaN because NaN is not equal to any other 2334 // value, including itself. 2335 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 2336 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 2337 mDirty |= DIRTY_SETTINGS; 2338 updatePowerStateLocked(); 2339 } 2340 } 2341 } 2342 2343 private void setDozeOverrideFromDreamManagerInternal( 2344 int screenState, int screenBrightness) { 2345 synchronized (mLock) { 2346 if (mDozeScreenStateOverrideFromDreamManager != screenState 2347 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) { 2348 mDozeScreenStateOverrideFromDreamManager = screenState; 2349 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness; 2350 mDirty |= DIRTY_SETTINGS; 2351 updatePowerStateLocked(); 2352 } 2353 } 2354 } 2355 2356 private void powerHintInternal(int hintId, int data) { 2357 nativeSendPowerHint(hintId, data); 2358 } 2359 2360 /** 2361 * Low-level function turn the device off immediately, without trying 2362 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 2363 */ 2364 public static void lowLevelShutdown() { 2365 SystemProperties.set("sys.powerctl", "shutdown"); 2366 } 2367 2368 /** 2369 * Low-level function to reboot the device. On success, this 2370 * function doesn't return. If more than 20 seconds passes from 2371 * the time a reboot is requested (120 seconds for reboot to 2372 * recovery), this method returns. 2373 * 2374 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 2375 */ 2376 public static void lowLevelReboot(String reason) { 2377 if (reason == null) { 2378 reason = ""; 2379 } 2380 long duration; 2381 if (reason.equals(PowerManager.REBOOT_RECOVERY)) { 2382 // If we are rebooting to go into recovery, instead of 2383 // setting sys.powerctl directly we'll start the 2384 // pre-recovery service which will do some preparation for 2385 // recovery and then reboot for us. 2386 // 2387 // This preparation can take more than 20 seconds if 2388 // there's a very large update package, so lengthen the 2389 // timeout. We have seen 750MB packages take 3-4 minutes 2390 SystemProperties.set("ctl.start", "pre-recovery"); 2391 duration = 300 * 1000L; 2392 } else { 2393 SystemProperties.set("sys.powerctl", "reboot," + reason); 2394 duration = 20 * 1000L; 2395 } 2396 try { 2397 Thread.sleep(duration); 2398 } catch (InterruptedException e) { 2399 Thread.currentThread().interrupt(); 2400 } 2401 } 2402 2403 @Override // Watchdog.Monitor implementation 2404 public void monitor() { 2405 // Grab and release lock for watchdog monitor to detect deadlocks. 2406 synchronized (mLock) { 2407 } 2408 } 2409 2410 private void dumpInternal(PrintWriter pw) { 2411 pw.println("POWER MANAGER (dumpsys power)\n"); 2412 2413 final WirelessChargerDetector wcd; 2414 synchronized (mLock) { 2415 pw.println("Power Manager State:"); 2416 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 2417 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness)); 2418 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging); 2419 pw.println(" mIsPowered=" + mIsPowered); 2420 pw.println(" mPlugType=" + mPlugType); 2421 pw.println(" mBatteryLevel=" + mBatteryLevel); 2422 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted); 2423 pw.println(" mDockState=" + mDockState); 2424 pw.println(" mStayOn=" + mStayOn); 2425 pw.println(" mProximityPositive=" + mProximityPositive); 2426 pw.println(" mBootCompleted=" + mBootCompleted); 2427 pw.println(" mSystemReady=" + mSystemReady); 2428 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled); 2429 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled); 2430 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 2431 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 2432 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 2433 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 2434 pw.println(" mSandmanSummoned=" + mSandmanSummoned); 2435 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled); 2436 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow); 2437 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 2438 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 2439 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 2440 pw.println(" mLastUserActivityTimeNoChangeLights=" 2441 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 2442 pw.println(" mLastInteractivePowerHintTime=" 2443 + TimeUtils.formatUptime(mLastInteractivePowerHintTime)); 2444 pw.println(" mLastScreenBrightnessBoostTime=" 2445 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime)); 2446 pw.println(" mScreenBrightnessBoostInProgress=" 2447 + mScreenBrightnessBoostInProgress); 2448 pw.println(" mDisplayReady=" + mDisplayReady); 2449 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 2450 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker); 2451 2452 pw.println(); 2453 pw.println("Settings and Configuration:"); 2454 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig=" 2455 + mDecoupleHalAutoSuspendModeFromDisplayConfig); 2456 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig=" 2457 + mDecoupleHalInteractiveModeFromDisplayConfig); 2458 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig=" 2459 + mWakeUpWhenPluggedOrUnpluggedConfig); 2460 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig=" 2461 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig); 2462 pw.println(" mTheaterModeEnabled=" 2463 + mTheaterModeEnabled); 2464 pw.println(" mSuspendWhenScreenOffDueToProximityConfig=" 2465 + mSuspendWhenScreenOffDueToProximityConfig); 2466 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 2467 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig); 2468 pw.println(" mDreamsActivatedOnSleepByDefaultConfig=" 2469 + mDreamsActivatedOnSleepByDefaultConfig); 2470 pw.println(" mDreamsActivatedOnDockByDefaultConfig=" 2471 + mDreamsActivatedOnDockByDefaultConfig); 2472 pw.println(" mDreamsEnabledOnBatteryConfig=" 2473 + mDreamsEnabledOnBatteryConfig); 2474 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig=" 2475 + mDreamsBatteryLevelMinimumWhenPoweredConfig); 2476 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig=" 2477 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig); 2478 pw.println(" mDreamsBatteryLevelDrainCutoffConfig=" 2479 + mDreamsBatteryLevelDrainCutoffConfig); 2480 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 2481 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 2482 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting); 2483 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig); 2484 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting); 2485 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured); 2486 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing); 2487 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig); 2488 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig); 2489 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig); 2490 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 2491 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting); 2492 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 2493 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 2494 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 2495 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 2496 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 2497 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 2498 + mScreenAutoBrightnessAdjustmentSetting); 2499 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 2500 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 2501 + mScreenBrightnessOverrideFromWindowManager); 2502 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 2503 + mUserActivityTimeoutOverrideFromWindowManager); 2504 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 2505 + mTemporaryScreenBrightnessSettingOverride); 2506 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 2507 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 2508 pw.println(" mDozeScreenStateOverrideFromDreamManager=" 2509 + mDozeScreenStateOverrideFromDreamManager); 2510 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager=" 2511 + mDozeScreenBrightnessOverrideFromDreamManager); 2512 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 2513 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 2514 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 2515 2516 final int sleepTimeout = getSleepTimeoutLocked(); 2517 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 2518 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 2519 pw.println(); 2520 pw.println("Sleep timeout: " + sleepTimeout + " ms"); 2521 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2522 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2523 2524 pw.println(); 2525 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2526 for (WakeLock wl : mWakeLocks) { 2527 pw.println(" " + wl); 2528 } 2529 2530 pw.println(); 2531 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2532 for (SuspendBlocker sb : mSuspendBlockers) { 2533 pw.println(" " + sb); 2534 } 2535 2536 pw.println(); 2537 pw.println("Display Power: " + mDisplayPowerCallbacks); 2538 2539 wcd = mWirelessChargerDetector; 2540 } 2541 2542 if (wcd != null) { 2543 wcd.dump(pw); 2544 } 2545 } 2546 2547 private SuspendBlocker createSuspendBlockerLocked(String name) { 2548 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2549 mSuspendBlockers.add(suspendBlocker); 2550 return suspendBlocker; 2551 } 2552 2553 private static WorkSource copyWorkSource(WorkSource workSource) { 2554 return workSource != null ? new WorkSource(workSource) : null; 2555 } 2556 2557 private final class BatteryReceiver extends BroadcastReceiver { 2558 @Override 2559 public void onReceive(Context context, Intent intent) { 2560 synchronized (mLock) { 2561 handleBatteryStateChangedLocked(); 2562 } 2563 } 2564 } 2565 2566 private final class DreamReceiver extends BroadcastReceiver { 2567 @Override 2568 public void onReceive(Context context, Intent intent) { 2569 synchronized (mLock) { 2570 scheduleSandmanLocked(); 2571 } 2572 } 2573 } 2574 2575 private final class UserSwitchedReceiver extends BroadcastReceiver { 2576 @Override 2577 public void onReceive(Context context, Intent intent) { 2578 synchronized (mLock) { 2579 handleSettingsChangedLocked(); 2580 } 2581 } 2582 } 2583 2584 private final class DockReceiver extends BroadcastReceiver { 2585 @Override 2586 public void onReceive(Context context, Intent intent) { 2587 synchronized (mLock) { 2588 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2589 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2590 if (mDockState != dockState) { 2591 mDockState = dockState; 2592 mDirty |= DIRTY_DOCK_STATE; 2593 updatePowerStateLocked(); 2594 } 2595 } 2596 } 2597 } 2598 2599 private final class SettingsObserver extends ContentObserver { 2600 public SettingsObserver(Handler handler) { 2601 super(handler); 2602 } 2603 2604 @Override 2605 public void onChange(boolean selfChange, Uri uri) { 2606 synchronized (mLock) { 2607 handleSettingsChangedLocked(); 2608 } 2609 } 2610 } 2611 2612 /** 2613 * Handler for asynchronous operations performed by the power manager. 2614 */ 2615 private final class PowerManagerHandler extends Handler { 2616 public PowerManagerHandler(Looper looper) { 2617 super(looper, null, true /*async*/); 2618 } 2619 2620 @Override 2621 public void handleMessage(Message msg) { 2622 switch (msg.what) { 2623 case MSG_USER_ACTIVITY_TIMEOUT: 2624 handleUserActivityTimeout(); 2625 break; 2626 case MSG_SANDMAN: 2627 handleSandman(); 2628 break; 2629 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT: 2630 handleScreenBrightnessBoostTimeout(); 2631 break; 2632 } 2633 } 2634 } 2635 2636 /** 2637 * Represents a wake lock that has been acquired by an application. 2638 */ 2639 private final class WakeLock implements IBinder.DeathRecipient { 2640 public final IBinder mLock; 2641 public int mFlags; 2642 public String mTag; 2643 public final String mPackageName; 2644 public WorkSource mWorkSource; 2645 public String mHistoryTag; 2646 public final int mOwnerUid; 2647 public final int mOwnerPid; 2648 public boolean mNotifiedAcquired; 2649 2650 public WakeLock(IBinder lock, int flags, String tag, String packageName, 2651 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 2652 mLock = lock; 2653 mFlags = flags; 2654 mTag = tag; 2655 mPackageName = packageName; 2656 mWorkSource = copyWorkSource(workSource); 2657 mHistoryTag = historyTag; 2658 mOwnerUid = ownerUid; 2659 mOwnerPid = ownerPid; 2660 } 2661 2662 @Override 2663 public void binderDied() { 2664 PowerManagerService.this.handleWakeLockDeath(this); 2665 } 2666 2667 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 2668 int ownerUid, int ownerPid) { 2669 return mFlags == flags 2670 && mTag.equals(tag) 2671 && hasSameWorkSource(workSource) 2672 && mOwnerUid == ownerUid 2673 && mOwnerPid == ownerPid; 2674 } 2675 2676 public void updateProperties(int flags, String tag, String packageName, 2677 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 2678 if (!mPackageName.equals(packageName)) { 2679 throw new IllegalStateException("Existing wake lock package name changed: " 2680 + mPackageName + " to " + packageName); 2681 } 2682 if (mOwnerUid != ownerUid) { 2683 throw new IllegalStateException("Existing wake lock uid changed: " 2684 + mOwnerUid + " to " + ownerUid); 2685 } 2686 if (mOwnerPid != ownerPid) { 2687 throw new IllegalStateException("Existing wake lock pid changed: " 2688 + mOwnerPid + " to " + ownerPid); 2689 } 2690 mFlags = flags; 2691 mTag = tag; 2692 updateWorkSource(workSource); 2693 mHistoryTag = historyTag; 2694 } 2695 2696 public boolean hasSameWorkSource(WorkSource workSource) { 2697 return Objects.equal(mWorkSource, workSource); 2698 } 2699 2700 public void updateWorkSource(WorkSource workSource) { 2701 mWorkSource = copyWorkSource(workSource); 2702 } 2703 2704 @Override 2705 public String toString() { 2706 return getLockLevelString() 2707 + " '" + mTag + "'" + getLockFlagsString() 2708 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2709 } 2710 2711 @SuppressWarnings("deprecation") 2712 private String getLockLevelString() { 2713 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2714 case PowerManager.FULL_WAKE_LOCK: 2715 return "FULL_WAKE_LOCK "; 2716 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2717 return "SCREEN_BRIGHT_WAKE_LOCK "; 2718 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2719 return "SCREEN_DIM_WAKE_LOCK "; 2720 case PowerManager.PARTIAL_WAKE_LOCK: 2721 return "PARTIAL_WAKE_LOCK "; 2722 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2723 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2724 case PowerManager.DOZE_WAKE_LOCK: 2725 return "DOZE_WAKE_LOCK "; 2726 case PowerManager.DRAW_WAKE_LOCK: 2727 return "DRAW_WAKE_LOCK "; 2728 default: 2729 return "??? "; 2730 } 2731 } 2732 2733 private String getLockFlagsString() { 2734 String result = ""; 2735 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2736 result += " ACQUIRE_CAUSES_WAKEUP"; 2737 } 2738 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2739 result += " ON_AFTER_RELEASE"; 2740 } 2741 return result; 2742 } 2743 } 2744 2745 private final class SuspendBlockerImpl implements SuspendBlocker { 2746 private final String mName; 2747 private final String mTraceName; 2748 private int mReferenceCount; 2749 2750 public SuspendBlockerImpl(String name) { 2751 mName = name; 2752 mTraceName = "SuspendBlocker (" + name + ")"; 2753 } 2754 2755 @Override 2756 protected void finalize() throws Throwable { 2757 try { 2758 if (mReferenceCount != 0) { 2759 Slog.wtf(TAG, "Suspend blocker \"" + mName 2760 + "\" was finalized without being released!"); 2761 mReferenceCount = 0; 2762 nativeReleaseSuspendBlocker(mName); 2763 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 2764 } 2765 } finally { 2766 super.finalize(); 2767 } 2768 } 2769 2770 @Override 2771 public void acquire() { 2772 synchronized (this) { 2773 mReferenceCount += 1; 2774 if (mReferenceCount == 1) { 2775 if (DEBUG_SPEW) { 2776 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\"."); 2777 } 2778 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0); 2779 nativeAcquireSuspendBlocker(mName); 2780 } 2781 } 2782 } 2783 2784 @Override 2785 public void release() { 2786 synchronized (this) { 2787 mReferenceCount -= 1; 2788 if (mReferenceCount == 0) { 2789 if (DEBUG_SPEW) { 2790 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\"."); 2791 } 2792 nativeReleaseSuspendBlocker(mName); 2793 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 2794 } else if (mReferenceCount < 0) { 2795 Slog.wtf(TAG, "Suspend blocker \"" + mName 2796 + "\" was released without being acquired!", new Throwable()); 2797 mReferenceCount = 0; 2798 } 2799 } 2800 } 2801 2802 @Override 2803 public String toString() { 2804 synchronized (this) { 2805 return mName + ": ref count=" + mReferenceCount; 2806 } 2807 } 2808 } 2809 2810 private final class BinderService extends IPowerManager.Stub { 2811 @Override // Binder call 2812 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag, 2813 String packageName, int uid) { 2814 if (uid < 0) { 2815 uid = Binder.getCallingUid(); 2816 } 2817 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null); 2818 } 2819 2820 @Override // Binder call 2821 public void powerHint(int hintId, int data) { 2822 if (!mSystemReady) { 2823 // Service not ready yet, so who the heck cares about power hints, bah. 2824 return; 2825 } 2826 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2827 powerHintInternal(hintId, data); 2828 } 2829 2830 @Override // Binder call 2831 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName, 2832 WorkSource ws, String historyTag) { 2833 if (lock == null) { 2834 throw new IllegalArgumentException("lock must not be null"); 2835 } 2836 if (packageName == null) { 2837 throw new IllegalArgumentException("packageName must not be null"); 2838 } 2839 PowerManager.validateWakeLockParameters(flags, tag); 2840 2841 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2842 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) { 2843 mContext.enforceCallingOrSelfPermission( 2844 android.Manifest.permission.DEVICE_POWER, null); 2845 } 2846 if (ws != null && ws.size() != 0) { 2847 mContext.enforceCallingOrSelfPermission( 2848 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 2849 } else { 2850 ws = null; 2851 } 2852 2853 final int uid = Binder.getCallingUid(); 2854 final int pid = Binder.getCallingPid(); 2855 final long ident = Binder.clearCallingIdentity(); 2856 try { 2857 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid); 2858 } finally { 2859 Binder.restoreCallingIdentity(ident); 2860 } 2861 } 2862 2863 @Override // Binder call 2864 public void releaseWakeLock(IBinder lock, int flags) { 2865 if (lock == null) { 2866 throw new IllegalArgumentException("lock must not be null"); 2867 } 2868 2869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2870 2871 final long ident = Binder.clearCallingIdentity(); 2872 try { 2873 releaseWakeLockInternal(lock, flags); 2874 } finally { 2875 Binder.restoreCallingIdentity(ident); 2876 } 2877 } 2878 2879 @Override // Binder call 2880 public void updateWakeLockUids(IBinder lock, int[] uids) { 2881 WorkSource ws = null; 2882 2883 if (uids != null) { 2884 ws = new WorkSource(); 2885 // XXX should WorkSource have a way to set uids as an int[] instead of adding them 2886 // one at a time? 2887 for (int i = 0; i < uids.length; i++) { 2888 ws.add(uids[i]); 2889 } 2890 } 2891 updateWakeLockWorkSource(lock, ws, null); 2892 } 2893 2894 @Override // Binder call 2895 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) { 2896 if (lock == null) { 2897 throw new IllegalArgumentException("lock must not be null"); 2898 } 2899 2900 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2901 if (ws != null && ws.size() != 0) { 2902 mContext.enforceCallingOrSelfPermission( 2903 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 2904 } else { 2905 ws = null; 2906 } 2907 2908 final int callingUid = Binder.getCallingUid(); 2909 final long ident = Binder.clearCallingIdentity(); 2910 try { 2911 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid); 2912 } finally { 2913 Binder.restoreCallingIdentity(ident); 2914 } 2915 } 2916 2917 @Override // Binder call 2918 public boolean isWakeLockLevelSupported(int level) { 2919 final long ident = Binder.clearCallingIdentity(); 2920 try { 2921 return isWakeLockLevelSupportedInternal(level); 2922 } finally { 2923 Binder.restoreCallingIdentity(ident); 2924 } 2925 } 2926 2927 @Override // Binder call 2928 public void userActivity(long eventTime, int event, int flags) { 2929 final long now = SystemClock.uptimeMillis(); 2930 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 2931 != PackageManager.PERMISSION_GRANTED 2932 && mContext.checkCallingOrSelfPermission( 2933 android.Manifest.permission.USER_ACTIVITY) 2934 != PackageManager.PERMISSION_GRANTED) { 2935 // Once upon a time applications could call userActivity(). 2936 // Now we require the DEVICE_POWER permission. Log a warning and ignore the 2937 // request instead of throwing a SecurityException so we don't break old apps. 2938 synchronized (mLock) { 2939 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) { 2940 mLastWarningAboutUserActivityPermission = now; 2941 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the " 2942 + "caller does not have DEVICE_POWER or USER_ACTIVITY " 2943 + "permission. Please fix your app! " 2944 + " pid=" + Binder.getCallingPid() 2945 + " uid=" + Binder.getCallingUid()); 2946 } 2947 } 2948 return; 2949 } 2950 2951 if (eventTime > SystemClock.uptimeMillis()) { 2952 throw new IllegalArgumentException("event time must not be in the future"); 2953 } 2954 2955 final int uid = Binder.getCallingUid(); 2956 final long ident = Binder.clearCallingIdentity(); 2957 try { 2958 userActivityInternal(eventTime, event, flags, uid); 2959 } finally { 2960 Binder.restoreCallingIdentity(ident); 2961 } 2962 } 2963 2964 @Override // Binder call 2965 public void wakeUp(long eventTime) { 2966 if (eventTime > SystemClock.uptimeMillis()) { 2967 throw new IllegalArgumentException("event time must not be in the future"); 2968 } 2969 2970 mContext.enforceCallingOrSelfPermission( 2971 android.Manifest.permission.DEVICE_POWER, null); 2972 2973 final int uid = Binder.getCallingUid(); 2974 final long ident = Binder.clearCallingIdentity(); 2975 try { 2976 wakeUpInternal(eventTime, uid); 2977 } finally { 2978 Binder.restoreCallingIdentity(ident); 2979 } 2980 } 2981 2982 @Override // Binder call 2983 public void goToSleep(long eventTime, int reason, int flags) { 2984 if (eventTime > SystemClock.uptimeMillis()) { 2985 throw new IllegalArgumentException("event time must not be in the future"); 2986 } 2987 2988 mContext.enforceCallingOrSelfPermission( 2989 android.Manifest.permission.DEVICE_POWER, null); 2990 2991 final int uid = Binder.getCallingUid(); 2992 final long ident = Binder.clearCallingIdentity(); 2993 try { 2994 goToSleepInternal(eventTime, reason, flags, uid); 2995 } finally { 2996 Binder.restoreCallingIdentity(ident); 2997 } 2998 } 2999 3000 @Override // Binder call 3001 public void nap(long eventTime) { 3002 if (eventTime > SystemClock.uptimeMillis()) { 3003 throw new IllegalArgumentException("event time must not be in the future"); 3004 } 3005 3006 mContext.enforceCallingOrSelfPermission( 3007 android.Manifest.permission.DEVICE_POWER, null); 3008 3009 final int uid = Binder.getCallingUid(); 3010 final long ident = Binder.clearCallingIdentity(); 3011 try { 3012 napInternal(eventTime, uid); 3013 } finally { 3014 Binder.restoreCallingIdentity(ident); 3015 } 3016 } 3017 3018 @Override // Binder call 3019 public boolean isInteractive() { 3020 final long ident = Binder.clearCallingIdentity(); 3021 try { 3022 return isInteractiveInternal(); 3023 } finally { 3024 Binder.restoreCallingIdentity(ident); 3025 } 3026 } 3027 3028 @Override // Binder call 3029 public boolean isPowerSaveMode() { 3030 final long ident = Binder.clearCallingIdentity(); 3031 try { 3032 return isLowPowerModeInternal(); 3033 } finally { 3034 Binder.restoreCallingIdentity(ident); 3035 } 3036 } 3037 3038 @Override // Binder call 3039 public boolean setPowerSaveMode(boolean mode) { 3040 mContext.enforceCallingOrSelfPermission( 3041 android.Manifest.permission.DEVICE_POWER, null); 3042 final long ident = Binder.clearCallingIdentity(); 3043 try { 3044 return setLowPowerModeInternal(mode); 3045 } finally { 3046 Binder.restoreCallingIdentity(ident); 3047 } 3048 } 3049 3050 /** 3051 * Reboots the device. 3052 * 3053 * @param confirm If true, shows a reboot confirmation dialog. 3054 * @param reason The reason for the reboot, or null if none. 3055 * @param wait If true, this call waits for the reboot to complete and does not return. 3056 */ 3057 @Override // Binder call 3058 public void reboot(boolean confirm, String reason, boolean wait) { 3059 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3060 if (PowerManager.REBOOT_RECOVERY.equals(reason)) { 3061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null); 3062 } 3063 3064 final long ident = Binder.clearCallingIdentity(); 3065 try { 3066 shutdownOrRebootInternal(false, confirm, reason, wait); 3067 } finally { 3068 Binder.restoreCallingIdentity(ident); 3069 } 3070 } 3071 3072 /** 3073 * Shuts down the device. 3074 * 3075 * @param confirm If true, shows a shutdown confirmation dialog. 3076 * @param wait If true, this call waits for the shutdown to complete and does not return. 3077 */ 3078 @Override // Binder call 3079 public void shutdown(boolean confirm, boolean wait) { 3080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3081 3082 final long ident = Binder.clearCallingIdentity(); 3083 try { 3084 shutdownOrRebootInternal(true, confirm, null, wait); 3085 } finally { 3086 Binder.restoreCallingIdentity(ident); 3087 } 3088 } 3089 3090 /** 3091 * Crash the runtime (causing a complete restart of the Android framework). 3092 * Requires REBOOT permission. Mostly for testing. Should not return. 3093 */ 3094 @Override // Binder call 3095 public void crash(String message) { 3096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3097 3098 final long ident = Binder.clearCallingIdentity(); 3099 try { 3100 crashInternal(message); 3101 } finally { 3102 Binder.restoreCallingIdentity(ident); 3103 } 3104 } 3105 3106 /** 3107 * Set the setting that determines whether the device stays on when plugged in. 3108 * The argument is a bit string, with each bit specifying a power source that, 3109 * when the device is connected to that source, causes the device to stay on. 3110 * See {@link android.os.BatteryManager} for the list of power sources that 3111 * can be specified. Current values include 3112 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 3113 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 3114 * 3115 * Used by "adb shell svc power stayon ..." 3116 * 3117 * @param val an {@code int} containing the bits that specify which power sources 3118 * should cause the device to stay on. 3119 */ 3120 @Override // Binder call 3121 public void setStayOnSetting(int val) { 3122 mContext.enforceCallingOrSelfPermission( 3123 android.Manifest.permission.WRITE_SETTINGS, null); 3124 3125 final long ident = Binder.clearCallingIdentity(); 3126 try { 3127 setStayOnSettingInternal(val); 3128 } finally { 3129 Binder.restoreCallingIdentity(ident); 3130 } 3131 } 3132 3133 /** 3134 * Used by the settings application and brightness control widgets to 3135 * temporarily override the current screen brightness setting so that the 3136 * user can observe the effect of an intended settings change without applying 3137 * it immediately. 3138 * 3139 * The override will be canceled when the setting value is next updated. 3140 * 3141 * @param brightness The overridden brightness. 3142 * 3143 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS 3144 */ 3145 @Override // Binder call 3146 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 3147 mContext.enforceCallingOrSelfPermission( 3148 android.Manifest.permission.DEVICE_POWER, null); 3149 3150 final long ident = Binder.clearCallingIdentity(); 3151 try { 3152 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 3153 } finally { 3154 Binder.restoreCallingIdentity(ident); 3155 } 3156 } 3157 3158 /** 3159 * Used by the settings application and brightness control widgets to 3160 * temporarily override the current screen auto-brightness adjustment setting so that the 3161 * user can observe the effect of an intended settings change without applying 3162 * it immediately. 3163 * 3164 * The override will be canceled when the setting value is next updated. 3165 * 3166 * @param adj The overridden brightness, or Float.NaN to disable the override. 3167 * 3168 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 3169 */ 3170 @Override // Binder call 3171 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 3172 mContext.enforceCallingOrSelfPermission( 3173 android.Manifest.permission.DEVICE_POWER, null); 3174 3175 final long ident = Binder.clearCallingIdentity(); 3176 try { 3177 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 3178 } finally { 3179 Binder.restoreCallingIdentity(ident); 3180 } 3181 } 3182 3183 /** 3184 * Used by the phone application to make the attention LED flash when ringing. 3185 */ 3186 @Override // Binder call 3187 public void setAttentionLight(boolean on, int color) { 3188 mContext.enforceCallingOrSelfPermission( 3189 android.Manifest.permission.DEVICE_POWER, null); 3190 3191 final long ident = Binder.clearCallingIdentity(); 3192 try { 3193 setAttentionLightInternal(on, color); 3194 } finally { 3195 Binder.restoreCallingIdentity(ident); 3196 } 3197 } 3198 3199 @Override // Binder call 3200 public void boostScreenBrightness(long eventTime) { 3201 if (eventTime > SystemClock.uptimeMillis()) { 3202 throw new IllegalArgumentException("event time must not be in the future"); 3203 } 3204 3205 mContext.enforceCallingOrSelfPermission( 3206 android.Manifest.permission.DEVICE_POWER, null); 3207 3208 final int uid = Binder.getCallingUid(); 3209 final long ident = Binder.clearCallingIdentity(); 3210 try { 3211 boostScreenBrightnessInternal(eventTime, uid); 3212 } finally { 3213 Binder.restoreCallingIdentity(ident); 3214 } 3215 } 3216 3217 @Override // Binder call 3218 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3219 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 3220 != PackageManager.PERMISSION_GRANTED) { 3221 pw.println("Permission Denial: can't dump PowerManager from from pid=" 3222 + Binder.getCallingPid() 3223 + ", uid=" + Binder.getCallingUid()); 3224 return; 3225 } 3226 3227 final long ident = Binder.clearCallingIdentity(); 3228 try { 3229 dumpInternal(pw); 3230 } finally { 3231 Binder.restoreCallingIdentity(ident); 3232 } 3233 } 3234 } 3235 3236 private final class LocalService extends PowerManagerInternal { 3237 @Override 3238 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) { 3239 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3240 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3241 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3242 } 3243 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness); 3244 } 3245 3246 @Override 3247 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) { 3248 // Do nothing. 3249 // Button lights are not currently supported in the new implementation. 3250 } 3251 3252 @Override 3253 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) { 3254 switch (screenState) { 3255 case Display.STATE_UNKNOWN: 3256 case Display.STATE_OFF: 3257 case Display.STATE_DOZE: 3258 case Display.STATE_DOZE_SUSPEND: 3259 case Display.STATE_ON: 3260 break; 3261 default: 3262 screenState = Display.STATE_UNKNOWN; 3263 break; 3264 } 3265 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3266 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3267 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3268 } 3269 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness); 3270 } 3271 3272 @Override 3273 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 3274 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 3275 } 3276 3277 @Override 3278 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 3279 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 3280 } 3281 3282 @Override 3283 public boolean getLowPowerModeEnabled() { 3284 synchronized (mLock) { 3285 return mLowPowerModeEnabled; 3286 } 3287 } 3288 3289 @Override 3290 public void registerLowPowerModeObserver(LowPowerModeListener listener) { 3291 synchronized (mLock) { 3292 mLowPowerModeListeners.add(listener); 3293 } 3294 } 3295 } 3296} 3297