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