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