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