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