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