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