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