PowerManagerService.java revision 131206b8a9d07400d7c98aea50cc45c38769448f
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.IAppOpsService; 20import com.android.internal.app.IBatteryStats; 21import com.android.server.BatteryService; 22import com.android.server.EventLogTags; 23import com.android.server.LocalServices; 24import com.android.server.ServiceThread; 25import com.android.server.lights.Light; 26import com.android.server.lights.LightsManager; 27import com.android.server.Watchdog; 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.hardware.SensorManager; 39import android.hardware.SystemSensorManager; 40import android.hardware.display.DisplayManagerInternal; 41import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest; 42import android.net.Uri; 43import android.os.BatteryManager; 44import android.os.Binder; 45import android.os.Handler; 46import android.os.IBinder; 47import android.os.IPowerManager; 48import android.os.Looper; 49import android.os.Message; 50import android.os.PowerManager; 51import android.os.PowerManagerInternal; 52import android.os.Process; 53import android.os.RemoteException; 54import android.os.SystemClock; 55import android.os.SystemProperties; 56import android.os.SystemService; 57import android.os.UserHandle; 58import android.os.WorkSource; 59import android.provider.Settings; 60import android.service.dreams.DreamManagerInternal; 61import android.util.EventLog; 62import android.util.Log; 63import android.util.Slog; 64import android.util.TimeUtils; 65import android.view.WindowManagerPolicy; 66 67import java.io.FileDescriptor; 68import java.io.PrintWriter; 69import java.util.ArrayList; 70 71import libcore.util.Objects; 72 73/** 74 * The power manager service is responsible for coordinating power management 75 * functions on the device. 76 */ 77public final class PowerManagerService extends com.android.server.SystemService 78 implements Watchdog.Monitor { 79 private static final String TAG = "PowerManagerService"; 80 81 private static final boolean DEBUG = false; 82 private static final boolean DEBUG_SPEW = DEBUG && true; 83 84 // Message: Sent when a user activity timeout occurs to update the power state. 85 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 86 // Message: Sent when the device enters or exits a dreaming or dozing state. 87 private static final int MSG_SANDMAN = 2; 88 // Message: Sent when the screen on blocker is released. 89 private static final int MSG_SCREEN_ON_BLOCKER_RELEASED = 3; 90 // Message: Sent to poll whether the boot animation has terminated. 91 private static final int MSG_CHECK_IF_BOOT_ANIMATION_FINISHED = 4; 92 93 // Dirty bit: mWakeLocks changed 94 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 95 // Dirty bit: mWakefulness changed 96 private static final int DIRTY_WAKEFULNESS = 1 << 1; 97 // Dirty bit: user activity was poked or may have timed out 98 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 99 // Dirty bit: actual display power state was updated asynchronously 100 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 101 // Dirty bit: mBootCompleted changed 102 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 103 // Dirty bit: settings changed 104 private static final int DIRTY_SETTINGS = 1 << 5; 105 // Dirty bit: mIsPowered changed 106 private static final int DIRTY_IS_POWERED = 1 << 6; 107 // Dirty bit: mStayOn changed 108 private static final int DIRTY_STAY_ON = 1 << 7; 109 // Dirty bit: battery state changed 110 private static final int DIRTY_BATTERY_STATE = 1 << 8; 111 // Dirty bit: proximity state changed 112 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9; 113 // Dirty bit: screen on blocker state became held or unheld 114 private static final int DIRTY_SCREEN_ON_BLOCKER_RELEASED = 1 << 10; 115 // Dirty bit: dock state changed 116 private static final int DIRTY_DOCK_STATE = 1 << 11; 117 118 // Wakefulness: The device is asleep and can only be awoken by a call to wakeUp(). 119 // The screen should be off or in the process of being turned off by the display controller. 120 // The device typically passes through the dozing state first. 121 private static final int WAKEFULNESS_ASLEEP = 0; 122 // Wakefulness: The device is fully awake. It can be put to sleep by a call to goToSleep(). 123 // When the user activity timeout expires, the device may start dreaming or go to sleep. 124 private static final int WAKEFULNESS_AWAKE = 1; 125 // Wakefulness: The device is dreaming. It can be awoken by a call to wakeUp(), 126 // which ends the dream. The device goes to sleep when goToSleep() is called, when 127 // the dream ends or when unplugged. 128 // User activity may brighten the screen but does not end the dream. 129 private static final int WAKEFULNESS_DREAMING = 2; 130 // Wakefulness: The device is dozing. It is almost asleep but is allowing a special 131 // low-power "doze" dream to run which keeps the display on but lets the application 132 // processor be suspended. It can be awoken by a call to wakeUp() which ends the dream. 133 // The device fully goes to sleep if the dream cannot be started or ends on its own. 134 private static final int WAKEFULNESS_DOZING = 3; 135 136 // Summarizes the state of all active wakelocks. 137 private static final int WAKE_LOCK_CPU = 1 << 0; 138 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 139 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 140 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 141 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 142 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake 143 private static final int WAKE_LOCK_DOZE = 1 << 6; 144 145 // Summarizes the user activity state. 146 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 147 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 148 149 // Default and minimum screen off timeout in milliseconds. 150 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 151 private static final int MINIMUM_SCREEN_OFF_TIMEOUT = 10 * 1000; 152 153 // The screen dim duration, in milliseconds. 154 // This is subtracted from the end of the screen off timeout so the 155 // minimum screen off timeout should be longer than this. 156 private static final int SCREEN_DIM_DURATION = 7 * 1000; 157 158 // The maximum screen dim time expressed as a ratio relative to the screen 159 // off timeout. If the screen off timeout is very short then we want the 160 // dim timeout to also be quite short so that most of the time is spent on. 161 // Otherwise the user won't get much screen on time before dimming occurs. 162 private static final float MAXIMUM_SCREEN_DIM_RATIO = 0.2f; 163 164 // The name of the boot animation service in init.rc. 165 private static final String BOOT_ANIMATION_SERVICE = "bootanim"; 166 167 // Poll interval in milliseconds for watching boot animation finished. 168 private static final int BOOT_ANIMATION_POLL_INTERVAL = 200; 169 170 private final Context mContext; 171 private LightsManager mLightsManager; 172 private BatteryService mBatteryService; 173 private DisplayManagerInternal mDisplayManagerInternal; 174 private IBatteryStats mBatteryStats; 175 private IAppOpsService mAppOps; 176 private ServiceThread mHandlerThread; 177 private PowerManagerHandler mHandler; 178 private WindowManagerPolicy mPolicy; 179 private Notifier mNotifier; 180 private WirelessChargerDetector mWirelessChargerDetector; 181 private SettingsObserver mSettingsObserver; 182 private DreamManagerInternal mDreamManager; 183 private Light mAttentionLight; 184 185 private final Object mLock = new Object(); 186 187 // A bitfield that indicates what parts of the power state have 188 // changed and need to be recalculated. 189 private int mDirty; 190 191 // Indicates whether the device is awake or asleep or somewhere in between. 192 // This is distinct from the screen power state, which is managed separately. 193 private int mWakefulness; 194 195 // True if the sandman has just been summoned for the first time since entering the 196 // dreaming or dozing state. Indicates whether a new dream should begin. 197 private boolean mSandmanSummoned; 198 199 // True if MSG_SANDMAN has been scheduled. 200 private boolean mSandmanScheduled; 201 202 // Table of all suspend blockers. 203 // There should only be a few of these. 204 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>(); 205 206 // Table of all wake locks acquired by applications. 207 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>(); 208 209 // A bitfield that summarizes the state of all active wakelocks. 210 private int mWakeLockSummary; 211 212 // If true, instructs the display controller to wait for the proximity sensor to 213 // go negative before turning the screen on. 214 private boolean mRequestWaitForNegativeProximity; 215 216 // Timestamp of the last time the device was awoken or put to sleep. 217 private long mLastWakeTime; 218 private long mLastSleepTime; 219 220 // True if we need to send a wake up or go to sleep finished notification 221 // when the display is ready. 222 private boolean mSendWakeUpFinishedNotificationWhenReady; 223 private boolean mSendGoToSleepFinishedNotificationWhenReady; 224 225 // Timestamp of the last call to user activity. 226 private long mLastUserActivityTime; 227 private long mLastUserActivityTimeNoChangeLights; 228 229 // A bitfield that summarizes the effect of the user activity timer. 230 // A zero value indicates that the user activity timer has expired. 231 private int mUserActivitySummary; 232 233 // The desired display power state. The actual state may lag behind the 234 // requested because it is updated asynchronously by the display power controller. 235 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 236 237 // True if the display power state has been fully applied, which means the display 238 // is actually on or actually off or whatever was requested. 239 private boolean mDisplayReady; 240 241 // The suspend blocker used to keep the CPU alive when an application has acquired 242 // a wake lock. 243 private final SuspendBlocker mWakeLockSuspendBlocker; 244 245 // True if the wake lock suspend blocker has been acquired. 246 private boolean mHoldingWakeLockSuspendBlocker; 247 248 // The suspend blocker used to keep the CPU alive when the display is on, the 249 // display is getting ready or there is user activity (in which case the display 250 // must be on). 251 private final SuspendBlocker mDisplaySuspendBlocker; 252 253 // True if the display suspend blocker has been acquired. 254 private boolean mHoldingDisplaySuspendBlocker; 255 256 // The screen on blocker used to keep the screen from turning on while the lock 257 // screen is coming up. 258 private final ScreenOnBlockerImpl mScreenOnBlocker; 259 260 // True if systemReady() has been called. 261 private boolean mSystemReady; 262 263 // True if boot completed occurred. We keep the screen on until this happens. 264 private boolean mBootCompleted; 265 266 // True if auto-suspend mode is enabled. 267 // Refer to autosuspend.h. 268 private boolean mAutoSuspendModeEnabled; 269 270 // True if interactive mode is enabled. 271 // Refer to power.h. 272 private boolean mInteractiveModeEnabled; 273 274 // True if the device is plugged into a power source. 275 private boolean mIsPowered; 276 277 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS. 278 private int mPlugType; 279 280 // The current battery level percentage. 281 private int mBatteryLevel; 282 283 // The battery level percentage at the time the dream started. 284 // This is used to terminate a dream and go to sleep if the battery is 285 // draining faster than it is charging and the user activity timeout has expired. 286 private int mBatteryLevelWhenDreamStarted; 287 288 // The current dock state. 289 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED; 290 291 // True to decouple auto-suspend mode from the display state. 292 private boolean mDecoupleAutoSuspendModeFromDisplayConfig; 293 294 // True to decouple interactive mode from the display state. 295 private boolean mDecoupleInteractiveModeFromDisplayConfig; 296 297 // True if the device should wake up when plugged or unplugged. 298 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 299 300 // True if the device should suspend when the screen is off due to proximity. 301 private boolean mSuspendWhenScreenOffDueToProximityConfig; 302 303 // True if dreams are supported on this device. 304 private boolean mDreamsSupportedConfig; 305 306 // Default value for dreams enabled 307 private boolean mDreamsEnabledByDefaultConfig; 308 309 // Default value for dreams activate-on-sleep 310 private boolean mDreamsActivatedOnSleepByDefaultConfig; 311 312 // Default value for dreams activate-on-dock 313 private boolean mDreamsActivatedOnDockByDefaultConfig; 314 315 // True if dreams can run while not plugged in. 316 private boolean mDreamsEnabledOnBatteryConfig; 317 318 // Minimum battery level to allow dreaming when powered. 319 // Use -1 to disable this safety feature. 320 private int mDreamsBatteryLevelMinimumWhenPoweredConfig; 321 322 // Minimum battery level to allow dreaming when not powered. 323 // Use -1 to disable this safety feature. 324 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig; 325 326 // If the battery level drops by this percentage and the user activity timeout 327 // has expired, then assume the device is receiving insufficient current to charge 328 // effectively and terminate the dream. Use -1 to disable this safety feature. 329 private int mDreamsBatteryLevelDrainCutoffConfig; 330 331 // True if dreams are enabled by the user. 332 private boolean mDreamsEnabledSetting; 333 334 // True if dreams should be activated on sleep. 335 private boolean mDreamsActivateOnSleepSetting; 336 337 // True if dreams should be activated on dock. 338 private boolean mDreamsActivateOnDockSetting; 339 340 // The screen off timeout setting value in milliseconds. 341 private int mScreenOffTimeoutSetting; 342 343 // The maximum allowable screen off timeout according to the device 344 // administration policy. Overrides other settings. 345 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 346 347 // The stay on while plugged in setting. 348 // A bitfield of battery conditions under which to make the screen stay on. 349 private int mStayOnWhilePluggedInSetting; 350 351 // True if the device should stay on. 352 private boolean mStayOn; 353 354 // True if the proximity sensor reads a positive result. 355 private boolean mProximityPositive; 356 357 // Screen brightness setting limits. 358 private int mScreenBrightnessSettingMinimum; 359 private int mScreenBrightnessSettingMaximum; 360 private int mScreenBrightnessSettingDefault; 361 362 // The screen brightness setting, from 0 to 255. 363 // Use -1 if no value has been set. 364 private int mScreenBrightnessSetting; 365 366 // The screen auto-brightness adjustment setting, from -1 to 1. 367 // Use 0 if there is no adjustment. 368 private float mScreenAutoBrightnessAdjustmentSetting; 369 370 // The screen brightness mode. 371 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 372 private int mScreenBrightnessModeSetting; 373 374 // The screen brightness setting override from the window manager 375 // to allow the current foreground activity to override the brightness. 376 // Use -1 to disable. 377 private int mScreenBrightnessOverrideFromWindowManager = -1; 378 379 // The user activity timeout override from the window manager 380 // to allow the current foreground activity to override the user activity timeout. 381 // Use -1 to disable. 382 private long mUserActivityTimeoutOverrideFromWindowManager = -1; 383 384 // The screen brightness setting override from the settings application 385 // to temporarily adjust the brightness until next updated, 386 // Use -1 to disable. 387 private int mTemporaryScreenBrightnessSettingOverride = -1; 388 389 // The screen brightness adjustment setting override from the settings 390 // application to temporarily adjust the auto-brightness adjustment factor 391 // until next updated, in the range -1..1. 392 // Use NaN to disable. 393 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 394 395 // Time when we last logged a warning about calling userActivity() without permission. 396 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE; 397 398 private native void nativeInit(); 399 400 private static native void nativeSetPowerState(boolean screenOn, boolean screenBright); 401 private static native void nativeAcquireSuspendBlocker(String name); 402 private static native void nativeReleaseSuspendBlocker(String name); 403 private static native void nativeSetInteractive(boolean enable); 404 private static native void nativeSetAutoSuspend(boolean enable); 405 private static native void nativeSendPowerHint(int hintId, int data); 406 407 public PowerManagerService(Context context) { 408 super(context); 409 mContext = context; 410 synchronized (mLock) { 411 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks"); 412 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display"); 413 mDisplaySuspendBlocker.acquire(); 414 mHoldingDisplaySuspendBlocker = true; 415 416 mScreenOnBlocker = new ScreenOnBlockerImpl(); 417 mWakefulness = WAKEFULNESS_AWAKE; 418 } 419 420 nativeInit(); 421 nativeSetPowerState(true, true); 422 } 423 424 @Override 425 public void onStart() { 426 publishBinderService(Context.POWER_SERVICE, new BinderService()); 427 publishLocalService(PowerManagerInternal.class, new LocalService()); 428 } 429 430 /** 431 * Initialize the power manager. 432 * Must be called before any other functions within the power manager are called. 433 */ 434 public void init(LightsManager ls, 435 BatteryService bs, IBatteryStats bss, 436 IAppOpsService appOps) { 437 mLightsManager = ls; 438 mBatteryService = bs; 439 mBatteryStats = bss; 440 mAppOps = appOps; 441 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class); 442 mHandlerThread = new ServiceThread(TAG, 443 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/); 444 mHandlerThread.start(); 445 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 446 447 Watchdog.getInstance().addMonitor(this); 448 Watchdog.getInstance().addThread(mHandler); 449 450 // Forcibly turn the screen on at boot so that it is in a known power state. 451 // We do this in init() rather than in the constructor because setting the 452 // screen state requires a call into surface flinger which then needs to call back 453 // into the activity manager to check permissions. Unfortunately the 454 // activity manager is not running when the constructor is called, so we 455 // have to defer setting the screen state until this point. 456 mDisplayPowerCallbacks.unblankAllDisplays(); 457 } 458 459 void setPolicy(WindowManagerPolicy policy) { 460 synchronized (mLock) { 461 mPolicy = policy; 462 } 463 } 464 465 public void systemReady() { 466 synchronized (mLock) { 467 mSystemReady = true; 468 mDreamManager = LocalServices.getService(DreamManagerInternal.class); 469 470 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 471 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 472 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 473 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 474 475 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper()); 476 477 // The notifier runs on the system server's main looper so as not to interfere 478 // with the animations and other critical functions of the power manager. 479 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, 480 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 481 mScreenOnBlocker, mPolicy); 482 483 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager, 484 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"), 485 mHandler); 486 mSettingsObserver = new SettingsObserver(mHandler); 487 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION); 488 489 // Initialize display power management. 490 mDisplayManagerInternal.initPowerManagement( 491 mDisplayPowerCallbacks, mHandler, sensorManager); 492 493 // Register for broadcasts from other components of the system. 494 IntentFilter filter = new IntentFilter(); 495 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 496 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler); 497 498 filter = new IntentFilter(); 499 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 500 mContext.registerReceiver(new BootCompletedReceiver(), filter, null, mHandler); 501 502 filter = new IntentFilter(); 503 filter.addAction(Intent.ACTION_DREAMING_STARTED); 504 filter.addAction(Intent.ACTION_DREAMING_STOPPED); 505 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler); 506 507 filter = new IntentFilter(); 508 filter.addAction(Intent.ACTION_USER_SWITCHED); 509 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler); 510 511 filter = new IntentFilter(); 512 filter.addAction(Intent.ACTION_DOCK_EVENT); 513 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler); 514 515 // Register for settings changes. 516 final ContentResolver resolver = mContext.getContentResolver(); 517 resolver.registerContentObserver(Settings.Secure.getUriFor( 518 Settings.Secure.SCREENSAVER_ENABLED), 519 false, mSettingsObserver, UserHandle.USER_ALL); 520 resolver.registerContentObserver(Settings.Secure.getUriFor( 521 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), 522 false, mSettingsObserver, UserHandle.USER_ALL); 523 resolver.registerContentObserver(Settings.Secure.getUriFor( 524 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), 525 false, mSettingsObserver, UserHandle.USER_ALL); 526 resolver.registerContentObserver(Settings.System.getUriFor( 527 Settings.System.SCREEN_OFF_TIMEOUT), 528 false, mSettingsObserver, UserHandle.USER_ALL); 529 resolver.registerContentObserver(Settings.Global.getUriFor( 530 Settings.Global.STAY_ON_WHILE_PLUGGED_IN), 531 false, mSettingsObserver, UserHandle.USER_ALL); 532 resolver.registerContentObserver(Settings.System.getUriFor( 533 Settings.System.SCREEN_BRIGHTNESS), 534 false, mSettingsObserver, UserHandle.USER_ALL); 535 resolver.registerContentObserver(Settings.System.getUriFor( 536 Settings.System.SCREEN_BRIGHTNESS_MODE), 537 false, mSettingsObserver, UserHandle.USER_ALL); 538 539 // Go. 540 readConfigurationLocked(); 541 updateSettingsLocked(); 542 mDirty |= DIRTY_BATTERY_STATE; 543 updatePowerStateLocked(); 544 } 545 } 546 547 private void readConfigurationLocked() { 548 final Resources resources = mContext.getResources(); 549 550 mDecoupleAutoSuspendModeFromDisplayConfig = resources.getBoolean( 551 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay); 552 mDecoupleInteractiveModeFromDisplayConfig = resources.getBoolean( 553 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay); 554 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 555 com.android.internal.R.bool.config_unplugTurnsOnScreen); 556 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean( 557 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity); 558 mDreamsSupportedConfig = resources.getBoolean( 559 com.android.internal.R.bool.config_dreamsSupported); 560 mDreamsEnabledByDefaultConfig = resources.getBoolean( 561 com.android.internal.R.bool.config_dreamsEnabledByDefault); 562 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean( 563 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault); 564 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean( 565 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault); 566 mDreamsEnabledOnBatteryConfig = resources.getBoolean( 567 com.android.internal.R.bool.config_dreamsEnabledOnBattery); 568 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger( 569 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered); 570 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger( 571 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered); 572 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger( 573 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff); 574 } 575 576 private void updateSettingsLocked() { 577 final ContentResolver resolver = mContext.getContentResolver(); 578 579 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver, 580 Settings.Secure.SCREENSAVER_ENABLED, 581 mDreamsEnabledByDefaultConfig ? 1 : 0, 582 UserHandle.USER_CURRENT) != 0); 583 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver, 584 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 585 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0, 586 UserHandle.USER_CURRENT) != 0); 587 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver, 588 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK, 589 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0, 590 UserHandle.USER_CURRENT) != 0); 591 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver, 592 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT, 593 UserHandle.USER_CURRENT); 594 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver, 595 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC); 596 597 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 598 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver, 599 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault, 600 UserHandle.USER_CURRENT); 601 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 602 mTemporaryScreenBrightnessSettingOverride = -1; 603 } 604 605 final float oldScreenAutoBrightnessAdjustmentSetting = 606 mScreenAutoBrightnessAdjustmentSetting; 607 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver, 608 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, 609 UserHandle.USER_CURRENT); 610 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 611 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 612 } 613 614 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver, 615 Settings.System.SCREEN_BRIGHTNESS_MODE, 616 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT); 617 618 mDirty |= DIRTY_SETTINGS; 619 } 620 621 private void handleSettingsChangedLocked() { 622 updateSettingsLocked(); 623 updatePowerStateLocked(); 624 } 625 626 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName, 627 WorkSource ws, String historyTag, int uid, int pid) { 628 synchronized (mLock) { 629 if (DEBUG_SPEW) { 630 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 631 + ", flags=0x" + Integer.toHexString(flags) 632 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 633 } 634 635 WakeLock wakeLock; 636 int index = findWakeLockIndexLocked(lock); 637 if (index >= 0) { 638 wakeLock = mWakeLocks.get(index); 639 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 640 // Update existing wake lock. This shouldn't happen but is harmless. 641 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName, 642 uid, pid, ws, historyTag); 643 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid); 644 } 645 } else { 646 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid); 647 try { 648 lock.linkToDeath(wakeLock, 0); 649 } catch (RemoteException ex) { 650 throw new IllegalArgumentException("Wake lock is already dead."); 651 } 652 notifyWakeLockAcquiredLocked(wakeLock); 653 mWakeLocks.add(wakeLock); 654 } 655 656 applyWakeLockFlagsOnAcquireLocked(wakeLock); 657 mDirty |= DIRTY_WAKE_LOCKS; 658 updatePowerStateLocked(); 659 } 660 } 661 662 @SuppressWarnings("deprecation") 663 private static boolean isScreenLock(final WakeLock wakeLock) { 664 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 665 case PowerManager.FULL_WAKE_LOCK: 666 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 667 case PowerManager.SCREEN_DIM_WAKE_LOCK: 668 return true; 669 } 670 return false; 671 } 672 673 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock) { 674 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0 675 && isScreenLock(wakeLock)) { 676 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 677 } 678 } 679 680 private void releaseWakeLockInternal(IBinder lock, int flags) { 681 synchronized (mLock) { 682 int index = findWakeLockIndexLocked(lock); 683 if (index < 0) { 684 if (DEBUG_SPEW) { 685 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 686 + " [not found], flags=0x" + Integer.toHexString(flags)); 687 } 688 return; 689 } 690 691 WakeLock wakeLock = mWakeLocks.get(index); 692 if (DEBUG_SPEW) { 693 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 694 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags)); 695 } 696 697 mWakeLocks.remove(index); 698 notifyWakeLockReleasedLocked(wakeLock); 699 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 700 701 if ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0) { 702 mRequestWaitForNegativeProximity = true; 703 } 704 705 applyWakeLockFlagsOnReleaseLocked(wakeLock); 706 mDirty |= DIRTY_WAKE_LOCKS; 707 updatePowerStateLocked(); 708 } 709 } 710 711 private void handleWakeLockDeath(WakeLock wakeLock) { 712 synchronized (mLock) { 713 if (DEBUG_SPEW) { 714 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock) 715 + " [" + wakeLock.mTag + "]"); 716 } 717 718 int index = mWakeLocks.indexOf(wakeLock); 719 if (index < 0) { 720 return; 721 } 722 723 mWakeLocks.remove(index); 724 notifyWakeLockReleasedLocked(wakeLock); 725 726 applyWakeLockFlagsOnReleaseLocked(wakeLock); 727 mDirty |= DIRTY_WAKE_LOCKS; 728 updatePowerStateLocked(); 729 } 730 } 731 732 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 733 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0 734 && isScreenLock(wakeLock)) { 735 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 736 PowerManager.USER_ACTIVITY_EVENT_OTHER, 737 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 738 wakeLock.mOwnerUid); 739 } 740 } 741 742 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag) { 743 synchronized (mLock) { 744 int index = findWakeLockIndexLocked(lock); 745 if (index < 0) { 746 if (DEBUG_SPEW) { 747 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 748 + " [not found], ws=" + ws); 749 } 750 throw new IllegalArgumentException("Wake lock not active"); 751 } 752 753 WakeLock wakeLock = mWakeLocks.get(index); 754 if (DEBUG_SPEW) { 755 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 756 + " [" + wakeLock.mTag + "], ws=" + ws); 757 } 758 759 if (!wakeLock.hasSameWorkSource(ws)) { 760 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag, 761 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 762 ws, historyTag); 763 wakeLock.mHistoryTag = historyTag; 764 wakeLock.updateWorkSource(ws); 765 } 766 } 767 } 768 769 private int findWakeLockIndexLocked(IBinder lock) { 770 final int count = mWakeLocks.size(); 771 for (int i = 0; i < count; i++) { 772 if (mWakeLocks.get(i).mLock == lock) { 773 return i; 774 } 775 } 776 return -1; 777 } 778 779 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 780 if (mSystemReady) { 781 wakeLock.mNotifiedAcquired = true; 782 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 783 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 784 wakeLock.mHistoryTag); 785 } 786 } 787 788 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag, 789 String packageName, int uid, int pid, WorkSource ws, String historyTag) { 790 if (mSystemReady && wakeLock.mNotifiedAcquired) { 791 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 792 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 793 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag); 794 } 795 } 796 797 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 798 if (mSystemReady && wakeLock.mNotifiedAcquired) { 799 wakeLock.mNotifiedAcquired = false; 800 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 801 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource); 802 } 803 } 804 805 @SuppressWarnings("deprecation") 806 private boolean isWakeLockLevelSupportedInternal(int level) { 807 synchronized (mLock) { 808 switch (level) { 809 case PowerManager.PARTIAL_WAKE_LOCK: 810 case PowerManager.SCREEN_DIM_WAKE_LOCK: 811 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 812 case PowerManager.FULL_WAKE_LOCK: 813 case PowerManager.DOZE_WAKE_LOCK: 814 return true; 815 816 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 817 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable(); 818 819 default: 820 return false; 821 } 822 } 823 } 824 825 // Called from native code. 826 private void userActivityFromNative(long eventTime, int event, int flags) { 827 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 828 } 829 830 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 831 synchronized (mLock) { 832 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 833 updatePowerStateLocked(); 834 } 835 } 836 } 837 838 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 839 if (DEBUG_SPEW) { 840 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 841 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 842 + ", uid=" + uid); 843 } 844 845 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 846 || mWakefulness == WAKEFULNESS_ASLEEP || mWakefulness == WAKEFULNESS_DOZING 847 || !mBootCompleted || !mSystemReady) { 848 return false; 849 } 850 851 mNotifier.onUserActivity(event, uid); 852 853 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 854 if (eventTime > mLastUserActivityTimeNoChangeLights 855 && eventTime > mLastUserActivityTime) { 856 mLastUserActivityTimeNoChangeLights = eventTime; 857 mDirty |= DIRTY_USER_ACTIVITY; 858 return true; 859 } 860 } else { 861 if (eventTime > mLastUserActivityTime) { 862 mLastUserActivityTime = eventTime; 863 mDirty |= DIRTY_USER_ACTIVITY; 864 return true; 865 } 866 } 867 return false; 868 } 869 870 // Called from native code. 871 private void wakeUpFromNative(long eventTime) { 872 wakeUpInternal(eventTime); 873 } 874 875 private void wakeUpInternal(long eventTime) { 876 synchronized (mLock) { 877 if (wakeUpNoUpdateLocked(eventTime)) { 878 updatePowerStateLocked(); 879 } 880 } 881 } 882 883 private boolean wakeUpNoUpdateLocked(long eventTime) { 884 if (DEBUG_SPEW) { 885 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime); 886 } 887 888 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 889 || !mBootCompleted || !mSystemReady) { 890 return false; 891 } 892 893 switch (mWakefulness) { 894 case WAKEFULNESS_ASLEEP: 895 Slog.i(TAG, "Waking up from sleep..."); 896 break; 897 case WAKEFULNESS_DREAMING: 898 Slog.i(TAG, "Waking up from dream..."); 899 break; 900 case WAKEFULNESS_DOZING: 901 Slog.i(TAG, "Waking up from dozing..."); 902 break; 903 } 904 905 if (mWakefulness != WAKEFULNESS_DREAMING) { 906 sendPendingNotificationsLocked(); 907 mNotifier.onWakeUpStarted(); 908 mSendWakeUpFinishedNotificationWhenReady = true; 909 } 910 911 mLastWakeTime = eventTime; 912 mWakefulness = WAKEFULNESS_AWAKE; 913 mDirty |= DIRTY_WAKEFULNESS; 914 915 userActivityNoUpdateLocked( 916 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 917 return true; 918 } 919 920 // Called from native code. 921 private void goToSleepFromNative(long eventTime, int reason) { 922 goToSleepInternal(eventTime, reason); 923 } 924 925 private void goToSleepInternal(long eventTime, int reason) { 926 synchronized (mLock) { 927 if (goToSleepNoUpdateLocked(eventTime, reason)) { 928 updatePowerStateLocked(); 929 } 930 } 931 } 932 933 // This method is called goToSleep for historical reasons but we actually start 934 // dozing before really going to sleep. 935 @SuppressWarnings("deprecation") 936 private boolean goToSleepNoUpdateLocked(long eventTime, int reason) { 937 if (DEBUG_SPEW) { 938 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime + ", reason=" + reason); 939 } 940 941 if (eventTime < mLastWakeTime 942 || mWakefulness == WAKEFULNESS_ASLEEP 943 || mWakefulness == WAKEFULNESS_DOZING 944 || !mBootCompleted || !mSystemReady) { 945 return false; 946 } 947 948 switch (reason) { 949 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 950 Slog.i(TAG, "Going to sleep due to device administration policy..."); 951 break; 952 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 953 Slog.i(TAG, "Going to sleep due to screen timeout..."); 954 break; 955 default: 956 Slog.i(TAG, "Going to sleep by user request..."); 957 reason = PowerManager.GO_TO_SLEEP_REASON_USER; 958 break; 959 } 960 961 sendPendingNotificationsLocked(); 962 mNotifier.onGoToSleepStarted(reason); 963 mSendGoToSleepFinishedNotificationWhenReady = true; 964 965 mLastSleepTime = eventTime; 966 mDirty |= DIRTY_WAKEFULNESS; 967 mWakefulness = WAKEFULNESS_DOZING; 968 mSandmanSummoned = true; 969 970 // Report the number of wake locks that will be cleared by going to sleep. 971 int numWakeLocksCleared = 0; 972 final int numWakeLocks = mWakeLocks.size(); 973 for (int i = 0; i < numWakeLocks; i++) { 974 final WakeLock wakeLock = mWakeLocks.get(i); 975 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 976 case PowerManager.FULL_WAKE_LOCK: 977 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 978 case PowerManager.SCREEN_DIM_WAKE_LOCK: 979 numWakeLocksCleared += 1; 980 break; 981 } 982 } 983 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 984 return true; 985 } 986 987 private void napInternal(long eventTime) { 988 synchronized (mLock) { 989 if (napNoUpdateLocked(eventTime)) { 990 updatePowerStateLocked(); 991 } 992 } 993 } 994 995 private boolean napNoUpdateLocked(long eventTime) { 996 if (DEBUG_SPEW) { 997 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime); 998 } 999 1000 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE 1001 || !mBootCompleted || !mSystemReady) { 1002 return false; 1003 } 1004 1005 Slog.i(TAG, "Nap time..."); 1006 1007 mDirty |= DIRTY_WAKEFULNESS; 1008 mWakefulness = WAKEFULNESS_DREAMING; 1009 mSandmanSummoned = true; 1010 return true; 1011 } 1012 1013 // Done dozing, drop everything and go to sleep. 1014 private boolean reallyGoToSleepNoUpdateLocked(long eventTime) { 1015 if (DEBUG_SPEW) { 1016 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime); 1017 } 1018 1019 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 1020 || !mBootCompleted || !mSystemReady) { 1021 return false; 1022 } 1023 1024 Slog.i(TAG, "Sleeping..."); 1025 1026 mDirty |= DIRTY_WAKEFULNESS; 1027 mWakefulness = WAKEFULNESS_ASLEEP; 1028 return true; 1029 } 1030 1031 /** 1032 * Updates the global power state based on dirty bits recorded in mDirty. 1033 * 1034 * This is the main function that performs power state transitions. 1035 * We centralize them here so that we can recompute the power state completely 1036 * each time something important changes, and ensure that we do it the same 1037 * way each time. The point is to gather all of the transition logic here. 1038 */ 1039 private void updatePowerStateLocked() { 1040 if (!mSystemReady || mDirty == 0) { 1041 return; 1042 } 1043 if (!Thread.holdsLock(mLock)) { 1044 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked"); 1045 } 1046 1047 // Phase 0: Basic state updates. 1048 updateIsPoweredLocked(mDirty); 1049 updateStayOnLocked(mDirty); 1050 1051 // Phase 1: Update wakefulness. 1052 // Loop because the wake lock and user activity computations are influenced 1053 // by changes in wakefulness. 1054 final long now = SystemClock.uptimeMillis(); 1055 int dirtyPhase2 = 0; 1056 for (;;) { 1057 int dirtyPhase1 = mDirty; 1058 dirtyPhase2 |= dirtyPhase1; 1059 mDirty = 0; 1060 1061 updateWakeLockSummaryLocked(dirtyPhase1); 1062 updateUserActivitySummaryLocked(now, dirtyPhase1); 1063 if (!updateWakefulnessLocked(dirtyPhase1)) { 1064 break; 1065 } 1066 } 1067 1068 // Phase 2: Update dreams and display power state. 1069 updateDreamLocked(dirtyPhase2); 1070 updateDisplayPowerStateLocked(dirtyPhase2); 1071 1072 // Phase 3: Send notifications, if needed. 1073 if (mDisplayReady) { 1074 sendPendingNotificationsLocked(); 1075 } 1076 1077 // Phase 4: Update suspend blocker. 1078 // Because we might release the last suspend blocker here, we need to make sure 1079 // we finished everything else first! 1080 updateSuspendBlockerLocked(); 1081 } 1082 1083 private void sendPendingNotificationsLocked() { 1084 if (mSendWakeUpFinishedNotificationWhenReady) { 1085 mSendWakeUpFinishedNotificationWhenReady = false; 1086 mNotifier.onWakeUpFinished(); 1087 } 1088 if (mSendGoToSleepFinishedNotificationWhenReady) { 1089 mSendGoToSleepFinishedNotificationWhenReady = false; 1090 mNotifier.onGoToSleepFinished(); 1091 } 1092 } 1093 1094 /** 1095 * Updates the value of mIsPowered. 1096 * Sets DIRTY_IS_POWERED if a change occurred. 1097 */ 1098 private void updateIsPoweredLocked(int dirty) { 1099 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 1100 final boolean wasPowered = mIsPowered; 1101 final int oldPlugType = mPlugType; 1102 mIsPowered = mBatteryService.isPowered(BatteryManager.BATTERY_PLUGGED_ANY); 1103 mPlugType = mBatteryService.getPlugType(); 1104 mBatteryLevel = mBatteryService.getBatteryLevel(); 1105 1106 if (DEBUG_SPEW) { 1107 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered 1108 + ", mIsPowered=" + mIsPowered 1109 + ", oldPlugType=" + oldPlugType 1110 + ", mPlugType=" + mPlugType 1111 + ", mBatteryLevel=" + mBatteryLevel); 1112 } 1113 1114 if (wasPowered != mIsPowered || oldPlugType != mPlugType) { 1115 mDirty |= DIRTY_IS_POWERED; 1116 1117 // Update wireless dock detection state. 1118 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update( 1119 mIsPowered, mPlugType, mBatteryLevel); 1120 1121 // Treat plugging and unplugging the devices as a user activity. 1122 // Users find it disconcerting when they plug or unplug the device 1123 // and it shuts off right away. 1124 // Some devices also wake the device when plugged or unplugged because 1125 // they don't have a charging LED. 1126 final long now = SystemClock.uptimeMillis(); 1127 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType, 1128 dockedOnWirelessCharger)) { 1129 wakeUpNoUpdateLocked(now); 1130 } 1131 userActivityNoUpdateLocked( 1132 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1133 1134 // Tell the notifier whether wireless charging has started so that 1135 // it can provide feedback to the user. 1136 if (dockedOnWirelessCharger) { 1137 mNotifier.onWirelessChargingStarted(); 1138 } 1139 } 1140 } 1141 } 1142 1143 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked( 1144 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) { 1145 // Don't wake when powered unless configured to do so. 1146 if (!mWakeUpWhenPluggedOrUnpluggedConfig) { 1147 return false; 1148 } 1149 1150 // Don't wake when undocked from wireless charger. 1151 // See WirelessChargerDetector for justification. 1152 if (wasPowered && !mIsPowered 1153 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 1154 return false; 1155 } 1156 1157 // Don't wake when docked on wireless charger unless we are certain of it. 1158 // See WirelessChargerDetector for justification. 1159 if (!wasPowered && mIsPowered 1160 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS 1161 && !dockedOnWirelessCharger) { 1162 return false; 1163 } 1164 1165 // If already dreaming and becoming powered, then don't wake. 1166 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) { 1167 return false; 1168 } 1169 1170 // Otherwise wake up! 1171 return true; 1172 } 1173 1174 /** 1175 * Updates the value of mStayOn. 1176 * Sets DIRTY_STAY_ON if a change occurred. 1177 */ 1178 private void updateStayOnLocked(int dirty) { 1179 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 1180 final boolean wasStayOn = mStayOn; 1181 if (mStayOnWhilePluggedInSetting != 0 1182 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1183 mStayOn = mBatteryService.isPowered(mStayOnWhilePluggedInSetting); 1184 } else { 1185 mStayOn = false; 1186 } 1187 1188 if (mStayOn != wasStayOn) { 1189 mDirty |= DIRTY_STAY_ON; 1190 } 1191 } 1192 } 1193 1194 /** 1195 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 1196 * Note that most wake-locks are ignored when the system is asleep. 1197 * 1198 * This function must have no other side-effects. 1199 */ 1200 @SuppressWarnings("deprecation") 1201 private void updateWakeLockSummaryLocked(int dirty) { 1202 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 1203 mWakeLockSummary = 0; 1204 1205 final int numWakeLocks = mWakeLocks.size(); 1206 for (int i = 0; i < numWakeLocks; i++) { 1207 final WakeLock wakeLock = mWakeLocks.get(i); 1208 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1209 case PowerManager.PARTIAL_WAKE_LOCK: 1210 mWakeLockSummary |= WAKE_LOCK_CPU; 1211 break; 1212 case PowerManager.FULL_WAKE_LOCK: 1213 if (mWakefulness == WAKEFULNESS_AWAKE 1214 || mWakefulness == WAKEFULNESS_DREAMING) { 1215 mWakeLockSummary |= WAKE_LOCK_CPU 1216 | WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 1217 } 1218 if (mWakefulness == WAKEFULNESS_AWAKE) { 1219 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1220 } 1221 break; 1222 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1223 if (mWakefulness == WAKEFULNESS_AWAKE 1224 || mWakefulness == WAKEFULNESS_DREAMING) { 1225 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_BRIGHT; 1226 } 1227 if (mWakefulness == WAKEFULNESS_AWAKE) { 1228 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1229 } 1230 break; 1231 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1232 if (mWakefulness == WAKEFULNESS_AWAKE 1233 || mWakefulness == WAKEFULNESS_DREAMING) { 1234 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_SCREEN_DIM; 1235 } 1236 if (mWakefulness == WAKEFULNESS_AWAKE) { 1237 mWakeLockSummary |= WAKE_LOCK_STAY_AWAKE; 1238 } 1239 break; 1240 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1241 if (mWakefulness == WAKEFULNESS_AWAKE 1242 || mWakefulness == WAKEFULNESS_DREAMING 1243 || mWakefulness == WAKEFULNESS_DOZING) { 1244 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1245 } 1246 break; 1247 case PowerManager.DOZE_WAKE_LOCK: 1248 if (mWakefulness == WAKEFULNESS_DOZING) { 1249 mWakeLockSummary |= WAKE_LOCK_DOZE; 1250 } 1251 break; 1252 } 1253 } 1254 1255 if (DEBUG_SPEW) { 1256 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1257 + wakefulnessToString(mWakefulness) 1258 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1259 } 1260 } 1261 } 1262 1263 /** 1264 * Updates the value of mUserActivitySummary to summarize the user requested 1265 * state of the system such as whether the screen should be bright or dim. 1266 * Note that user activity is ignored when the system is asleep. 1267 * 1268 * This function must have no other side-effects. 1269 */ 1270 private void updateUserActivitySummaryLocked(long now, int dirty) { 1271 // Update the status of the user activity timeout timer. 1272 if ((dirty & (DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1273 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1274 1275 long nextTimeout = 0; 1276 if (mWakefulness == WAKEFULNESS_AWAKE 1277 || mWakefulness == WAKEFULNESS_DREAMING) { 1278 final int screenOffTimeout = getScreenOffTimeoutLocked(); 1279 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1280 1281 mUserActivitySummary = 0; 1282 if (mLastUserActivityTime >= mLastWakeTime) { 1283 nextTimeout = mLastUserActivityTime 1284 + screenOffTimeout - screenDimDuration; 1285 if (now < nextTimeout) { 1286 mUserActivitySummary |= USER_ACTIVITY_SCREEN_BRIGHT; 1287 } else { 1288 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1289 if (now < nextTimeout) { 1290 mUserActivitySummary |= USER_ACTIVITY_SCREEN_DIM; 1291 } 1292 } 1293 } 1294 if (mUserActivitySummary == 0 1295 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1296 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1297 if (now < nextTimeout 1298 && mDisplayPowerRequest.wantScreenOnNormal()) { 1299 mUserActivitySummary = mDisplayPowerRequest.screenState 1300 == DisplayPowerRequest.SCREEN_STATE_BRIGHT ? 1301 USER_ACTIVITY_SCREEN_BRIGHT : USER_ACTIVITY_SCREEN_DIM; 1302 } 1303 } 1304 if (mUserActivitySummary != 0) { 1305 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1306 msg.setAsynchronous(true); 1307 mHandler.sendMessageAtTime(msg, nextTimeout); 1308 } 1309 } else { 1310 mUserActivitySummary = 0; 1311 } 1312 1313 if (DEBUG_SPEW) { 1314 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1315 + wakefulnessToString(mWakefulness) 1316 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1317 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1318 } 1319 } 1320 } 1321 1322 /** 1323 * Called when a user activity timeout has occurred. 1324 * Simply indicates that something about user activity has changed so that the new 1325 * state can be recomputed when the power state is updated. 1326 * 1327 * This function must have no other side-effects besides setting the dirty 1328 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1329 */ 1330 private void handleUserActivityTimeout() { // runs on handler thread 1331 synchronized (mLock) { 1332 if (DEBUG_SPEW) { 1333 Slog.d(TAG, "handleUserActivityTimeout"); 1334 } 1335 1336 mDirty |= DIRTY_USER_ACTIVITY; 1337 updatePowerStateLocked(); 1338 } 1339 } 1340 1341 private int getScreenOffTimeoutLocked() { 1342 int timeout = mScreenOffTimeoutSetting; 1343 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1344 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1345 } 1346 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) { 1347 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager); 1348 } 1349 return Math.max(timeout, MINIMUM_SCREEN_OFF_TIMEOUT); 1350 } 1351 1352 private int getScreenDimDurationLocked(int screenOffTimeout) { 1353 return Math.min(SCREEN_DIM_DURATION, 1354 (int)(screenOffTimeout * MAXIMUM_SCREEN_DIM_RATIO)); 1355 } 1356 1357 /** 1358 * Updates the wakefulness of the device. 1359 * 1360 * This is the function that decides whether the device should start dreaming 1361 * based on the current wake locks and user activity state. It may modify mDirty 1362 * if the wakefulness changes. 1363 * 1364 * Returns true if the wakefulness changed and we need to restart power state calculation. 1365 */ 1366 private boolean updateWakefulnessLocked(int dirty) { 1367 boolean changed = false; 1368 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1369 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE 1370 | DIRTY_DOCK_STATE)) != 0) { 1371 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1372 if (DEBUG_SPEW) { 1373 Slog.d(TAG, "updateWakefulnessLocked: Bed time..."); 1374 } 1375 final long time = SystemClock.uptimeMillis(); 1376 if (shouldNapAtBedTimeLocked()) { 1377 changed = napNoUpdateLocked(time); 1378 } else { 1379 changed = goToSleepNoUpdateLocked(time, 1380 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1381 } 1382 } 1383 } 1384 return changed; 1385 } 1386 1387 /** 1388 * Returns true if the device should automatically nap and start dreaming when the user 1389 * activity timeout has expired and it's bedtime. 1390 */ 1391 private boolean shouldNapAtBedTimeLocked() { 1392 return mDreamsActivateOnSleepSetting 1393 || (mDreamsActivateOnDockSetting 1394 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED); 1395 } 1396 1397 /** 1398 * Returns true if the device should go to sleep now. 1399 * Also used when exiting a dream to determine whether we should go back 1400 * to being fully awake or else go to sleep for good. 1401 */ 1402 private boolean isItBedTimeYetLocked() { 1403 return mBootCompleted && !isBeingKeptAwakeLocked(); 1404 } 1405 1406 /** 1407 * Returns true if the device is being kept awake by a wake lock, user activity 1408 * or the stay on while powered setting. We also keep the phone awake when 1409 * the proximity sensor returns a positive result so that the device does not 1410 * lock while in a phone call. This function only controls whether the device 1411 * will go to sleep or dream which is independent of whether it will be allowed 1412 * to suspend. 1413 */ 1414 private boolean isBeingKeptAwakeLocked() { 1415 return mStayOn 1416 || mProximityPositive 1417 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0 1418 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1419 | USER_ACTIVITY_SCREEN_DIM)) != 0; 1420 } 1421 1422 /** 1423 * Determines whether to post a message to the sandman to update the dream state. 1424 */ 1425 private void updateDreamLocked(int dirty) { 1426 if ((dirty & (DIRTY_WAKEFULNESS 1427 | DIRTY_USER_ACTIVITY 1428 | DIRTY_WAKE_LOCKS 1429 | DIRTY_BOOT_COMPLETED 1430 | DIRTY_SETTINGS 1431 | DIRTY_IS_POWERED 1432 | DIRTY_STAY_ON 1433 | DIRTY_PROXIMITY_POSITIVE 1434 | DIRTY_BATTERY_STATE)) != 0) { 1435 scheduleSandmanLocked(); 1436 } 1437 } 1438 1439 private void scheduleSandmanLocked() { 1440 if (!mSandmanScheduled) { 1441 mSandmanScheduled = true; 1442 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1443 msg.setAsynchronous(true); 1444 mHandler.sendMessage(msg); 1445 } 1446 } 1447 1448 /** 1449 * Called when the device enters or exits a dreaming or dozing state. 1450 * 1451 * We do this asynchronously because we must call out of the power manager to start 1452 * the dream and we don't want to hold our lock while doing so. There is a risk that 1453 * the device will wake or go to sleep in the meantime so we have to handle that case. 1454 */ 1455 private void handleSandman() { // runs on handler thread 1456 // Handle preconditions. 1457 final boolean startDreaming; 1458 final int wakefulness; 1459 synchronized (mLock) { 1460 mSandmanScheduled = false; 1461 wakefulness = mWakefulness; 1462 if (mSandmanSummoned) { 1463 startDreaming = ((wakefulness == WAKEFULNESS_DREAMING && canDreamLocked()) 1464 || wakefulness == WAKEFULNESS_DOZING); 1465 mSandmanSummoned = false; 1466 } else { 1467 startDreaming = false; 1468 } 1469 } 1470 1471 // Start dreaming if needed. 1472 // We only control the dream on the handler thread, so we don't need to worry about 1473 // concurrent attempts to start or stop the dream. 1474 final boolean isDreaming; 1475 if (mDreamManager != null) { 1476 // Restart the dream whenever the sandman is summoned. 1477 if (startDreaming) { 1478 mDreamManager.stopDream(); 1479 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING); 1480 } 1481 isDreaming = mDreamManager.isDreaming(); 1482 } else { 1483 isDreaming = false; 1484 } 1485 1486 // Update dream state. 1487 synchronized (mLock) { 1488 // Remember the initial battery level when the dream started. 1489 if (startDreaming && isDreaming) { 1490 mBatteryLevelWhenDreamStarted = mBatteryLevel; 1491 if (wakefulness == WAKEFULNESS_DOZING) { 1492 Slog.i(TAG, "Dozing..."); 1493 } else { 1494 Slog.i(TAG, "Dreaming..."); 1495 } 1496 } 1497 1498 // If preconditions changed, wait for the next iteration to determine 1499 // whether the dream should continue (or be restarted). 1500 if (mSandmanSummoned || mWakefulness != wakefulness) { 1501 return; // wait for next cycle 1502 } 1503 1504 // Determine whether the dream should continue. 1505 if (wakefulness == WAKEFULNESS_DREAMING) { 1506 if (isDreaming && canDreamLocked()) { 1507 if (mDreamsBatteryLevelDrainCutoffConfig >= 0 1508 && mBatteryLevel < mBatteryLevelWhenDreamStarted 1509 - mDreamsBatteryLevelDrainCutoffConfig 1510 && !isBeingKeptAwakeLocked()) { 1511 // If the user activity timeout expired and the battery appears 1512 // to be draining faster than it is charging then stop dreaming 1513 // and go to sleep. 1514 Slog.i(TAG, "Stopping dream because the battery appears to " 1515 + "be draining faster than it is charging. " 1516 + "Battery level when dream started: " 1517 + mBatteryLevelWhenDreamStarted + "%. " 1518 + "Battery level now: " + mBatteryLevel + "%."); 1519 } else { 1520 return; // continue dreaming 1521 } 1522 } 1523 1524 // Dream has ended or will be stopped. Update the power state. 1525 if (isItBedTimeYetLocked()) { 1526 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1527 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1528 updatePowerStateLocked(); 1529 } else { 1530 wakeUpNoUpdateLocked(SystemClock.uptimeMillis()); 1531 updatePowerStateLocked(); 1532 } 1533 } else if (wakefulness == WAKEFULNESS_DOZING) { 1534 if (isDreaming) { 1535 return; // continue dozing 1536 } 1537 1538 // Doze has ended or will be stopped. Update the power state. 1539 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis()); 1540 updatePowerStateLocked(); 1541 } 1542 } 1543 1544 // Stop dream. 1545 if (isDreaming) { 1546 mDreamManager.stopDream(); 1547 } 1548 } 1549 1550 /** 1551 * Returns true if the device is allowed to dream in its current state. 1552 * This function is not called when dozing. 1553 */ 1554 private boolean canDreamLocked() { 1555 if (mWakefulness != WAKEFULNESS_DREAMING 1556 || !mDreamsSupportedConfig 1557 || !mDreamsEnabledSetting 1558 || !mDisplayPowerRequest.wantScreenOnNormal() 1559 || !mBootCompleted) { 1560 return false; 1561 } 1562 if (!isBeingKeptAwakeLocked()) { 1563 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) { 1564 return false; 1565 } 1566 if (!mIsPowered 1567 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0 1568 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) { 1569 return false; 1570 } 1571 if (mIsPowered 1572 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0 1573 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) { 1574 return false; 1575 } 1576 } 1577 return true; 1578 } 1579 1580 private void handleScreenOnBlockerReleased() { 1581 synchronized (mLock) { 1582 mDirty |= DIRTY_SCREEN_ON_BLOCKER_RELEASED; 1583 updatePowerStateLocked(); 1584 } 1585 } 1586 1587 /** 1588 * Updates the display power state asynchronously. 1589 * When the update is finished, mDisplayReady will be set to true. The display 1590 * controller posts a message to tell us when the actual display power state 1591 * has been updated so we come back here to double-check and finish up. 1592 * 1593 * This function recalculates the display power state each time. 1594 */ 1595 private void updateDisplayPowerStateLocked(int dirty) { 1596 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1597 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1598 | DIRTY_SETTINGS | DIRTY_SCREEN_ON_BLOCKER_RELEASED)) != 0) { 1599 final int newScreenState = getDesiredScreenPowerStateLocked(); 1600 mDisplayPowerRequest.screenState = newScreenState; 1601 nativeSetPowerState(isScreenOnLocked(), 1602 newScreenState == DisplayPowerRequest.SCREEN_STATE_BRIGHT); 1603 1604 int screenBrightness = mScreenBrightnessSettingDefault; 1605 float screenAutoBrightnessAdjustment = 0.0f; 1606 boolean autoBrightness = (mScreenBrightnessModeSetting == 1607 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 1608 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 1609 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 1610 autoBrightness = false; 1611 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 1612 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 1613 } else if (isValidBrightness(mScreenBrightnessSetting)) { 1614 screenBrightness = mScreenBrightnessSetting; 1615 } 1616 if (autoBrightness) { 1617 screenBrightness = mScreenBrightnessSettingDefault; 1618 if (isValidAutoBrightnessAdjustment( 1619 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 1620 screenAutoBrightnessAdjustment = 1621 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 1622 } else if (isValidAutoBrightnessAdjustment( 1623 mScreenAutoBrightnessAdjustmentSetting)) { 1624 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 1625 } 1626 } 1627 screenBrightness = Math.max(Math.min(screenBrightness, 1628 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 1629 screenAutoBrightnessAdjustment = Math.max(Math.min( 1630 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 1631 mDisplayPowerRequest.screenBrightness = screenBrightness; 1632 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 1633 screenAutoBrightnessAdjustment; 1634 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 1635 1636 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 1637 1638 mDisplayPowerRequest.blockScreenOn = mScreenOnBlocker.isHeld(); 1639 1640 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest, 1641 mRequestWaitForNegativeProximity); 1642 mRequestWaitForNegativeProximity = false; 1643 1644 if (DEBUG_SPEW) { 1645 Slog.d(TAG, "updateScreenStateLocked: mDisplayReady=" + mDisplayReady 1646 + ", newScreenState=" + newScreenState 1647 + ", mWakefulness=" + mWakefulness 1648 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 1649 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1650 + ", mBootCompleted=" + mBootCompleted); 1651 } 1652 } 1653 } 1654 1655 private static boolean isValidBrightness(int value) { 1656 return value >= 0 && value <= 255; 1657 } 1658 1659 private static boolean isValidAutoBrightnessAdjustment(float value) { 1660 // Handles NaN by always returning false. 1661 return value >= -1.0f && value <= 1.0f; 1662 } 1663 1664 private int getDesiredScreenPowerStateLocked() { 1665 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1666 return DisplayPowerRequest.SCREEN_STATE_OFF; 1667 } 1668 1669 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 1670 return DisplayPowerRequest.SCREEN_STATE_DOZE; 1671 } 1672 1673 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 1674 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 1675 || !mBootCompleted) { 1676 return DisplayPowerRequest.SCREEN_STATE_BRIGHT; 1677 } 1678 1679 return DisplayPowerRequest.SCREEN_STATE_DIM; 1680 } 1681 1682 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks = 1683 new DisplayManagerInternal.DisplayPowerCallbacks() { 1684 private boolean mBlanked; 1685 1686 @Override 1687 public void onStateChanged() { 1688 synchronized (mLock) { 1689 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 1690 updatePowerStateLocked(); 1691 } 1692 } 1693 1694 @Override 1695 public void onProximityPositive() { 1696 synchronized (mLock) { 1697 mProximityPositive = true; 1698 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1699 updatePowerStateLocked(); 1700 } 1701 } 1702 1703 @Override 1704 public void onProximityNegative() { 1705 synchronized (mLock) { 1706 mProximityPositive = false; 1707 mDirty |= DIRTY_PROXIMITY_POSITIVE; 1708 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 1709 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1710 updatePowerStateLocked(); 1711 } 1712 } 1713 1714 @Override 1715 public void acquireSuspendBlocker() { 1716 mDisplaySuspendBlocker.acquire(); 1717 } 1718 1719 @Override 1720 public void releaseSuspendBlocker() { 1721 mDisplaySuspendBlocker.release(); 1722 } 1723 1724 @Override 1725 public void blankAllDisplays() { 1726 synchronized (this) { 1727 mBlanked = true; 1728 mDisplayManagerInternal.blankAllDisplaysFromPowerManager(); 1729 if (!mDecoupleInteractiveModeFromDisplayConfig) { 1730 setInteractiveModeLocked(false); 1731 } 1732 if (!mDecoupleAutoSuspendModeFromDisplayConfig) { 1733 setAutoSuspendModeLocked(true); 1734 } 1735 } 1736 } 1737 1738 @Override 1739 public void unblankAllDisplays() { 1740 synchronized (this) { 1741 if (!mDecoupleAutoSuspendModeFromDisplayConfig) { 1742 setAutoSuspendModeLocked(false); 1743 } 1744 if (!mDecoupleInteractiveModeFromDisplayConfig) { 1745 setInteractiveModeLocked(true); 1746 } 1747 mDisplayManagerInternal.unblankAllDisplaysFromPowerManager(); 1748 mBlanked = false; 1749 } 1750 } 1751 1752 @Override 1753 public String toString() { 1754 synchronized (this) { 1755 return "blanked=" + mBlanked; 1756 } 1757 } 1758 }; 1759 1760 private boolean shouldUseProximitySensorLocked() { 1761 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 1762 } 1763 1764 /** 1765 * Updates the suspend blocker that keeps the CPU alive. 1766 * 1767 * This function must have no other side-effects. 1768 */ 1769 private void updateSuspendBlockerLocked() { 1770 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0); 1771 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked(); 1772 final boolean autoSuspend = !needDisplaySuspendBlocker; 1773 1774 // Disable auto-suspend if needed. 1775 if (!autoSuspend) { 1776 if (mDecoupleAutoSuspendModeFromDisplayConfig) { 1777 setAutoSuspendModeLocked(false); 1778 } 1779 if (mDecoupleInteractiveModeFromDisplayConfig) { 1780 setInteractiveModeLocked(true); 1781 } 1782 } 1783 1784 // First acquire suspend blockers if needed. 1785 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) { 1786 mWakeLockSuspendBlocker.acquire(); 1787 mHoldingWakeLockSuspendBlocker = true; 1788 } 1789 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) { 1790 mDisplaySuspendBlocker.acquire(); 1791 mHoldingDisplaySuspendBlocker = true; 1792 } 1793 1794 // Then release suspend blockers if needed. 1795 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) { 1796 mWakeLockSuspendBlocker.release(); 1797 mHoldingWakeLockSuspendBlocker = false; 1798 } 1799 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) { 1800 mDisplaySuspendBlocker.release(); 1801 mHoldingDisplaySuspendBlocker = false; 1802 } 1803 1804 // Enable auto-suspend if needed. 1805 if (autoSuspend) { 1806 if (mDecoupleInteractiveModeFromDisplayConfig) { 1807 setInteractiveModeLocked(false); 1808 } 1809 if (mDecoupleAutoSuspendModeFromDisplayConfig) { 1810 setAutoSuspendModeLocked(true); 1811 } 1812 } 1813 } 1814 1815 /** 1816 * Return true if we must keep a suspend blocker active on behalf of the display. 1817 * We do so if the screen is on or is in transition between states. 1818 */ 1819 private boolean needDisplaySuspendBlockerLocked() { 1820 if (!mDisplayReady) { 1821 return true; 1822 } 1823 if (mDisplayPowerRequest.wantScreenOnNormal()) { 1824 // If we asked for the screen to be on but it is off due to the proximity 1825 // sensor then we may suspend but only if the configuration allows it. 1826 // On some hardware it may not be safe to suspend because the proximity 1827 // sensor may not be correctly configured as a wake-up source. 1828 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive 1829 || !mSuspendWhenScreenOffDueToProximityConfig) { 1830 return true; 1831 } 1832 } 1833 // Let the system suspend if the screen is off or dozing. 1834 return false; 1835 } 1836 1837 private void setAutoSuspendModeLocked(boolean enable) { 1838 if (enable != mAutoSuspendModeEnabled) { 1839 if (DEBUG) { 1840 Slog.d(TAG, "Setting auto-suspend mode to " + enable); 1841 } 1842 mAutoSuspendModeEnabled = enable; 1843 nativeSetAutoSuspend(enable); 1844 } 1845 } 1846 1847 private void setInteractiveModeLocked(boolean enable) { 1848 if (enable != mInteractiveModeEnabled) { 1849 if (DEBUG) { 1850 Slog.d(TAG, "Setting interactive mode to " + enable); 1851 } 1852 mInteractiveModeEnabled = enable; 1853 nativeSetInteractive(enable); 1854 } 1855 } 1856 1857 private boolean isScreenOnInternal() { 1858 synchronized (mLock) { 1859 // XXX This is a temporary hack to let certain parts of the system pretend the 1860 // screen is still on even when dozing and we would normally want to report 1861 // screen off. Will be removed when the window manager is modified to use 1862 // the true blanking state of the display. 1863 return isScreenOnLocked() 1864 || mWakefulness == WAKEFULNESS_DOZING; 1865 } 1866 } 1867 1868 private boolean isScreenOnLocked() { 1869 return mWakefulness == WAKEFULNESS_AWAKE 1870 || mWakefulness == WAKEFULNESS_DREAMING; 1871 } 1872 1873 private void handleBatteryStateChangedLocked() { 1874 mDirty |= DIRTY_BATTERY_STATE; 1875 updatePowerStateLocked(); 1876 } 1877 1878 private void startWatchingForBootAnimationFinished() { 1879 mHandler.sendEmptyMessage(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED); 1880 } 1881 1882 private void checkIfBootAnimationFinished() { 1883 if (DEBUG) { 1884 Slog.d(TAG, "Check if boot animation finished..."); 1885 } 1886 1887 if (SystemService.isRunning(BOOT_ANIMATION_SERVICE)) { 1888 mHandler.sendEmptyMessageDelayed(MSG_CHECK_IF_BOOT_ANIMATION_FINISHED, 1889 BOOT_ANIMATION_POLL_INTERVAL); 1890 return; 1891 } 1892 1893 synchronized (mLock) { 1894 if (!mBootCompleted) { 1895 Slog.i(TAG, "Boot animation finished."); 1896 handleBootCompletedLocked(); 1897 } 1898 } 1899 } 1900 1901 private void handleBootCompletedLocked() { 1902 final long now = SystemClock.uptimeMillis(); 1903 mBootCompleted = true; 1904 mDirty |= DIRTY_BOOT_COMPLETED; 1905 userActivityNoUpdateLocked( 1906 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1907 updatePowerStateLocked(); 1908 } 1909 1910 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm, 1911 final String reason, boolean wait) { 1912 if (mHandler == null || !mSystemReady) { 1913 throw new IllegalStateException("Too early to call shutdown() or reboot()"); 1914 } 1915 1916 Runnable runnable = new Runnable() { 1917 @Override 1918 public void run() { 1919 synchronized (this) { 1920 if (shutdown) { 1921 ShutdownThread.shutdown(mContext, confirm); 1922 } else { 1923 ShutdownThread.reboot(mContext, reason, confirm); 1924 } 1925 } 1926 } 1927 }; 1928 1929 // ShutdownThread must run on a looper capable of displaying the UI. 1930 Message msg = Message.obtain(mHandler, runnable); 1931 msg.setAsynchronous(true); 1932 mHandler.sendMessage(msg); 1933 1934 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 1935 if (wait) { 1936 synchronized (runnable) { 1937 while (true) { 1938 try { 1939 runnable.wait(); 1940 } catch (InterruptedException e) { 1941 } 1942 } 1943 } 1944 } 1945 } 1946 1947 private void crashInternal(final String message) { 1948 Thread t = new Thread("PowerManagerService.crash()") { 1949 @Override 1950 public void run() { 1951 throw new RuntimeException(message); 1952 } 1953 }; 1954 try { 1955 t.start(); 1956 t.join(); 1957 } catch (InterruptedException e) { 1958 Log.wtf(TAG, e); 1959 } 1960 } 1961 1962 private void setStayOnSettingInternal(int val) { 1963 Settings.Global.putInt(mContext.getContentResolver(), 1964 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 1965 } 1966 1967 private void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 1968 synchronized (mLock) { 1969 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 1970 mDirty |= DIRTY_SETTINGS; 1971 updatePowerStateLocked(); 1972 } 1973 } 1974 1975 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 1976 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 1977 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 1978 } 1979 1980 private void setAttentionLightInternal(boolean on, int color) { 1981 Light light; 1982 synchronized (mLock) { 1983 if (!mSystemReady) { 1984 return; 1985 } 1986 light = mAttentionLight; 1987 } 1988 1989 // Control light outside of lock. 1990 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 1991 } 1992 1993 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 1994 synchronized (mLock) { 1995 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 1996 mScreenBrightnessOverrideFromWindowManager = brightness; 1997 mDirty |= DIRTY_SETTINGS; 1998 updatePowerStateLocked(); 1999 } 2000 } 2001 } 2002 2003 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 2004 synchronized (mLock) { 2005 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 2006 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 2007 mDirty |= DIRTY_SETTINGS; 2008 updatePowerStateLocked(); 2009 } 2010 } 2011 } 2012 2013 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 2014 synchronized (mLock) { 2015 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 2016 mTemporaryScreenBrightnessSettingOverride = brightness; 2017 mDirty |= DIRTY_SETTINGS; 2018 updatePowerStateLocked(); 2019 } 2020 } 2021 } 2022 2023 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 2024 synchronized (mLock) { 2025 // Note: This condition handles NaN because NaN is not equal to any other 2026 // value, including itself. 2027 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 2028 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 2029 mDirty |= DIRTY_SETTINGS; 2030 updatePowerStateLocked(); 2031 } 2032 } 2033 } 2034 2035 /** 2036 * Low-level function turn the device off immediately, without trying 2037 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 2038 */ 2039 public static void lowLevelShutdown() { 2040 SystemProperties.set("sys.powerctl", "shutdown"); 2041 } 2042 2043 /** 2044 * Low-level function to reboot the device. On success, this 2045 * function doesn't return. If more than 20 seconds passes from 2046 * the time a reboot is requested (120 seconds for reboot to 2047 * recovery), this method returns. 2048 * 2049 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 2050 */ 2051 public static void lowLevelReboot(String reason) { 2052 if (reason == null) { 2053 reason = ""; 2054 } 2055 long duration; 2056 if (reason.equals(PowerManager.REBOOT_RECOVERY)) { 2057 // If we are rebooting to go into recovery, instead of 2058 // setting sys.powerctl directly we'll start the 2059 // pre-recovery service which will do some preparation for 2060 // recovery and then reboot for us. 2061 // 2062 // This preparation can take more than 20 seconds if 2063 // there's a very large update package, so lengthen the 2064 // timeout. 2065 SystemProperties.set("ctl.start", "pre-recovery"); 2066 duration = 120 * 1000L; 2067 } else { 2068 SystemProperties.set("sys.powerctl", "reboot," + reason); 2069 duration = 20 * 1000L; 2070 } 2071 try { 2072 Thread.sleep(duration); 2073 } catch (InterruptedException e) { 2074 Thread.currentThread().interrupt(); 2075 } 2076 } 2077 2078 @Override // Watchdog.Monitor implementation 2079 public void monitor() { 2080 // Grab and release lock for watchdog monitor to detect deadlocks. 2081 synchronized (mLock) { 2082 } 2083 } 2084 2085 private void dumpInternal(PrintWriter pw) { 2086 pw.println("POWER MANAGER (dumpsys power)\n"); 2087 2088 final WirelessChargerDetector wcd; 2089 synchronized (mLock) { 2090 pw.println("Power Manager State:"); 2091 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 2092 pw.println(" mWakefulness=" + wakefulnessToString(mWakefulness)); 2093 pw.println(" mIsPowered=" + mIsPowered); 2094 pw.println(" mPlugType=" + mPlugType); 2095 pw.println(" mBatteryLevel=" + mBatteryLevel); 2096 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted); 2097 pw.println(" mDockState=" + mDockState); 2098 pw.println(" mStayOn=" + mStayOn); 2099 pw.println(" mProximityPositive=" + mProximityPositive); 2100 pw.println(" mBootCompleted=" + mBootCompleted); 2101 pw.println(" mSystemReady=" + mSystemReady); 2102 pw.println(" mAutoSuspendModeEnabled=" + mAutoSuspendModeEnabled); 2103 pw.println(" mInteactiveModeEnabled=" + mInteractiveModeEnabled); 2104 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 2105 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 2106 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 2107 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 2108 pw.println(" mSandmanSummoned=" + mSandmanSummoned); 2109 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 2110 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 2111 pw.println(" mSendWakeUpFinishedNotificationWhenReady=" 2112 + mSendWakeUpFinishedNotificationWhenReady); 2113 pw.println(" mSendGoToSleepFinishedNotificationWhenReady=" 2114 + mSendGoToSleepFinishedNotificationWhenReady); 2115 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 2116 pw.println(" mLastUserActivityTimeNoChangeLights=" 2117 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 2118 pw.println(" mDisplayReady=" + mDisplayReady); 2119 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 2120 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker); 2121 2122 pw.println(); 2123 pw.println("Settings and Configuration:"); 2124 pw.println(" mDecoupleAutoSuspendModeFromDisplayConfig=" 2125 + mDecoupleAutoSuspendModeFromDisplayConfig); 2126 pw.println(" mDecoupleInteractiveModeFromDisplayConfig=" 2127 + mDecoupleInteractiveModeFromDisplayConfig); 2128 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig=" 2129 + mWakeUpWhenPluggedOrUnpluggedConfig); 2130 pw.println(" mSuspendWhenScreenOffDueToProximityConfig=" 2131 + mSuspendWhenScreenOffDueToProximityConfig); 2132 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 2133 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig); 2134 pw.println(" mDreamsActivatedOnSleepByDefaultConfig=" 2135 + mDreamsActivatedOnSleepByDefaultConfig); 2136 pw.println(" mDreamsActivatedOnDockByDefaultConfig=" 2137 + mDreamsActivatedOnDockByDefaultConfig); 2138 pw.println(" mDreamsEnabledOnBatteryConfig=" 2139 + mDreamsEnabledOnBatteryConfig); 2140 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig=" 2141 + mDreamsBatteryLevelMinimumWhenPoweredConfig); 2142 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig=" 2143 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig); 2144 pw.println(" mDreamsBatteryLevelDrainCutoffConfig=" 2145 + mDreamsBatteryLevelDrainCutoffConfig); 2146 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 2147 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 2148 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting); 2149 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 2150 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 2151 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 2152 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 2153 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 2154 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 2155 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 2156 + mScreenAutoBrightnessAdjustmentSetting); 2157 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 2158 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 2159 + mScreenBrightnessOverrideFromWindowManager); 2160 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 2161 + mUserActivityTimeoutOverrideFromWindowManager); 2162 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 2163 + mTemporaryScreenBrightnessSettingOverride); 2164 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 2165 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 2166 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 2167 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 2168 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 2169 2170 final int screenOffTimeout = getScreenOffTimeoutLocked(); 2171 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 2172 pw.println(); 2173 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2174 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2175 2176 pw.println(); 2177 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2178 for (WakeLock wl : mWakeLocks) { 2179 pw.println(" " + wl); 2180 } 2181 2182 pw.println(); 2183 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2184 for (SuspendBlocker sb : mSuspendBlockers) { 2185 pw.println(" " + sb); 2186 } 2187 2188 pw.println(); 2189 pw.println("Screen On Blocker: " + mScreenOnBlocker); 2190 2191 pw.println(); 2192 pw.println("Display Power: " + mDisplayPowerCallbacks); 2193 2194 wcd = mWirelessChargerDetector; 2195 } 2196 2197 if (wcd != null) { 2198 wcd.dump(pw); 2199 } 2200 } 2201 2202 private SuspendBlocker createSuspendBlockerLocked(String name) { 2203 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2204 mSuspendBlockers.add(suspendBlocker); 2205 return suspendBlocker; 2206 } 2207 2208 private static String wakefulnessToString(int wakefulness) { 2209 switch (wakefulness) { 2210 case WAKEFULNESS_ASLEEP: 2211 return "Asleep"; 2212 case WAKEFULNESS_AWAKE: 2213 return "Awake"; 2214 case WAKEFULNESS_DREAMING: 2215 return "Dreaming"; 2216 case WAKEFULNESS_DOZING: 2217 return "Dozing"; 2218 default: 2219 return Integer.toString(wakefulness); 2220 } 2221 } 2222 2223 private static WorkSource copyWorkSource(WorkSource workSource) { 2224 return workSource != null ? new WorkSource(workSource) : null; 2225 } 2226 2227 private final class BatteryReceiver extends BroadcastReceiver { 2228 @Override 2229 public void onReceive(Context context, Intent intent) { 2230 synchronized (mLock) { 2231 handleBatteryStateChangedLocked(); 2232 } 2233 } 2234 } 2235 2236 private final class BootCompletedReceiver extends BroadcastReceiver { 2237 @Override 2238 public void onReceive(Context context, Intent intent) { 2239 // This is our early signal that the system thinks it has finished booting. 2240 // However, the boot animation may still be running for a few more seconds 2241 // since it is ultimately in charge of when it terminates. 2242 // Defer transitioning into the boot completed state until the animation exits. 2243 // We do this so that the screen does not start to dim prematurely before 2244 // the user has actually had a chance to interact with the device. 2245 startWatchingForBootAnimationFinished(); 2246 } 2247 } 2248 2249 private final class DreamReceiver extends BroadcastReceiver { 2250 @Override 2251 public void onReceive(Context context, Intent intent) { 2252 synchronized (mLock) { 2253 scheduleSandmanLocked(); 2254 } 2255 } 2256 } 2257 2258 private final class UserSwitchedReceiver extends BroadcastReceiver { 2259 @Override 2260 public void onReceive(Context context, Intent intent) { 2261 synchronized (mLock) { 2262 handleSettingsChangedLocked(); 2263 } 2264 } 2265 } 2266 2267 private final class DockReceiver extends BroadcastReceiver { 2268 @Override 2269 public void onReceive(Context context, Intent intent) { 2270 synchronized (mLock) { 2271 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2272 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2273 if (mDockState != dockState) { 2274 mDockState = dockState; 2275 mDirty |= DIRTY_DOCK_STATE; 2276 updatePowerStateLocked(); 2277 } 2278 } 2279 } 2280 } 2281 2282 private final class SettingsObserver extends ContentObserver { 2283 public SettingsObserver(Handler handler) { 2284 super(handler); 2285 } 2286 2287 @Override 2288 public void onChange(boolean selfChange, Uri uri) { 2289 synchronized (mLock) { 2290 handleSettingsChangedLocked(); 2291 } 2292 } 2293 } 2294 2295 /** 2296 * Handler for asynchronous operations performed by the power manager. 2297 */ 2298 private final class PowerManagerHandler extends Handler { 2299 public PowerManagerHandler(Looper looper) { 2300 super(looper, null, true /*async*/); 2301 } 2302 2303 @Override 2304 public void handleMessage(Message msg) { 2305 switch (msg.what) { 2306 case MSG_USER_ACTIVITY_TIMEOUT: 2307 handleUserActivityTimeout(); 2308 break; 2309 case MSG_SANDMAN: 2310 handleSandman(); 2311 break; 2312 case MSG_SCREEN_ON_BLOCKER_RELEASED: 2313 handleScreenOnBlockerReleased(); 2314 break; 2315 case MSG_CHECK_IF_BOOT_ANIMATION_FINISHED: 2316 checkIfBootAnimationFinished(); 2317 break; 2318 } 2319 } 2320 } 2321 2322 /** 2323 * Represents a wake lock that has been acquired by an application. 2324 */ 2325 private final class WakeLock implements IBinder.DeathRecipient { 2326 public final IBinder mLock; 2327 public int mFlags; 2328 public String mTag; 2329 public final String mPackageName; 2330 public WorkSource mWorkSource; 2331 public String mHistoryTag; 2332 public final int mOwnerUid; 2333 public final int mOwnerPid; 2334 public boolean mNotifiedAcquired; 2335 2336 public WakeLock(IBinder lock, int flags, String tag, String packageName, 2337 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 2338 mLock = lock; 2339 mFlags = flags; 2340 mTag = tag; 2341 mPackageName = packageName; 2342 mWorkSource = copyWorkSource(workSource); 2343 mHistoryTag = historyTag; 2344 mOwnerUid = ownerUid; 2345 mOwnerPid = ownerPid; 2346 } 2347 2348 @Override 2349 public void binderDied() { 2350 PowerManagerService.this.handleWakeLockDeath(this); 2351 } 2352 2353 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 2354 int ownerUid, int ownerPid) { 2355 return mFlags == flags 2356 && mTag.equals(tag) 2357 && hasSameWorkSource(workSource) 2358 && mOwnerUid == ownerUid 2359 && mOwnerPid == ownerPid; 2360 } 2361 2362 public void updateProperties(int flags, String tag, String packageName, 2363 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 2364 if (!mPackageName.equals(packageName)) { 2365 throw new IllegalStateException("Existing wake lock package name changed: " 2366 + mPackageName + " to " + packageName); 2367 } 2368 if (mOwnerUid != ownerUid) { 2369 throw new IllegalStateException("Existing wake lock uid changed: " 2370 + mOwnerUid + " to " + ownerUid); 2371 } 2372 if (mOwnerPid != ownerPid) { 2373 throw new IllegalStateException("Existing wake lock pid changed: " 2374 + mOwnerPid + " to " + ownerPid); 2375 } 2376 mFlags = flags; 2377 mTag = tag; 2378 updateWorkSource(workSource); 2379 mHistoryTag = historyTag; 2380 } 2381 2382 public boolean hasSameWorkSource(WorkSource workSource) { 2383 return Objects.equal(mWorkSource, workSource); 2384 } 2385 2386 public void updateWorkSource(WorkSource workSource) { 2387 mWorkSource = copyWorkSource(workSource); 2388 } 2389 2390 @Override 2391 public String toString() { 2392 return getLockLevelString() 2393 + " '" + mTag + "'" + getLockFlagsString() 2394 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 2395 } 2396 2397 @SuppressWarnings("deprecation") 2398 private String getLockLevelString() { 2399 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 2400 case PowerManager.FULL_WAKE_LOCK: 2401 return "FULL_WAKE_LOCK "; 2402 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 2403 return "SCREEN_BRIGHT_WAKE_LOCK "; 2404 case PowerManager.SCREEN_DIM_WAKE_LOCK: 2405 return "SCREEN_DIM_WAKE_LOCK "; 2406 case PowerManager.PARTIAL_WAKE_LOCK: 2407 return "PARTIAL_WAKE_LOCK "; 2408 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 2409 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 2410 case PowerManager.DOZE_WAKE_LOCK: 2411 return "DOZE_WAKE_LOCK "; 2412 default: 2413 return "??? "; 2414 } 2415 } 2416 2417 private String getLockFlagsString() { 2418 String result = ""; 2419 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 2420 result += " ACQUIRE_CAUSES_WAKEUP"; 2421 } 2422 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 2423 result += " ON_AFTER_RELEASE"; 2424 } 2425 return result; 2426 } 2427 } 2428 2429 private final class SuspendBlockerImpl implements SuspendBlocker { 2430 private final String mName; 2431 private int mReferenceCount; 2432 2433 public SuspendBlockerImpl(String name) { 2434 mName = name; 2435 } 2436 2437 @Override 2438 protected void finalize() throws Throwable { 2439 try { 2440 if (mReferenceCount != 0) { 2441 Log.wtf(TAG, "Suspend blocker \"" + mName 2442 + "\" was finalized without being released!"); 2443 mReferenceCount = 0; 2444 nativeReleaseSuspendBlocker(mName); 2445 } 2446 } finally { 2447 super.finalize(); 2448 } 2449 } 2450 2451 @Override 2452 public void acquire() { 2453 synchronized (this) { 2454 mReferenceCount += 1; 2455 if (mReferenceCount == 1) { 2456 if (DEBUG_SPEW) { 2457 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\"."); 2458 } 2459 nativeAcquireSuspendBlocker(mName); 2460 } 2461 } 2462 } 2463 2464 @Override 2465 public void release() { 2466 synchronized (this) { 2467 mReferenceCount -= 1; 2468 if (mReferenceCount == 0) { 2469 if (DEBUG_SPEW) { 2470 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\"."); 2471 } 2472 nativeReleaseSuspendBlocker(mName); 2473 } else if (mReferenceCount < 0) { 2474 Log.wtf(TAG, "Suspend blocker \"" + mName 2475 + "\" was released without being acquired!", new Throwable()); 2476 mReferenceCount = 0; 2477 } 2478 } 2479 } 2480 2481 @Override 2482 public String toString() { 2483 synchronized (this) { 2484 return mName + ": ref count=" + mReferenceCount; 2485 } 2486 } 2487 } 2488 2489 private final class ScreenOnBlockerImpl implements ScreenOnBlocker { 2490 private int mNestCount; 2491 2492 public boolean isHeld() { 2493 synchronized (this) { 2494 return mNestCount != 0; 2495 } 2496 } 2497 2498 @Override 2499 public void acquire() { 2500 synchronized (this) { 2501 mNestCount += 1; 2502 if (DEBUG) { 2503 Slog.d(TAG, "Screen on blocked: mNestCount=" + mNestCount); 2504 } 2505 } 2506 } 2507 2508 @Override 2509 public void release() { 2510 synchronized (this) { 2511 mNestCount -= 1; 2512 if (mNestCount < 0) { 2513 Log.wtf(TAG, "Screen on blocker was released without being acquired!", 2514 new Throwable()); 2515 mNestCount = 0; 2516 } 2517 if (mNestCount == 0) { 2518 mHandler.sendEmptyMessage(MSG_SCREEN_ON_BLOCKER_RELEASED); 2519 } 2520 if (DEBUG) { 2521 Slog.d(TAG, "Screen on unblocked: mNestCount=" + mNestCount); 2522 } 2523 } 2524 } 2525 2526 @Override 2527 public String toString() { 2528 synchronized (this) { 2529 return "held=" + (mNestCount != 0) + ", mNestCount=" + mNestCount; 2530 } 2531 } 2532 } 2533 2534 private final class BinderService extends IPowerManager.Stub { 2535 @Override // Binder call 2536 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag, 2537 String packageName, int uid) { 2538 if (uid < 0) { 2539 uid = Binder.getCallingUid(); 2540 } 2541 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null); 2542 } 2543 2544 @Override // Binder call 2545 public void powerHint(int hintId, int data) { 2546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2547 nativeSendPowerHint(hintId, data); 2548 } 2549 2550 @Override // Binder call 2551 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName, 2552 WorkSource ws, String historyTag) { 2553 if (lock == null) { 2554 throw new IllegalArgumentException("lock must not be null"); 2555 } 2556 if (packageName == null) { 2557 throw new IllegalArgumentException("packageName must not be null"); 2558 } 2559 PowerManager.validateWakeLockParameters(flags, tag); 2560 2561 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2562 if (ws != null && ws.size() != 0) { 2563 mContext.enforceCallingOrSelfPermission( 2564 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 2565 } else { 2566 ws = null; 2567 } 2568 2569 final int uid = Binder.getCallingUid(); 2570 final int pid = Binder.getCallingPid(); 2571 final long ident = Binder.clearCallingIdentity(); 2572 try { 2573 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid); 2574 } finally { 2575 Binder.restoreCallingIdentity(ident); 2576 } 2577 } 2578 2579 @Override // Binder call 2580 public void releaseWakeLock(IBinder lock, int flags) { 2581 if (lock == null) { 2582 throw new IllegalArgumentException("lock must not be null"); 2583 } 2584 2585 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2586 2587 final long ident = Binder.clearCallingIdentity(); 2588 try { 2589 releaseWakeLockInternal(lock, flags); 2590 } finally { 2591 Binder.restoreCallingIdentity(ident); 2592 } 2593 } 2594 2595 @Override // Binder call 2596 public void updateWakeLockUids(IBinder lock, int[] uids) { 2597 WorkSource ws = null; 2598 2599 if (uids != null) { 2600 ws = new WorkSource(); 2601 // XXX should WorkSource have a way to set uids as an int[] instead of adding them 2602 // one at a time? 2603 for (int i = 0; i < uids.length; i++) { 2604 ws.add(uids[i]); 2605 } 2606 } 2607 updateWakeLockWorkSource(lock, ws, null); 2608 } 2609 2610 @Override // Binder call 2611 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) { 2612 if (lock == null) { 2613 throw new IllegalArgumentException("lock must not be null"); 2614 } 2615 2616 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 2617 if (ws != null && ws.size() != 0) { 2618 mContext.enforceCallingOrSelfPermission( 2619 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 2620 } else { 2621 ws = null; 2622 } 2623 2624 final long ident = Binder.clearCallingIdentity(); 2625 try { 2626 updateWakeLockWorkSourceInternal(lock, ws, historyTag); 2627 } finally { 2628 Binder.restoreCallingIdentity(ident); 2629 } 2630 } 2631 2632 @Override // Binder call 2633 public boolean isWakeLockLevelSupported(int level) { 2634 final long ident = Binder.clearCallingIdentity(); 2635 try { 2636 return isWakeLockLevelSupportedInternal(level); 2637 } finally { 2638 Binder.restoreCallingIdentity(ident); 2639 } 2640 } 2641 2642 @Override // Binder call 2643 public void userActivity(long eventTime, int event, int flags) { 2644 final long now = SystemClock.uptimeMillis(); 2645 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 2646 != PackageManager.PERMISSION_GRANTED) { 2647 // Once upon a time applications could call userActivity(). 2648 // Now we require the DEVICE_POWER permission. Log a warning and ignore the 2649 // request instead of throwing a SecurityException so we don't break old apps. 2650 synchronized (mLock) { 2651 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) { 2652 mLastWarningAboutUserActivityPermission = now; 2653 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the " 2654 + "caller does not have DEVICE_POWER permission. " 2655 + "Please fix your app! " 2656 + " pid=" + Binder.getCallingPid() 2657 + " uid=" + Binder.getCallingUid()); 2658 } 2659 } 2660 return; 2661 } 2662 2663 if (eventTime > SystemClock.uptimeMillis()) { 2664 throw new IllegalArgumentException("event time must not be in the future"); 2665 } 2666 2667 final int uid = Binder.getCallingUid(); 2668 final long ident = Binder.clearCallingIdentity(); 2669 try { 2670 userActivityInternal(eventTime, event, flags, uid); 2671 } finally { 2672 Binder.restoreCallingIdentity(ident); 2673 } 2674 } 2675 2676 @Override // Binder call 2677 public void wakeUp(long eventTime) { 2678 if (eventTime > SystemClock.uptimeMillis()) { 2679 throw new IllegalArgumentException("event time must not be in the future"); 2680 } 2681 2682 mContext.enforceCallingOrSelfPermission( 2683 android.Manifest.permission.DEVICE_POWER, null); 2684 2685 final long ident = Binder.clearCallingIdentity(); 2686 try { 2687 wakeUpInternal(eventTime); 2688 } finally { 2689 Binder.restoreCallingIdentity(ident); 2690 } 2691 } 2692 2693 @Override // Binder call 2694 public void goToSleep(long eventTime, int reason) { 2695 if (eventTime > SystemClock.uptimeMillis()) { 2696 throw new IllegalArgumentException("event time must not be in the future"); 2697 } 2698 2699 mContext.enforceCallingOrSelfPermission( 2700 android.Manifest.permission.DEVICE_POWER, null); 2701 2702 final long ident = Binder.clearCallingIdentity(); 2703 try { 2704 goToSleepInternal(eventTime, reason); 2705 } finally { 2706 Binder.restoreCallingIdentity(ident); 2707 } 2708 } 2709 2710 @Override // Binder call 2711 public void nap(long eventTime) { 2712 if (eventTime > SystemClock.uptimeMillis()) { 2713 throw new IllegalArgumentException("event time must not be in the future"); 2714 } 2715 2716 mContext.enforceCallingOrSelfPermission( 2717 android.Manifest.permission.DEVICE_POWER, null); 2718 2719 final long ident = Binder.clearCallingIdentity(); 2720 try { 2721 napInternal(eventTime); 2722 } finally { 2723 Binder.restoreCallingIdentity(ident); 2724 } 2725 } 2726 2727 @Override // Binder call 2728 public boolean isScreenOn() { 2729 final long ident = Binder.clearCallingIdentity(); 2730 try { 2731 return isScreenOnInternal(); 2732 } finally { 2733 Binder.restoreCallingIdentity(ident); 2734 } 2735 } 2736 2737 /** 2738 * Reboots the device. 2739 * 2740 * @param confirm If true, shows a reboot confirmation dialog. 2741 * @param reason The reason for the reboot, or null if none. 2742 * @param wait If true, this call waits for the reboot to complete and does not return. 2743 */ 2744 @Override // Binder call 2745 public void reboot(boolean confirm, String reason, boolean wait) { 2746 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 2747 if (PowerManager.REBOOT_RECOVERY.equals(reason)) { 2748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null); 2749 } 2750 2751 final long ident = Binder.clearCallingIdentity(); 2752 try { 2753 shutdownOrRebootInternal(false, confirm, reason, wait); 2754 } finally { 2755 Binder.restoreCallingIdentity(ident); 2756 } 2757 } 2758 2759 /** 2760 * Shuts down the device. 2761 * 2762 * @param confirm If true, shows a shutdown confirmation dialog. 2763 * @param wait If true, this call waits for the shutdown to complete and does not return. 2764 */ 2765 @Override // Binder call 2766 public void shutdown(boolean confirm, boolean wait) { 2767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 2768 2769 final long ident = Binder.clearCallingIdentity(); 2770 try { 2771 shutdownOrRebootInternal(true, confirm, null, wait); 2772 } finally { 2773 Binder.restoreCallingIdentity(ident); 2774 } 2775 } 2776 2777 /** 2778 * Crash the runtime (causing a complete restart of the Android framework). 2779 * Requires REBOOT permission. Mostly for testing. Should not return. 2780 */ 2781 @Override // Binder call 2782 public void crash(String message) { 2783 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 2784 2785 final long ident = Binder.clearCallingIdentity(); 2786 try { 2787 crashInternal(message); 2788 } finally { 2789 Binder.restoreCallingIdentity(ident); 2790 } 2791 } 2792 2793 /** 2794 * Set the setting that determines whether the device stays on when plugged in. 2795 * The argument is a bit string, with each bit specifying a power source that, 2796 * when the device is connected to that source, causes the device to stay on. 2797 * See {@link android.os.BatteryManager} for the list of power sources that 2798 * can be specified. Current values include 2799 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 2800 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 2801 * 2802 * Used by "adb shell svc power stayon ..." 2803 * 2804 * @param val an {@code int} containing the bits that specify which power sources 2805 * should cause the device to stay on. 2806 */ 2807 @Override // Binder call 2808 public void setStayOnSetting(int val) { 2809 mContext.enforceCallingOrSelfPermission( 2810 android.Manifest.permission.WRITE_SETTINGS, null); 2811 2812 final long ident = Binder.clearCallingIdentity(); 2813 try { 2814 setStayOnSettingInternal(val); 2815 } finally { 2816 Binder.restoreCallingIdentity(ident); 2817 } 2818 } 2819 2820 /** 2821 * Used by device administration to set the maximum screen off timeout. 2822 * 2823 * This method must only be called by the device administration policy manager. 2824 */ 2825 @Override // Binder call 2826 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 2827 final long ident = Binder.clearCallingIdentity(); 2828 try { 2829 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 2830 } finally { 2831 Binder.restoreCallingIdentity(ident); 2832 } 2833 } 2834 2835 /** 2836 * Used by the settings application and brightness control widgets to 2837 * temporarily override the current screen brightness setting so that the 2838 * user can observe the effect of an intended settings change without applying 2839 * it immediately. 2840 * 2841 * The override will be canceled when the setting value is next updated. 2842 * 2843 * @param brightness The overridden brightness. 2844 * 2845 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS 2846 */ 2847 @Override // Binder call 2848 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 2849 mContext.enforceCallingOrSelfPermission( 2850 android.Manifest.permission.DEVICE_POWER, null); 2851 2852 final long ident = Binder.clearCallingIdentity(); 2853 try { 2854 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 2855 } finally { 2856 Binder.restoreCallingIdentity(ident); 2857 } 2858 } 2859 2860 /** 2861 * Used by the settings application and brightness control widgets to 2862 * temporarily override the current screen auto-brightness adjustment setting so that the 2863 * user can observe the effect of an intended settings change without applying 2864 * it immediately. 2865 * 2866 * The override will be canceled when the setting value is next updated. 2867 * 2868 * @param adj The overridden brightness, or Float.NaN to disable the override. 2869 * 2870 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 2871 */ 2872 @Override // Binder call 2873 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 2874 mContext.enforceCallingOrSelfPermission( 2875 android.Manifest.permission.DEVICE_POWER, null); 2876 2877 final long ident = Binder.clearCallingIdentity(); 2878 try { 2879 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 2880 } finally { 2881 Binder.restoreCallingIdentity(ident); 2882 } 2883 } 2884 2885 /** 2886 * Used by the phone application to make the attention LED flash when ringing. 2887 */ 2888 @Override // Binder call 2889 public void setAttentionLight(boolean on, int color) { 2890 mContext.enforceCallingOrSelfPermission( 2891 android.Manifest.permission.DEVICE_POWER, null); 2892 2893 final long ident = Binder.clearCallingIdentity(); 2894 try { 2895 setAttentionLightInternal(on, color); 2896 } finally { 2897 Binder.restoreCallingIdentity(ident); 2898 } 2899 } 2900 2901 @Override // Binder call 2902 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2903 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 2904 != PackageManager.PERMISSION_GRANTED) { 2905 pw.println("Permission Denial: can't dump PowerManager from from pid=" 2906 + Binder.getCallingPid() 2907 + ", uid=" + Binder.getCallingUid()); 2908 return; 2909 } 2910 2911 final long ident = Binder.clearCallingIdentity(); 2912 try { 2913 dumpInternal(pw); 2914 } finally { 2915 Binder.restoreCallingIdentity(ident); 2916 } 2917 } 2918 } 2919 2920 private final class LocalService extends PowerManagerInternal { 2921 /** 2922 * Used by the window manager to override the screen brightness based on the 2923 * current foreground activity. 2924 * 2925 * This method must only be called by the window manager. 2926 * 2927 * @param brightness The overridden brightness, or -1 to disable the override. 2928 */ 2929 @Override 2930 public void setScreenBrightnessOverrideFromWindowManager(int brightness) { 2931 mContext.enforceCallingOrSelfPermission( 2932 android.Manifest.permission.DEVICE_POWER, null); 2933 2934 final long ident = Binder.clearCallingIdentity(); 2935 try { 2936 setScreenBrightnessOverrideFromWindowManagerInternal(brightness); 2937 } finally { 2938 Binder.restoreCallingIdentity(ident); 2939 } 2940 } 2941 2942 /** 2943 * Used by the window manager to override the button brightness based on the 2944 * current foreground activity. 2945 * 2946 * This method must only be called by the window manager. 2947 * 2948 * @param brightness The overridden brightness, or -1 to disable the override. 2949 */ 2950 @Override 2951 public void setButtonBrightnessOverrideFromWindowManager(int brightness) { 2952 // Do nothing. 2953 // Button lights are not currently supported in the new implementation. 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.DEVICE_POWER, null); 2956 } 2957 2958 /** 2959 * Used by the window manager to override the user activity timeout based on the 2960 * current foreground activity. It can only be used to make the timeout shorter 2961 * than usual, not longer. 2962 * 2963 * This method must only be called by the window manager. 2964 * 2965 * @param timeoutMillis The overridden timeout, or -1 to disable the override. 2966 */ 2967 @Override 2968 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 2969 mContext.enforceCallingOrSelfPermission( 2970 android.Manifest.permission.DEVICE_POWER, null); 2971 2972 final long ident = Binder.clearCallingIdentity(); 2973 try { 2974 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 2975 } finally { 2976 Binder.restoreCallingIdentity(ident); 2977 } 2978 } 2979 2980 @Override 2981 public void setPolicy(WindowManagerPolicy policy) { 2982 PowerManagerService.this.setPolicy(policy); 2983 } 2984 } 2985} 2986