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