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