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