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