PowerManagerService.java revision ff532540f18e3b2181da0550fe55045418a3b84e
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 // Also used when exiting a dream to determine whether we should go back 1286 // to being fully awake or else go to sleep for good. 1287 private boolean isItBedTimeYetLocked() { 1288 return mBootCompleted && !mStayOn 1289 && (mWakeLockSummary 1290 & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM 1291 | WAKE_LOCK_PROXIMITY_SCREEN_OFF)) == 0 1292 && (mUserActivitySummary 1293 & (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) == 0; 1294 } 1295 1296 /** 1297 * Determines whether to post a message to the sandman to update the dream state. 1298 */ 1299 private void updateDreamLocked(int dirty) { 1300 if ((dirty & (DIRTY_WAKEFULNESS 1301 | DIRTY_SETTINGS 1302 | DIRTY_IS_POWERED 1303 | DIRTY_STAY_ON 1304 | DIRTY_BATTERY_STATE)) != 0) { 1305 scheduleSandmanLocked(); 1306 } 1307 } 1308 1309 private void scheduleSandmanLocked() { 1310 if (!mSandmanScheduled) { 1311 mSandmanScheduled = true; 1312 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1313 msg.setAsynchronous(true); 1314 mHandler.sendMessage(msg); 1315 } 1316 } 1317 1318 /** 1319 * Called when the device enters or exits a napping or dreaming state. 1320 * 1321 * We do this asynchronously because we must call out of the power manager to start 1322 * the dream and we don't want to hold our lock while doing so. There is a risk that 1323 * the device will wake or go to sleep in the meantime so we have to handle that case. 1324 */ 1325 private void handleSandman() { // runs on handler thread 1326 // Handle preconditions. 1327 boolean startDreaming = false; 1328 synchronized (mLock) { 1329 mSandmanScheduled = false; 1330 boolean canDream = canDreamLocked(); 1331 if (DEBUG_SPEW) { 1332 Log.d(TAG, "handleSandman: canDream=" + canDream 1333 + ", mWakefulness=" + wakefulnessToString(mWakefulness)); 1334 } 1335 1336 if (canDream && mWakefulness == WAKEFULNESS_NAPPING) { 1337 startDreaming = true; 1338 } 1339 } 1340 1341 // Start dreaming if needed. 1342 // We only control the dream on the handler thread, so we don't need to worry about 1343 // concurrent attempts to start or stop the dream. 1344 boolean isDreaming = false; 1345 if (mDreamManager != null) { 1346 if (startDreaming) { 1347 mDreamManager.startDream(); 1348 } 1349 isDreaming = mDreamManager.isDreaming(); 1350 } 1351 1352 // Update dream state. 1353 // We might need to stop the dream again if the preconditions changed. 1354 boolean continueDreaming = false; 1355 synchronized (mLock) { 1356 if (isDreaming && canDreamLocked()) { 1357 if (mWakefulness == WAKEFULNESS_NAPPING) { 1358 mWakefulness = WAKEFULNESS_DREAMING; 1359 mDirty |= DIRTY_WAKEFULNESS; 1360 updatePowerStateLocked(); 1361 continueDreaming = true; 1362 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1363 continueDreaming = true; 1364 } 1365 } 1366 if (!continueDreaming) { 1367 handleDreamFinishedLocked(); 1368 } 1369 } 1370 1371 // Stop dreaming if needed. 1372 // It's possible that something else changed to make us need to start the dream again. 1373 // If so, then the power manager will have posted another message to the handler 1374 // to take care of it later. 1375 if (mDreamManager != null) { 1376 if (!continueDreaming) { 1377 mDreamManager.stopDream(); 1378 } 1379 } 1380 } 1381 1382 /** 1383 * Returns true if the device is allowed to dream in its current state, 1384 * assuming that there was either an explicit request to nap or the user activity 1385 * timeout expired and no wake locks are held. 1386 */ 1387 private boolean canDreamLocked() { 1388 return mIsPowered 1389 && mDreamsSupportedConfig 1390 && mDreamsEnabledSetting 1391 && mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF; 1392 } 1393 1394 /** 1395 * Called when a dream is ending to figure out what to do next. 1396 */ 1397 private void handleDreamFinishedLocked() { 1398 if (mWakefulness == WAKEFULNESS_NAPPING 1399 || mWakefulness == WAKEFULNESS_DREAMING) { 1400 if (isItBedTimeYetLocked()) { 1401 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1402 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1403 updatePowerStateLocked(); 1404 } else { 1405 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 1406 updatePowerStateLocked(); 1407 } 1408 } 1409 } 1410 1411 /** 1412 * Updates the display power state asynchronously. 1413 * When the update is finished, mDisplayReady will be set to true. The display 1414 * controller posts a message to tell us when the actual display power state 1415 * has been updated so we come back here to double-check and finish up. 1416 * 1417 * This function recalculates the display power state each time. 1418 */ 1419 private void updateDisplayPowerStateLocked(int dirty) { 1420 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1421 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1422 | DIRTY_SETTINGS)) != 0) { 1423 int newScreenState = getDesiredScreenPowerState(); 1424 if (newScreenState != mDisplayPowerRequest.screenState) { 1425 if (newScreenState == DisplayPowerRequest.SCREEN_STATE_OFF 1426 && mDisplayPowerRequest.screenState 1427 != DisplayPowerRequest.SCREEN_STATE_OFF) { 1428 mLastScreenOffEventElapsedRealTime = SystemClock.elapsedRealtime(); 1429 } 1430 1431 mDisplayPowerRequest.screenState = newScreenState; 1432 nativeSetPowerState( 1433 newScreenState != DisplayPowerRequest.SCREEN_STATE_OFF, 1434 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT); 1435 } 1436 1437 int screenBrightness = mScreenBrightnessSettingDefault; 1438 float screenAutoBrightnessAdjustment = 0.0f; 1439 boolean autoBrightness = (mScreenBrightnessModeSetting == 1440 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1441 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1442 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1443 autoBrightness = false; 1444 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1445 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1446 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1447 screenBrightness = mScreenBrightnessSetting; 1448 } 1449 if (autoBrightness) { 1450 screenBrightness = mScreenBrightnessSettingDefault; 1451 if (isValidAutoBrightnessAdjustment( 1452 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1453 screenAutoBrightnessAdjustment = 1454 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1455 } else if (isValidAutoBrightnessAdjustment( 1456 mScreenAutoBrightnessAdjustmentSetting)) { 1457 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1458 } 1459 } 1460 screenBrightness = Math.max(Math.min(screenBrightness, 1461 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1462 screenAutoBrightnessAdjustment = Math.max(Math.min( 1463 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1464 mDisplayPowerRequest.screenBrightness = screenBrightness; 1465 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1466 screenAutoBrightnessAdjustment; 1467 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1468 1469 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1470 1471 mDisplayReady = mDisplayPowerController.requestPowerState(mDisplayPowerRequest, 1472 mRequestWaitForNegativeProximity); 1473 mRequestWaitForNegativeProximity = false; 1474 1475 if (DEBUG_SPEW) { 1476 Slog.d(TAG, "updateScreenStateLocked: displayReady=" + mDisplayReady 1477 + ", newScreenState=" + newScreenState 1478 + ", mWakefulness=" + mWakefulness 1479 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1480 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1481 + ", mBootCompleted=" + mBootCompleted); 1482 } 1483 } 1484 } 1485 1486 private static boolean isValidBrightness(int value) { 1487 return value >= 0 && value <= 255; 1488 } 1489 1490 private static boolean isValidAutoBrightnessAdjustment(float value) { 1491 // Handles NaN by always returning false. 1492 return value >= -1.0f && value <= 1.0f; 1493 } 1494 1495 private int getDesiredScreenPowerState() { 1496 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1497 return DisplayPowerRequest.SCREEN_STATE_OFF; 1498 } 1499 1500 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1501 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1502 || !mBootCompleted) { 1503 return DisplayPowerRequest.SCREEN_STATE_BRIGHT; 1504 } 1505 1506 return DisplayPowerRequest.SCREEN_STATE_DIM; 1507 } 1508 1509 private final DisplayPowerController.Callbacks mDisplayPowerControllerCallbacks = 1510 new DisplayPowerController.Callbacks() { 1511 @Override 1512 public void onStateChanged() { 1513 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1514 updatePowerStateLocked(); 1515 } 1516 1517 @Override 1518 public void onProximityNegative() { 1519 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1520 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1521 updatePowerStateLocked(); 1522 } 1523 }; 1524 1525 private boolean shouldUseProximitySensorLocked() { 1526 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 1527 } 1528 1529 /** 1530 * Updates the suspend blocker that keeps the CPU alive. 1531 * 1532 * This function must have no other side-effects. 1533 */ 1534 private void updateSuspendBlockerLocked() { 1535 boolean wantCpu = isCpuNeededLocked(); 1536 if (wantCpu != mHoldingWakeLockSuspendBlocker) { 1537 mHoldingWakeLockSuspendBlocker = wantCpu; 1538 if (wantCpu) { 1539 if (DEBUG) { 1540 Slog.d(TAG, "updateSuspendBlockerLocked: Acquiring suspend blocker."); 1541 } 1542 mWakeLockSuspendBlocker.acquire(); 1543 } else { 1544 if (DEBUG) { 1545 Slog.d(TAG, "updateSuspendBlockerLocked: Releasing suspend blocker."); 1546 } 1547 mWakeLockSuspendBlocker.release(); 1548 } 1549 } 1550 } 1551 1552 private boolean isCpuNeededLocked() { 1553 return !mBootCompleted 1554 || mWakeLockSummary != 0 1555 || mUserActivitySummary != 0 1556 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF 1557 || !mDisplayReady; 1558 } 1559 1560 @Override // Binder call 1561 public boolean isScreenOn() { 1562 final long ident = Binder.clearCallingIdentity(); 1563 try { 1564 return isScreenOnInternal(); 1565 } finally { 1566 Binder.restoreCallingIdentity(ident); 1567 } 1568 } 1569 1570 private boolean isScreenOnInternal() { 1571 synchronized (mLock) { 1572 return !mSystemReady 1573 || mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF; 1574 } 1575 } 1576 1577 private void handleBatteryStateChangedLocked() { 1578 mDirty |= DIRTY_BATTERY_STATE; 1579 updatePowerStateLocked(); 1580 } 1581 1582 private void handleBootCompletedLocked() { 1583 final long now = SystemClock.uptimeMillis(); 1584 mBootCompleted = true; 1585 mDirty |= DIRTY_BOOT_COMPLETED; 1586 userActivityNoUpdateLocked( 1587 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1588 updatePowerStateLocked(); 1589 } 1590 1591 /** 1592 * Reboot the device immediately, passing 'reason' (may be null) 1593 * to the underlying __reboot system call. Should not return. 1594 */ 1595 @Override // Binder call 1596 public void reboot(String reason) { 1597 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1598 1599 final long ident = Binder.clearCallingIdentity(); 1600 try { 1601 rebootInternal(reason); 1602 } finally { 1603 Binder.restoreCallingIdentity(ident); 1604 } 1605 } 1606 1607 private void rebootInternal(final String reason) { 1608 if (mHandler == null || !mSystemReady) { 1609 throw new IllegalStateException("Too early to call reboot()"); 1610 } 1611 1612 Runnable runnable = new Runnable() { 1613 public void run() { 1614 synchronized (this) { 1615 ShutdownThread.reboot(mContext, reason, false); 1616 } 1617 } 1618 }; 1619 1620 // ShutdownThread must run on a looper capable of displaying the UI. 1621 Message msg = Message.obtain(mHandler, runnable); 1622 msg.setAsynchronous(true); 1623 mHandler.sendMessage(msg); 1624 1625 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 1626 synchronized (runnable) { 1627 while (true) { 1628 try { 1629 runnable.wait(); 1630 } catch (InterruptedException e) { 1631 } 1632 } 1633 } 1634 } 1635 1636 /** 1637 * Crash the runtime (causing a complete restart of the Android framework). 1638 * Requires REBOOT permission. Mostly for testing. Should not return. 1639 */ 1640 @Override // Binder call 1641 public void crash(String message) { 1642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 1643 1644 final long ident = Binder.clearCallingIdentity(); 1645 try { 1646 crashInternal(message); 1647 } finally { 1648 Binder.restoreCallingIdentity(ident); 1649 } 1650 } 1651 1652 private void crashInternal(final String message) { 1653 Thread t = new Thread("PowerManagerService.crash()") { 1654 public void run() { 1655 throw new RuntimeException(message); 1656 } 1657 }; 1658 try { 1659 t.start(); 1660 t.join(); 1661 } catch (InterruptedException e) { 1662 Log.wtf(TAG, e); 1663 } 1664 } 1665 1666 /** 1667 * Set the setting that determines whether the device stays on when plugged in. 1668 * The argument is a bit string, with each bit specifying a power source that, 1669 * when the device is connected to that source, causes the device to stay on. 1670 * See {@link android.os.BatteryManager} for the list of power sources that 1671 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 1672 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 1673 * 1674 * Used by "adb shell svc power stayon ..." 1675 * 1676 * @param val an {@code int} containing the bits that specify which power sources 1677 * should cause the device to stay on. 1678 */ 1679 @Override // Binder call 1680 public void setStayOnSetting(int val) { 1681 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null); 1682 1683 final long ident = Binder.clearCallingIdentity(); 1684 try { 1685 setStayOnSettingInternal(val); 1686 } finally { 1687 Binder.restoreCallingIdentity(ident); 1688 } 1689 } 1690 1691 private void setStayOnSettingInternal(int val) { 1692 Settings.Global.putInt(mContext.getContentResolver(), 1693 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 1694 } 1695 1696 /** 1697 * Used by device administration to set the maximum screen off timeout. 1698 * 1699 * This method must only be called by the device administration policy manager. 1700 */ 1701 @Override // Binder call 1702 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 1703 final long ident = Binder.clearCallingIdentity(); 1704 try { 1705 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 1706 } finally { 1707 Binder.restoreCallingIdentity(ident); 1708 } 1709 } 1710 1711 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 1712 synchronized (mLock) { 1713 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 1714 mDirty |= DIRTY_SETTINGS; 1715 updatePowerStateLocked(); 1716 } 1717 } 1718 1719 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 1720 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 1721 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 1722 } 1723 1724 /** 1725 * Used by the phone application to make the attention LED flash when ringing. 1726 */ 1727 @Override // Binder call 1728 public void setAttentionLight(boolean on, int color) { 1729 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1730 1731 final long ident = Binder.clearCallingIdentity(); 1732 try { 1733 setAttentionLightInternal(on, color); 1734 } finally { 1735 Binder.restoreCallingIdentity(ident); 1736 } 1737 } 1738 1739 private void setAttentionLightInternal(boolean on, int color) { 1740 LightsService.Light light; 1741 synchronized (mLock) { 1742 if (!mSystemReady) { 1743 return; 1744 } 1745 light = mAttentionLight; 1746 } 1747 1748 // Control light outside of lock. 1749 light.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 1750 } 1751 1752 /** 1753 * Used by the Watchdog. 1754 */ 1755 public long timeSinceScreenWasLastOn() { 1756 synchronized (mLock) { 1757 if (mDisplayPowerRequest.screenState != DisplayPowerRequest.SCREEN_STATE_OFF) { 1758 return 0; 1759 } 1760 return SystemClock.elapsedRealtime() - mLastScreenOffEventElapsedRealTime; 1761 } 1762 } 1763 1764 /** 1765 * Used by the window manager to override the screen brightness based on the 1766 * current foreground activity. 1767 * 1768 * This method must only be called by the window manager. 1769 * 1770 * @param brightness The overridden brightness, or -1 to disable the override. 1771 */ 1772 public void setScreenBrightnessOverrideFromWindowManager(int brightness) { 1773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1774 1775 final long ident = Binder.clearCallingIdentity(); 1776 try { 1777 setScreenBrightnessOverrideFromWindowManagerInternal(brightness); 1778 } finally { 1779 Binder.restoreCallingIdentity(ident); 1780 } 1781 } 1782 1783 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 1784 synchronized (mLock) { 1785 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 1786 mScreenBrightnessOverrideFromWindowManager = brightness; 1787 mDirty |= DIRTY_SETTINGS; 1788 updatePowerStateLocked(); 1789 } 1790 } 1791 } 1792 1793 /** 1794 * Used by the window manager to override the button brightness based on the 1795 * current foreground activity. 1796 * 1797 * This method must only be called by the window manager. 1798 * 1799 * @param brightness The overridden brightness, or -1 to disable the override. 1800 */ 1801 public void setButtonBrightnessOverrideFromWindowManager(int brightness) { 1802 // Do nothing. 1803 // Button lights are not currently supported in the new implementation. 1804 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1805 } 1806 1807 /** 1808 * Used by the window manager to override the user activity timeout based on the 1809 * current foreground activity. It can only be used to make the timeout shorter 1810 * than usual, not longer. 1811 * 1812 * This method must only be called by the window manager. 1813 * 1814 * @param timeoutMillis The overridden timeout, or -1 to disable the override. 1815 */ 1816 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 1817 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1818 1819 final long ident = Binder.clearCallingIdentity(); 1820 try { 1821 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 1822 } finally { 1823 Binder.restoreCallingIdentity(ident); 1824 } 1825 } 1826 1827 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 1828 synchronized (mLock) { 1829 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 1830 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 1831 mDirty |= DIRTY_SETTINGS; 1832 updatePowerStateLocked(); 1833 } 1834 } 1835 } 1836 1837 /** 1838 * Used by the settings application and brightness control widgets to 1839 * temporarily override the current screen brightness setting so that the 1840 * user can observe the effect of an intended settings change without applying 1841 * it immediately. 1842 * 1843 * The override will be canceled when the setting value is next updated. 1844 * 1845 * @param brightness The overridden brightness. 1846 * 1847 * @see Settings.System#SCREEN_BRIGHTNESS 1848 */ 1849 @Override // Binder call 1850 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 1851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1852 1853 final long ident = Binder.clearCallingIdentity(); 1854 try { 1855 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 1856 } finally { 1857 Binder.restoreCallingIdentity(ident); 1858 } 1859 } 1860 1861 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 1862 synchronized (mLock) { 1863 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 1864 mTemporaryScreenBrightnessSettingOverride = brightness; 1865 mDirty |= DIRTY_SETTINGS; 1866 updatePowerStateLocked(); 1867 } 1868 } 1869 } 1870 1871 /** 1872 * Used by the settings application and brightness control widgets to 1873 * temporarily override the current screen auto-brightness adjustment setting so that the 1874 * user can observe the effect of an intended settings change without applying 1875 * it immediately. 1876 * 1877 * The override will be canceled when the setting value is next updated. 1878 * 1879 * @param adj The overridden brightness, or Float.NaN to disable the override. 1880 * 1881 * @see Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 1882 */ 1883 @Override // Binder call 1884 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 1885 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1886 1887 final long ident = Binder.clearCallingIdentity(); 1888 try { 1889 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 1890 } finally { 1891 Binder.restoreCallingIdentity(ident); 1892 } 1893 } 1894 1895 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 1896 synchronized (mLock) { 1897 // Note: This condition handles NaN because NaN is not equal to any other 1898 // value, including itself. 1899 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 1900 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 1901 mDirty |= DIRTY_SETTINGS; 1902 updatePowerStateLocked(); 1903 } 1904 } 1905 } 1906 1907 /** 1908 * Low-level function turn the device off immediately, without trying 1909 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 1910 */ 1911 public static void lowLevelShutdown() { 1912 nativeShutdown(); 1913 } 1914 1915 /** 1916 * Low-level function to reboot the device. 1917 * 1918 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 1919 * @throws IOException if reboot fails for some reason (eg, lack of 1920 * permission) 1921 */ 1922 public static void lowLevelReboot(String reason) throws IOException { 1923 nativeReboot(reason); 1924 } 1925 1926 @Override // Watchdog.Monitor implementation 1927 public void monitor() { 1928 // Grab and release lock for watchdog monitor to detect deadlocks. 1929 synchronized (mLock) { 1930 } 1931 } 1932 1933 @Override // Binder call 1934 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1935 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 1936 != PackageManager.PERMISSION_GRANTED) { 1937 pw.println("Permission Denial: can't dump PowerManager from from pid=" 1938 + Binder.getCallingPid() 1939 + ", uid=" + Binder.getCallingUid()); 1940 return; 1941 } 1942 1943 pw.println("POWER MANAGER (dumpsys power)\n"); 1944 1945 final DisplayPowerController dpc; 1946 synchronized (mLock) { 1947 pw.println("Power Manager State:"); 1948 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 1949 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness)); 1950 pw.println(" mIsPowered=" + mIsPowered); 1951 pw.println(" mPlugType=" + mPlugType); 1952 pw.println(" mStayOn=" + mStayOn); 1953 pw.println(" mBootCompleted=" + mBootCompleted); 1954 pw.println(" mSystemReady=" + mSystemReady); 1955 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1956 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 1957 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 1958 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 1959 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 1960 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 1961 pw.println(" mSendWakeUpFinishedNotificationWhenReady=" 1962 + mSendWakeUpFinishedNotificationWhenReady); 1963 pw.println(" mSendGoToSleepFinishedNotificationWhenReady=" 1964 + mSendGoToSleepFinishedNotificationWhenReady); 1965 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 1966 pw.println(" mLastUserActivityTimeNoChangeLights=" 1967 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 1968 pw.println(" mDisplayReady=" + mDisplayReady); 1969 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 1970 1971 pw.println(); 1972 pw.println("Settings and Configuration:"); 1973 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 1974 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 1975 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 1976 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 1977 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 1978 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 1979 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 1980 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 1981 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 1982 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 1983 + mScreenAutoBrightnessAdjustmentSetting); 1984 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 1985 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 1986 + mScreenBrightnessOverrideFromWindowManager); 1987 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 1988 + mUserActivityTimeoutOverrideFromWindowManager); 1989 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 1990 + mTemporaryScreenBrightnessSettingOverride); 1991 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 1992 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 1993 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 1994 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 1995 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 1996 1997 final int screenOffTimeout = getScreenOffTimeoutLocked(); 1998 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1999 pw.println(); 2000 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2001 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2002 2003 pw.println(); 2004 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2005 for (WakeLock wl : mWakeLocks) { 2006 pw.println(" " + wl); 2007 } 2008 2009 pw.println(); 2010 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2011 for (SuspendBlocker sb : mSuspendBlockers) { 2012 pw.println(" " + sb); 2013 } 2014 2015 dpc = mDisplayPowerController; 2016 } 2017 2018 if (dpc != null) { 2019 dpc.dump(pw); 2020 } 2021 } 2022 2023 private SuspendBlocker createSuspendBlockerLocked(String name) { 2024 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2025 mSuspendBlockers.add(suspendBlocker); 2026 return suspendBlocker; 2027 } 2028 2029 private static String wakefulnessToString(int wakefulness) { 2030 switch (wakefulness) { 2031 case WAKEFULNESS_ASLEEP: 2032 return "Asleep"; 2033 case WAKEFULNESS_AWAKE: 2034 return "Awake"; 2035 case WAKEFULNESS_DREAMING: 2036 return "Dreaming"; 2037 case WAKEFULNESS_NAPPING: 2038 return "Napping"; 2039 default: 2040 return Integer.toString(wakefulness); 2041 } 2042 } 2043 2044 private static WorkSource copyWorkSource(WorkSource workSource) { 2045 return workSource != null ? new WorkSource(workSource) : null; 2046 } 2047 2048 private final class BatteryReceiver extends BroadcastReceiver { 2049 @Override 2050 public void onReceive(Context context, Intent intent) { 2051 synchronized (mLock) { 2052 handleBatteryStateChangedLocked(); 2053 } 2054 } 2055 } 2056 2057 private final class BootCompletedReceiver extends BroadcastReceiver { 2058 @Override 2059 public void onReceive(Context context, Intent intent) { 2060 synchronized (mLock) { 2061 handleBootCompletedLocked(); 2062 } 2063 } 2064 } 2065 2066 private final class DreamReceiver extends BroadcastReceiver { 2067 @Override 2068 public void onReceive(Context context, Intent intent) { 2069 synchronized (mLock) { 2070 scheduleSandmanLocked(); 2071 } 2072 } 2073 } 2074 2075 private final class UserSwitchedReceiver extends BroadcastReceiver { 2076 @Override 2077 public void onReceive(Context context, Intent intent) { 2078 synchronized (mLock) { 2079 handleSettingsChangedLocked(); 2080 } 2081 } 2082 } 2083 2084 private final class SettingsObserver extends ContentObserver { 2085 public SettingsObserver(Handler handler) { 2086 super(handler); 2087 } 2088 2089 @Override 2090 public void onChange(boolean selfChange, Uri uri) { 2091 synchronized (mLock) { 2092 handleSettingsChangedLocked(); 2093 } 2094 } 2095 } 2096 2097 private final WindowManagerPolicy.ScreenOnListener mScreenOnListener = 2098 new WindowManagerPolicy.ScreenOnListener() { 2099 @Override 2100 public void onScreenOn() { 2101 } 2102 }; 2103 2104 /** 2105 * Handler for asynchronous operations performed by the power manager. 2106 */ 2107 private final class PowerManagerHandler extends Handler { 2108 public PowerManagerHandler(Looper looper) { 2109 super(looper, null, true /*async*/); 2110 } 2111 2112 @Override 2113 public void handleMessage(Message msg) { 2114 switch (msg.what) { 2115 case MSG_USER_ACTIVITY_TIMEOUT: 2116 handleUserActivityTimeout(); 2117 break; 2118 case MSG_SANDMAN: 2119 handleSandman(); 2120 break; 2121 } 2122 } 2123 } 2124 2125 /** 2126 * Represents a wake lock that has been acquired by an application. 2127 */ 2128 private final class WakeLock implements IBinder.DeathRecipient { 2129 public final IBinder mLock; 2130 public int mFlags; 2131 public String mTag; 2132 public WorkSource mWorkSource; 2133 public int mOwnerUid; 2134 public int mOwnerPid; 2135 2136 public WakeLock(IBinder lock, int flags, String tag, WorkSource workSource, 2137 int ownerUid, int ownerPid) { 2138 mLock = lock; 2139 mFlags = flags; 2140 mTag = tag; 2141 mWorkSource = copyWorkSource(workSource); 2142 mOwnerUid = ownerUid; 2143 mOwnerPid = ownerPid; 2144 } 2145 2146 @Override 2147 public void binderDied() { 2148 PowerManagerService.this.handleWakeLockDeath(this); 2149 } 2150 2151 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 2152 int ownerUid, int ownerPid) { 2153 return mFlags == flags 2154 && mTag.equals(tag) 2155 && hasSameWorkSource(workSource) 2156 && mOwnerUid == ownerUid 2157 && mOwnerPid == ownerPid; 2158 } 2159 2160 public void updateProperties(int flags, String tag, WorkSource workSource, 2161 int ownerUid, int ownerPid) { 2162 mFlags = flags; 2163 mTag = tag; 2164 updateWorkSource(workSource); 2165 mOwnerUid = ownerUid; 2166 mOwnerPid = ownerPid; 2167 } 2168 2169 public boolean hasSameWorkSource(WorkSource workSource) { 2170 return Objects.equal(mWorkSource, workSource); 2171 } 2172 2173 public void updateWorkSource(WorkSource workSource) { 2174 mWorkSource = copyWorkSource(workSource); 2175 } 2176 2177 @Override 2178 public String toString() { 2179 return getLockLevelString() 2180 + " '" + mTag + "'" + getLockFlagsString() 2181 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2182 } 2183 2184 private String getLockLevelString() { 2185 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2186 case PowerManager.FULL_WAKE_LOCK: 2187 return "FULL_WAKE_LOCK "; 2188 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2189 return "SCREEN_BRIGHT_WAKE_LOCK "; 2190 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2191 return "SCREEN_DIM_WAKE_LOCK "; 2192 case PowerManager.PARTIAL_WAKE_LOCK: 2193 return "PARTIAL_WAKE_LOCK "; 2194 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2195 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2196 default: 2197 return "??? "; 2198 } 2199 } 2200 2201 private String getLockFlagsString() { 2202 String result = ""; 2203 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2204 result += " ACQUIRE_CAUSES_WAKEUP"; 2205 } 2206 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2207 result += " ON_AFTER_RELEASE"; 2208 } 2209 return result; 2210 } 2211 } 2212 2213 private final class SuspendBlockerImpl implements SuspendBlocker { 2214 private final String mName; 2215 private int mReferenceCount; 2216 2217 public SuspendBlockerImpl(String name) { 2218 mName = name; 2219 } 2220 2221 @Override 2222 protected void finalize() throws Throwable { 2223 try { 2224 if (mReferenceCount != 0) { 2225 Log.wtf(TAG, "Suspend blocker \"" + mName 2226 + "\" was finalized without being released!"); 2227 mReferenceCount = 0; 2228 nativeReleaseSuspendBlocker(mName); 2229 } 2230 } finally { 2231 super.finalize(); 2232 } 2233 } 2234 2235 @Override 2236 public void acquire() { 2237 synchronized (this) { 2238 mReferenceCount += 1; 2239 if (mReferenceCount == 1) { 2240 nativeAcquireSuspendBlocker(mName); 2241 } 2242 } 2243 } 2244 2245 @Override 2246 public void release() { 2247 synchronized (this) { 2248 mReferenceCount -= 1; 2249 if (mReferenceCount == 0) { 2250 nativeReleaseSuspendBlocker(mName); 2251 } else if (mReferenceCount < 0) { 2252 Log.wtf(TAG, "Suspend blocker \"" + mName 2253 + "\" was released without being acquired!", new Throwable()); 2254 mReferenceCount = 0; 2255 } 2256 } 2257 } 2258 2259 @Override 2260 public String toString() { 2261 synchronized (this) { 2262 return mName + ": ref count=" + mReferenceCount; 2263 } 2264 } 2265 } 2266} 2267