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