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