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