PowerManagerService.java revision 03a0428ed3857d1881def7c2767a15acfacfa999
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 android.Manifest; 20import android.app.ActivityManager; 21import android.content.BroadcastReceiver; 22import android.content.ContentResolver; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentFilter; 26import android.content.pm.PackageManager; 27import android.content.res.Resources; 28import android.database.ContentObserver; 29import android.hardware.SensorManager; 30import android.hardware.SystemSensorManager; 31import android.hardware.display.DisplayManagerInternal; 32import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest; 33import android.net.Uri; 34import android.os.BatteryManager; 35import android.os.BatteryManagerInternal; 36import android.os.Binder; 37import android.os.Handler; 38import android.os.IBinder; 39import android.os.IPowerManager; 40import android.os.Looper; 41import android.os.Message; 42import android.os.PowerManager; 43import android.os.PowerManagerInternal; 44import android.os.Process; 45import android.os.RemoteException; 46import android.os.SystemClock; 47import android.os.SystemProperties; 48import android.os.Trace; 49import android.os.UserHandle; 50import android.os.WorkSource; 51import android.provider.Settings; 52import android.provider.Settings.Secure; 53import android.provider.Settings.SettingNotFoundException; 54import android.service.dreams.DreamManagerInternal; 55import android.util.EventLog; 56import android.util.Slog; 57import android.util.SparseIntArray; 58import android.util.TimeUtils; 59import android.view.Display; 60import android.view.WindowManagerPolicy; 61 62import com.android.internal.app.IAppOpsService; 63import com.android.internal.app.IBatteryStats; 64import com.android.internal.os.BackgroundThread; 65import com.android.internal.util.ArrayUtils; 66import com.android.server.EventLogTags; 67import com.android.server.ServiceThread; 68import com.android.server.SystemService; 69import com.android.server.Watchdog; 70import com.android.server.am.BatteryStatsService; 71import com.android.server.lights.Light; 72import com.android.server.lights.LightsManager; 73import com.android.server.vr.VrManagerInternal; 74import com.android.server.vr.VrStateListener; 75import libcore.util.Objects; 76 77import java.io.FileDescriptor; 78import java.io.PrintWriter; 79import java.util.ArrayList; 80import java.util.Arrays; 81 82import static android.os.PowerManagerInternal.POWER_HINT_INTERACTION; 83import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP; 84import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE; 85import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING; 86import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING; 87 88/** 89 * The power manager service is responsible for coordinating power management 90 * functions on the device. 91 */ 92public final class PowerManagerService extends SystemService 93 implements Watchdog.Monitor { 94 private static final String TAG = "PowerManagerService"; 95 96 private static final boolean DEBUG = false; 97 private static final boolean DEBUG_SPEW = DEBUG && true; 98 99 // Message: Sent when a user activity timeout occurs to update the power state. 100 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1; 101 // Message: Sent when the device enters or exits a dreaming or dozing state. 102 private static final int MSG_SANDMAN = 2; 103 // Message: Sent when the screen brightness boost expires. 104 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3; 105 106 // Dirty bit: mWakeLocks changed 107 private static final int DIRTY_WAKE_LOCKS = 1 << 0; 108 // Dirty bit: mWakefulness changed 109 private static final int DIRTY_WAKEFULNESS = 1 << 1; 110 // Dirty bit: user activity was poked or may have timed out 111 private static final int DIRTY_USER_ACTIVITY = 1 << 2; 112 // Dirty bit: actual display power state was updated asynchronously 113 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3; 114 // Dirty bit: mBootCompleted changed 115 private static final int DIRTY_BOOT_COMPLETED = 1 << 4; 116 // Dirty bit: settings changed 117 private static final int DIRTY_SETTINGS = 1 << 5; 118 // Dirty bit: mIsPowered changed 119 private static final int DIRTY_IS_POWERED = 1 << 6; 120 // Dirty bit: mStayOn changed 121 private static final int DIRTY_STAY_ON = 1 << 7; 122 // Dirty bit: battery state changed 123 private static final int DIRTY_BATTERY_STATE = 1 << 8; 124 // Dirty bit: proximity state changed 125 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9; 126 // Dirty bit: dock state changed 127 private static final int DIRTY_DOCK_STATE = 1 << 10; 128 // Dirty bit: brightness boost changed 129 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11; 130 131 // Summarizes the state of all active wakelocks. 132 private static final int WAKE_LOCK_CPU = 1 << 0; 133 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1; 134 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2; 135 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3; 136 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4; 137 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake 138 private static final int WAKE_LOCK_DOZE = 1 << 6; 139 private static final int WAKE_LOCK_DRAW = 1 << 7; 140 private static final int WAKE_LOCK_SUSTAINED_PERFORMANCE = 1 << 8; 141 142 // Summarizes the user activity state. 143 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0; 144 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1; 145 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2; 146 147 // Default timeout in milliseconds. This is only used until the settings 148 // provider populates the actual default value (R.integer.def_screen_off_timeout). 149 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000; 150 private static final int DEFAULT_SLEEP_TIMEOUT = -1; 151 152 // Screen brightness boost timeout. 153 // Hardcoded for now until we decide what the right policy should be. 154 // This should perhaps be a setting. 155 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000; 156 157 // Power hints defined in hardware/libhardware/include/hardware/power.h. 158 private static final int POWER_HINT_LOW_POWER = 5; 159 private static final int POWER_HINT_SUSTAINED_PERFORMANCE = 6; 160 private static final int POWER_HINT_VR_MODE = 7; 161 162 // Power features defined in hardware/libhardware/include/hardware/power.h. 163 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1; 164 165 // Default setting for double tap to wake. 166 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0; 167 168 private final Context mContext; 169 private final ServiceThread mHandlerThread; 170 private final PowerManagerHandler mHandler; 171 172 private LightsManager mLightsManager; 173 private BatteryManagerInternal mBatteryManagerInternal; 174 private DisplayManagerInternal mDisplayManagerInternal; 175 private IBatteryStats mBatteryStats; 176 private IAppOpsService mAppOps; 177 private WindowManagerPolicy mPolicy; 178 private Notifier mNotifier; 179 private WirelessChargerDetector mWirelessChargerDetector; 180 private SettingsObserver mSettingsObserver; 181 private DreamManagerInternal mDreamManager; 182 private Light mAttentionLight; 183 184 private final Object mLock = new Object(); 185 186 // A bitfield that indicates what parts of the power state have 187 // changed and need to be recalculated. 188 private int mDirty; 189 190 // Indicates whether the device is awake or asleep or somewhere in between. 191 // This is distinct from the screen power state, which is managed separately. 192 private int mWakefulness; 193 private boolean mWakefulnessChanging; 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 // Timestamp of the last call to user activity. 221 private long mLastUserActivityTime; 222 private long mLastUserActivityTimeNoChangeLights; 223 224 // Timestamp of last interactive power hint. 225 private long mLastInteractivePowerHintTime; 226 227 // Timestamp of the last screen brightness boost. 228 private long mLastScreenBrightnessBoostTime; 229 private boolean mScreenBrightnessBoostInProgress; 230 231 // A bitfield that summarizes the effect of the user activity timer. 232 private int mUserActivitySummary; 233 234 // The desired display power state. The actual state may lag behind the 235 // requested because it is updated asynchronously by the display power controller. 236 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest(); 237 238 // True if the display power state has been fully applied, which means the display 239 // is actually on or actually off or whatever was requested. 240 private boolean mDisplayReady; 241 242 // The suspend blocker used to keep the CPU alive when an application has acquired 243 // a wake lock. 244 private final SuspendBlocker mWakeLockSuspendBlocker; 245 246 // True if the wake lock suspend blocker has been acquired. 247 private boolean mHoldingWakeLockSuspendBlocker; 248 249 // The suspend blocker used to keep the CPU alive when the display is on, the 250 // display is getting ready or there is user activity (in which case the display 251 // must be on). 252 private final SuspendBlocker mDisplaySuspendBlocker; 253 254 // True if the display suspend blocker has been acquired. 255 private boolean mHoldingDisplaySuspendBlocker; 256 257 // True if systemReady() has been called. 258 private boolean mSystemReady; 259 260 // True if boot completed occurred. We keep the screen on until this happens. 261 private boolean mBootCompleted; 262 263 // Runnables that should be triggered on boot completed 264 private Runnable[] mBootCompletedRunnables; 265 266 // True if auto-suspend mode is enabled. 267 // Refer to autosuspend.h. 268 private boolean mHalAutoSuspendModeEnabled; 269 270 // True if interactive mode is enabled. 271 // Refer to power.h. 272 private boolean mHalInteractiveModeEnabled; 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 mDecoupleHalAutoSuspendModeFromDisplayConfig; 293 294 // True to decouple interactive mode from the display state. 295 private boolean mDecoupleHalInteractiveModeFromDisplayConfig; 296 297 // True if the device should wake up when plugged or unplugged. 298 private boolean mWakeUpWhenPluggedOrUnpluggedConfig; 299 300 // True if the device should wake up when plugged or unplugged in theater mode. 301 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig; 302 303 // True if the device should suspend when the screen is off due to proximity. 304 private boolean mSuspendWhenScreenOffDueToProximityConfig; 305 306 // True if dreams are supported on this device. 307 private boolean mDreamsSupportedConfig; 308 309 // Default value for dreams enabled 310 private boolean mDreamsEnabledByDefaultConfig; 311 312 // Default value for dreams activate-on-sleep 313 private boolean mDreamsActivatedOnSleepByDefaultConfig; 314 315 // Default value for dreams activate-on-dock 316 private boolean mDreamsActivatedOnDockByDefaultConfig; 317 318 // True if dreams can run while not plugged in. 319 private boolean mDreamsEnabledOnBatteryConfig; 320 321 // Minimum battery level to allow dreaming when powered. 322 // Use -1 to disable this safety feature. 323 private int mDreamsBatteryLevelMinimumWhenPoweredConfig; 324 325 // Minimum battery level to allow dreaming when not powered. 326 // Use -1 to disable this safety feature. 327 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig; 328 329 // If the battery level drops by this percentage and the user activity timeout 330 // has expired, then assume the device is receiving insufficient current to charge 331 // effectively and terminate the dream. Use -1 to disable this safety feature. 332 private int mDreamsBatteryLevelDrainCutoffConfig; 333 334 // True if dreams are enabled by the user. 335 private boolean mDreamsEnabledSetting; 336 337 // True if dreams should be activated on sleep. 338 private boolean mDreamsActivateOnSleepSetting; 339 340 // True if dreams should be activated on dock. 341 private boolean mDreamsActivateOnDockSetting; 342 343 // True if doze should not be started until after the screen off transition. 344 private boolean mDozeAfterScreenOffConfig; 345 346 // The minimum screen off timeout, in milliseconds. 347 private int mMinimumScreenOffTimeoutConfig; 348 349 // The screen dim duration, in milliseconds. 350 // This is subtracted from the end of the screen off timeout so the 351 // minimum screen off timeout should be longer than this. 352 private int mMaximumScreenDimDurationConfig; 353 354 // The maximum screen dim time expressed as a ratio relative to the screen 355 // off timeout. If the screen off timeout is very short then we want the 356 // dim timeout to also be quite short so that most of the time is spent on. 357 // Otherwise the user won't get much screen on time before dimming occurs. 358 private float mMaximumScreenDimRatioConfig; 359 360 // Whether device supports double tap to wake. 361 private boolean mSupportsDoubleTapWakeConfig; 362 363 // The screen off timeout setting value in milliseconds. 364 private int mScreenOffTimeoutSetting; 365 366 // The sleep timeout setting value in milliseconds. 367 private int mSleepTimeoutSetting; 368 369 // The maximum allowable screen off timeout according to the device 370 // administration policy. Overrides other settings. 371 private int mMaximumScreenOffTimeoutFromDeviceAdmin = Integer.MAX_VALUE; 372 373 // The stay on while plugged in setting. 374 // A bitfield of battery conditions under which to make the screen stay on. 375 private int mStayOnWhilePluggedInSetting; 376 377 // True if the device should stay on. 378 private boolean mStayOn; 379 380 // True if the proximity sensor reads a positive result. 381 private boolean mProximityPositive; 382 383 // Screen brightness setting limits. 384 private int mScreenBrightnessSettingMinimum; 385 private int mScreenBrightnessSettingMaximum; 386 private int mScreenBrightnessSettingDefault; 387 388 // The screen brightness setting, from 0 to 255. 389 // Use -1 if no value has been set. 390 private int mScreenBrightnessSetting; 391 392 // The screen auto-brightness adjustment setting, from -1 to 1. 393 // Use 0 if there is no adjustment. 394 private float mScreenAutoBrightnessAdjustmentSetting; 395 396 // The screen brightness mode. 397 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants. 398 private int mScreenBrightnessModeSetting; 399 400 // The screen brightness setting override from the window manager 401 // to allow the current foreground activity to override the brightness. 402 // Use -1 to disable. 403 private int mScreenBrightnessOverrideFromWindowManager = -1; 404 405 // The window manager has determined the user to be inactive via other means. 406 // Set this to false to disable. 407 private boolean mUserInactiveOverrideFromWindowManager; 408 409 // The next possible user activity timeout after being explicitly told the user is inactive. 410 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep. 411 private long mOverriddenTimeout = -1; 412 413 // The user activity timeout override from the window manager 414 // to allow the current foreground activity to override the user activity timeout. 415 // Use -1 to disable. 416 private long mUserActivityTimeoutOverrideFromWindowManager = -1; 417 418 // The screen brightness setting override from the settings application 419 // to temporarily adjust the brightness until next updated, 420 // Use -1 to disable. 421 private int mTemporaryScreenBrightnessSettingOverride = -1; 422 423 // The screen brightness adjustment setting override from the settings 424 // application to temporarily adjust the auto-brightness adjustment factor 425 // until next updated, in the range -1..1. 426 // Use NaN to disable. 427 private float mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 428 429 // The screen state to use while dozing. 430 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN; 431 432 // The screen brightness to use while dozing. 433 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT; 434 435 // Time when we last logged a warning about calling userActivity() without permission. 436 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE; 437 438 // If true, the device is in low power mode. 439 private boolean mLowPowerModeEnabled; 440 441 // Current state of the low power mode setting. 442 private boolean mLowPowerModeSetting; 443 444 // Current state of whether the settings are allowing auto low power mode. 445 private boolean mAutoLowPowerModeConfigured; 446 447 // The user turned off low power mode below the trigger level 448 private boolean mAutoLowPowerModeSnoozing; 449 450 // True if the battery level is currently considered low. 451 private boolean mBatteryLevelLow; 452 453 // True if we are currently in device idle mode. 454 private boolean mDeviceIdleMode; 455 456 // True if we are currently in light device idle mode. 457 private boolean mLightDeviceIdleMode; 458 459 // True if we are currently in sustained performance mode. 460 private boolean mSustainedPerformanceMode; 461 462 // Set of app ids that we will always respect the wake locks for. 463 int[] mDeviceIdleWhitelist = new int[0]; 464 465 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message 466 int[] mDeviceIdleTempWhitelist = new int[0]; 467 468 private final SparseIntArray mUidState = new SparseIntArray(); 469 470 private final SparseIntArray mSustainedPerformanceUid = new SparseIntArray(); 471 472 // True if theater mode is enabled 473 private boolean mTheaterModeEnabled; 474 475 // True if double tap to wake is enabled 476 private boolean mDoubleTapWakeEnabled; 477 478 private final ArrayList<PowerManagerInternal.LowPowerModeListener> mLowPowerModeListeners 479 = new ArrayList<PowerManagerInternal.LowPowerModeListener>(); 480 481 // True if brightness should be affected by twilight. 482 private boolean mBrightnessUseTwilight; 483 484 private native void nativeInit(); 485 486 private static native void nativeAcquireSuspendBlocker(String name); 487 private static native void nativeReleaseSuspendBlocker(String name); 488 private static native void nativeSetInteractive(boolean enable); 489 private static native void nativeSetAutoSuspend(boolean enable); 490 private static native void nativeSendPowerHint(int hintId, int data); 491 private static native void nativeSetFeature(int featureId, int data); 492 493 public PowerManagerService(Context context) { 494 super(context); 495 mContext = context; 496 mHandlerThread = new ServiceThread(TAG, 497 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/); 498 mHandlerThread.start(); 499 mHandler = new PowerManagerHandler(mHandlerThread.getLooper()); 500 501 synchronized (mLock) { 502 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks"); 503 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display"); 504 mDisplaySuspendBlocker.acquire(); 505 mHoldingDisplaySuspendBlocker = true; 506 mHalAutoSuspendModeEnabled = false; 507 mHalInteractiveModeEnabled = true; 508 509 mWakefulness = WAKEFULNESS_AWAKE; 510 511 nativeInit(); 512 nativeSetAutoSuspend(false); 513 nativeSetInteractive(true); 514 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0); 515 } 516 } 517 518 @Override 519 public void onStart() { 520 publishBinderService(Context.POWER_SERVICE, new BinderService()); 521 publishLocalService(PowerManagerInternal.class, new LocalService()); 522 523 Watchdog.getInstance().addMonitor(this); 524 Watchdog.getInstance().addThread(mHandler); 525 } 526 527 @Override 528 public void onBootPhase(int phase) { 529 synchronized (mLock) { 530 if (phase == PHASE_BOOT_COMPLETED) { 531 final long now = SystemClock.uptimeMillis(); 532 mBootCompleted = true; 533 mDirty |= DIRTY_BOOT_COMPLETED; 534 userActivityNoUpdateLocked( 535 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 536 updatePowerStateLocked(); 537 538 if (!ArrayUtils.isEmpty(mBootCompletedRunnables)) { 539 Slog.d(TAG, "Posting " + mBootCompletedRunnables.length + " delayed runnables"); 540 for (Runnable r : mBootCompletedRunnables) { 541 BackgroundThread.getHandler().post(r); 542 } 543 } 544 mBootCompletedRunnables = null; 545 546 incrementBootCount(); 547 } 548 } 549 } 550 551 public void systemReady(IAppOpsService appOps) { 552 synchronized (mLock) { 553 mSystemReady = true; 554 mAppOps = appOps; 555 mDreamManager = getLocalService(DreamManagerInternal.class); 556 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class); 557 mPolicy = getLocalService(WindowManagerPolicy.class); 558 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class); 559 560 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 561 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting(); 562 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting(); 563 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting(); 564 565 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper()); 566 567 // The notifier runs on the system server's main looper so as not to interfere 568 // with the animations and other critical functions of the power manager. 569 mBatteryStats = BatteryStatsService.getService(); 570 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats, 571 mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"), 572 mPolicy); 573 574 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager, 575 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"), 576 mHandler); 577 mSettingsObserver = new SettingsObserver(mHandler); 578 579 mLightsManager = getLocalService(LightsManager.class); 580 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION); 581 582 // Initialize display power management. 583 mDisplayManagerInternal.initPowerManagement( 584 mDisplayPowerCallbacks, mHandler, sensorManager); 585 586 // Register for broadcasts from other components of the system. 587 IntentFilter filter = new IntentFilter(); 588 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 589 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 590 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler); 591 592 filter = new IntentFilter(); 593 filter.addAction(Intent.ACTION_DREAMING_STARTED); 594 filter.addAction(Intent.ACTION_DREAMING_STOPPED); 595 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler); 596 597 filter = new IntentFilter(); 598 filter.addAction(Intent.ACTION_USER_SWITCHED); 599 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler); 600 601 filter = new IntentFilter(); 602 filter.addAction(Intent.ACTION_DOCK_EVENT); 603 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler); 604 605 // Register for settings changes. 606 final ContentResolver resolver = mContext.getContentResolver(); 607 resolver.registerContentObserver(Settings.Secure.getUriFor( 608 Settings.Secure.SCREENSAVER_ENABLED), 609 false, mSettingsObserver, UserHandle.USER_ALL); 610 resolver.registerContentObserver(Settings.Secure.getUriFor( 611 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP), 612 false, mSettingsObserver, UserHandle.USER_ALL); 613 resolver.registerContentObserver(Settings.Secure.getUriFor( 614 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK), 615 false, mSettingsObserver, UserHandle.USER_ALL); 616 resolver.registerContentObserver(Settings.System.getUriFor( 617 Settings.System.SCREEN_OFF_TIMEOUT), 618 false, mSettingsObserver, UserHandle.USER_ALL); 619 resolver.registerContentObserver(Settings.Secure.getUriFor( 620 Settings.Secure.SLEEP_TIMEOUT), 621 false, mSettingsObserver, UserHandle.USER_ALL); 622 resolver.registerContentObserver(Settings.Global.getUriFor( 623 Settings.Global.STAY_ON_WHILE_PLUGGED_IN), 624 false, mSettingsObserver, UserHandle.USER_ALL); 625 resolver.registerContentObserver(Settings.System.getUriFor( 626 Settings.System.SCREEN_BRIGHTNESS), 627 false, mSettingsObserver, UserHandle.USER_ALL); 628 resolver.registerContentObserver(Settings.System.getUriFor( 629 Settings.System.SCREEN_BRIGHTNESS_MODE), 630 false, mSettingsObserver, UserHandle.USER_ALL); 631 resolver.registerContentObserver(Settings.System.getUriFor( 632 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ), 633 false, mSettingsObserver, UserHandle.USER_ALL); 634 resolver.registerContentObserver(Settings.Global.getUriFor( 635 Settings.Global.LOW_POWER_MODE), 636 false, mSettingsObserver, UserHandle.USER_ALL); 637 resolver.registerContentObserver(Settings.Global.getUriFor( 638 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL), 639 false, mSettingsObserver, UserHandle.USER_ALL); 640 resolver.registerContentObserver(Settings.Global.getUriFor( 641 Settings.Global.THEATER_MODE_ON), 642 false, mSettingsObserver, UserHandle.USER_ALL); 643 resolver.registerContentObserver(Settings.Secure.getUriFor( 644 Settings.Secure.DOUBLE_TAP_TO_WAKE), 645 false, mSettingsObserver, UserHandle.USER_ALL); 646 resolver.registerContentObserver(Settings.Secure.getUriFor( 647 Secure.BRIGHTNESS_USE_TWILIGHT), 648 false, mSettingsObserver, UserHandle.USER_ALL); 649 getLocalService(VrManagerInternal.class).registerListener(mVrStateListener); 650 // Go. 651 readConfigurationLocked(); 652 updateSettingsLocked(); 653 mDirty |= DIRTY_BATTERY_STATE; 654 updatePowerStateLocked(); 655 } 656 } 657 658 private void readConfigurationLocked() { 659 final Resources resources = mContext.getResources(); 660 661 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean( 662 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay); 663 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean( 664 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay); 665 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean( 666 com.android.internal.R.bool.config_unplugTurnsOnScreen); 667 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean( 668 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug); 669 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean( 670 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity); 671 mDreamsSupportedConfig = resources.getBoolean( 672 com.android.internal.R.bool.config_dreamsSupported); 673 mDreamsEnabledByDefaultConfig = resources.getBoolean( 674 com.android.internal.R.bool.config_dreamsEnabledByDefault); 675 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean( 676 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault); 677 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean( 678 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault); 679 mDreamsEnabledOnBatteryConfig = resources.getBoolean( 680 com.android.internal.R.bool.config_dreamsEnabledOnBattery); 681 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger( 682 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered); 683 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger( 684 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered); 685 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger( 686 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff); 687 mDozeAfterScreenOffConfig = resources.getBoolean( 688 com.android.internal.R.bool.config_dozeAfterScreenOff); 689 mMinimumScreenOffTimeoutConfig = resources.getInteger( 690 com.android.internal.R.integer.config_minimumScreenOffTimeout); 691 mMaximumScreenDimDurationConfig = resources.getInteger( 692 com.android.internal.R.integer.config_maximumScreenDimDuration); 693 mMaximumScreenDimRatioConfig = resources.getFraction( 694 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1); 695 mSupportsDoubleTapWakeConfig = resources.getBoolean( 696 com.android.internal.R.bool.config_supportDoubleTapWake); 697 } 698 699 private void updateSettingsLocked() { 700 final ContentResolver resolver = mContext.getContentResolver(); 701 702 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver, 703 Settings.Secure.SCREENSAVER_ENABLED, 704 mDreamsEnabledByDefaultConfig ? 1 : 0, 705 UserHandle.USER_CURRENT) != 0); 706 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver, 707 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 708 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0, 709 UserHandle.USER_CURRENT) != 0); 710 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver, 711 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK, 712 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0, 713 UserHandle.USER_CURRENT) != 0); 714 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver, 715 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT, 716 UserHandle.USER_CURRENT); 717 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver, 718 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT, 719 UserHandle.USER_CURRENT); 720 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver, 721 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC); 722 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(), 723 Settings.Global.THEATER_MODE_ON, 0) == 1; 724 725 if (mSupportsDoubleTapWakeConfig) { 726 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver, 727 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE, 728 UserHandle.USER_CURRENT) != 0; 729 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) { 730 mDoubleTapWakeEnabled = doubleTapWakeEnabled; 731 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0); 732 } 733 } 734 735 final int oldScreenBrightnessSetting = mScreenBrightnessSetting; 736 mScreenBrightnessSetting = Settings.System.getIntForUser(resolver, 737 Settings.System.SCREEN_BRIGHTNESS, mScreenBrightnessSettingDefault, 738 UserHandle.USER_CURRENT); 739 if (oldScreenBrightnessSetting != mScreenBrightnessSetting) { 740 mTemporaryScreenBrightnessSettingOverride = -1; 741 } 742 743 final float oldScreenAutoBrightnessAdjustmentSetting = 744 mScreenAutoBrightnessAdjustmentSetting; 745 mScreenAutoBrightnessAdjustmentSetting = Settings.System.getFloatForUser(resolver, 746 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ, 0.0f, 747 UserHandle.USER_CURRENT); 748 if (oldScreenAutoBrightnessAdjustmentSetting != mScreenAutoBrightnessAdjustmentSetting) { 749 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = Float.NaN; 750 } 751 752 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver, 753 Settings.System.SCREEN_BRIGHTNESS_MODE, 754 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT); 755 756 mBrightnessUseTwilight = Settings.Secure.getIntForUser(resolver, 757 Secure.BRIGHTNESS_USE_TWILIGHT, 0, UserHandle.USER_CURRENT) != 0; 758 759 final boolean lowPowerModeEnabled = Settings.Global.getInt(resolver, 760 Settings.Global.LOW_POWER_MODE, 0) != 0; 761 final boolean autoLowPowerModeConfigured = Settings.Global.getInt(resolver, 762 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0) != 0; 763 if (lowPowerModeEnabled != mLowPowerModeSetting 764 || autoLowPowerModeConfigured != mAutoLowPowerModeConfigured) { 765 mLowPowerModeSetting = lowPowerModeEnabled; 766 mAutoLowPowerModeConfigured = autoLowPowerModeConfigured; 767 updateLowPowerModeLocked(); 768 } 769 770 mDirty |= DIRTY_SETTINGS; 771 } 772 773 private void postAfterBootCompleted(Runnable r) { 774 if (mBootCompleted) { 775 BackgroundThread.getHandler().post(r); 776 } else { 777 Slog.d(TAG, "Delaying runnable until system is booted"); 778 mBootCompletedRunnables = ArrayUtils.appendElement(Runnable.class, 779 mBootCompletedRunnables, r); 780 } 781 } 782 783 private void updateLowPowerModeLocked() { 784 if (mIsPowered && mLowPowerModeSetting) { 785 if (DEBUG_SPEW) { 786 Slog.d(TAG, "updateLowPowerModeLocked: powered, turning setting off"); 787 } 788 // Turn setting off if powered 789 Settings.Global.putInt(mContext.getContentResolver(), 790 Settings.Global.LOW_POWER_MODE, 0); 791 mLowPowerModeSetting = false; 792 } 793 final boolean autoLowPowerModeEnabled = !mIsPowered && mAutoLowPowerModeConfigured 794 && !mAutoLowPowerModeSnoozing && mBatteryLevelLow; 795 final boolean lowPowerModeEnabled = mLowPowerModeSetting || autoLowPowerModeEnabled; 796 797 if (mLowPowerModeEnabled != lowPowerModeEnabled) { 798 mLowPowerModeEnabled = lowPowerModeEnabled; 799 powerHintInternal(POWER_HINT_LOW_POWER, lowPowerModeEnabled ? 1 : 0); 800 postAfterBootCompleted(new Runnable() { 801 @Override 802 public void run() { 803 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGING) 804 .putExtra(PowerManager.EXTRA_POWER_SAVE_MODE, mLowPowerModeEnabled) 805 .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 806 mContext.sendBroadcast(intent); 807 ArrayList<PowerManagerInternal.LowPowerModeListener> listeners; 808 synchronized (mLock) { 809 listeners = new ArrayList<PowerManagerInternal.LowPowerModeListener>( 810 mLowPowerModeListeners); 811 } 812 for (int i=0; i<listeners.size(); i++) { 813 listeners.get(i).onLowPowerModeChanged(lowPowerModeEnabled); 814 } 815 intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); 816 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 817 mContext.sendBroadcast(intent); 818 // Send internal version that requires signature permission. 819 mContext.sendBroadcastAsUser(new Intent( 820 PowerManager.ACTION_POWER_SAVE_MODE_CHANGED_INTERNAL), UserHandle.ALL, 821 Manifest.permission.DEVICE_POWER); 822 } 823 }); 824 } 825 } 826 827 private void handleSettingsChangedLocked() { 828 updateSettingsLocked(); 829 updatePowerStateLocked(); 830 } 831 832 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName, 833 WorkSource ws, String historyTag, int uid, int pid) { 834 synchronized (mLock) { 835 if (DEBUG_SPEW) { 836 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock) 837 + ", flags=0x" + Integer.toHexString(flags) 838 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid); 839 } 840 841 WakeLock wakeLock; 842 int index = findWakeLockIndexLocked(lock); 843 boolean notifyAcquire; 844 if (index >= 0) { 845 wakeLock = mWakeLocks.get(index); 846 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) { 847 // Update existing wake lock. This shouldn't happen but is harmless. 848 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName, 849 uid, pid, ws, historyTag); 850 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid); 851 } 852 notifyAcquire = false; 853 } else { 854 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid); 855 try { 856 lock.linkToDeath(wakeLock, 0); 857 } catch (RemoteException ex) { 858 throw new IllegalArgumentException("Wake lock is already dead."); 859 } 860 mWakeLocks.add(wakeLock); 861 862 if ((flags & PowerManager.WAKE_LOCK_LEVEL_MASK) 863 == PowerManager.SUSTAINED_PERFORMANCE_WAKE_LOCK) { 864 int numberWakelock = mSustainedPerformanceUid.get(uid); 865 mSustainedPerformanceUid.put(uid, numberWakelock + 1); 866 } 867 setWakeLockDisabledStateLocked(wakeLock); 868 notifyAcquire = true; 869 } 870 871 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid); 872 mDirty |= DIRTY_WAKE_LOCKS; 873 updatePowerStateLocked(); 874 if (notifyAcquire) { 875 // This needs to be done last so we are sure we have acquired the 876 // kernel wake lock. Otherwise we have a race where the system may 877 // go to sleep between the time we start the accounting in battery 878 // stats and when we actually get around to telling the kernel to 879 // stay awake. 880 notifyWakeLockAcquiredLocked(wakeLock); 881 } 882 } 883 } 884 885 @SuppressWarnings("deprecation") 886 private static boolean isScreenLock(final WakeLock wakeLock) { 887 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 888 case PowerManager.FULL_WAKE_LOCK: 889 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 890 case PowerManager.SCREEN_DIM_WAKE_LOCK: 891 return true; 892 } 893 return false; 894 } 895 896 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) { 897 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0 898 && isScreenLock(wakeLock)) { 899 String opPackageName; 900 int opUid; 901 if (wakeLock.mWorkSource != null && wakeLock.mWorkSource.getName(0) != null) { 902 opPackageName = wakeLock.mWorkSource.getName(0); 903 opUid = wakeLock.mWorkSource.get(0); 904 } else { 905 opPackageName = wakeLock.mPackageName; 906 opUid = wakeLock.mWorkSource != null ? wakeLock.mWorkSource.get(0) 907 : wakeLock.mOwnerUid; 908 } 909 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), wakeLock.mTag, opUid, 910 opPackageName, opUid); 911 } 912 } 913 914 private void releaseWakeLockInternal(IBinder lock, int flags) { 915 synchronized (mLock) { 916 int index = findWakeLockIndexLocked(lock); 917 if (index < 0) { 918 if (DEBUG_SPEW) { 919 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 920 + " [not found], flags=0x" + Integer.toHexString(flags)); 921 } 922 return; 923 } 924 925 WakeLock wakeLock = mWakeLocks.get(index); 926 if (DEBUG_SPEW) { 927 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock) 928 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags)); 929 } 930 931 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) { 932 mRequestWaitForNegativeProximity = true; 933 } 934 935 936 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 937 == PowerManager.SUSTAINED_PERFORMANCE_WAKE_LOCK) { 938 int numberWakelock = mSustainedPerformanceUid.get(wakeLock.mOwnerUid); 939 if (numberWakelock == 1) { 940 mSustainedPerformanceUid.delete(wakeLock.mOwnerUid); 941 } else { 942 mSustainedPerformanceUid.put(wakeLock.mOwnerUid, numberWakelock - 1); 943 } 944 } 945 946 wakeLock.mLock.unlinkToDeath(wakeLock, 0); 947 removeWakeLockLocked(wakeLock, index); 948 } 949 } 950 951 private void handleWakeLockDeath(WakeLock wakeLock) { 952 synchronized (mLock) { 953 if (DEBUG_SPEW) { 954 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock) 955 + " [" + wakeLock.mTag + "]"); 956 } 957 958 int index = mWakeLocks.indexOf(wakeLock); 959 if (index < 0) { 960 return; 961 } 962 963 removeWakeLockLocked(wakeLock, index); 964 } 965 } 966 967 private void removeWakeLockLocked(WakeLock wakeLock, int index) { 968 mWakeLocks.remove(index); 969 notifyWakeLockReleasedLocked(wakeLock); 970 971 applyWakeLockFlagsOnReleaseLocked(wakeLock); 972 mDirty |= DIRTY_WAKE_LOCKS; 973 updatePowerStateLocked(); 974 } 975 976 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) { 977 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0 978 && isScreenLock(wakeLock)) { 979 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 980 PowerManager.USER_ACTIVITY_EVENT_OTHER, 981 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS, 982 wakeLock.mOwnerUid); 983 } 984 } 985 986 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag, 987 int callingUid) { 988 synchronized (mLock) { 989 int index = findWakeLockIndexLocked(lock); 990 if (index < 0) { 991 if (DEBUG_SPEW) { 992 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 993 + " [not found], ws=" + ws); 994 } 995 throw new IllegalArgumentException("Wake lock not active: " + lock 996 + " from uid " + callingUid); 997 } 998 999 WakeLock wakeLock = mWakeLocks.get(index); 1000 if (DEBUG_SPEW) { 1001 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock) 1002 + " [" + wakeLock.mTag + "], ws=" + ws); 1003 } 1004 1005 if (!wakeLock.hasSameWorkSource(ws)) { 1006 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag, 1007 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 1008 ws, historyTag); 1009 wakeLock.mHistoryTag = historyTag; 1010 wakeLock.updateWorkSource(ws); 1011 } 1012 } 1013 } 1014 1015 private int findWakeLockIndexLocked(IBinder lock) { 1016 final int count = mWakeLocks.size(); 1017 for (int i = 0; i < count; i++) { 1018 if (mWakeLocks.get(i).mLock == lock) { 1019 return i; 1020 } 1021 } 1022 return -1; 1023 } 1024 1025 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) { 1026 if (mSystemReady && !wakeLock.mDisabled) { 1027 wakeLock.mNotifiedAcquired = true; 1028 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 1029 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 1030 wakeLock.mHistoryTag); 1031 } 1032 } 1033 1034 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag, 1035 String packageName, int uid, int pid, WorkSource ws, String historyTag) { 1036 if (mSystemReady && wakeLock.mNotifiedAcquired) { 1037 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName, 1038 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource, 1039 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag); 1040 } 1041 } 1042 1043 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) { 1044 if (mSystemReady && wakeLock.mNotifiedAcquired) { 1045 wakeLock.mNotifiedAcquired = false; 1046 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag, 1047 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid, 1048 wakeLock.mWorkSource, wakeLock.mHistoryTag); 1049 } 1050 } 1051 1052 @SuppressWarnings("deprecation") 1053 private boolean isWakeLockLevelSupportedInternal(int level) { 1054 synchronized (mLock) { 1055 switch (level) { 1056 case PowerManager.PARTIAL_WAKE_LOCK: 1057 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1058 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1059 case PowerManager.FULL_WAKE_LOCK: 1060 case PowerManager.DOZE_WAKE_LOCK: 1061 case PowerManager.DRAW_WAKE_LOCK: 1062 return true; 1063 1064 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1065 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable(); 1066 1067 default: 1068 return false; 1069 } 1070 } 1071 } 1072 1073 // Called from native code. 1074 private void userActivityFromNative(long eventTime, int event, int flags) { 1075 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID); 1076 } 1077 1078 private void userActivityInternal(long eventTime, int event, int flags, int uid) { 1079 synchronized (mLock) { 1080 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) { 1081 updatePowerStateLocked(); 1082 } 1083 } 1084 } 1085 1086 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) { 1087 if (DEBUG_SPEW) { 1088 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime 1089 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags) 1090 + ", uid=" + uid); 1091 } 1092 1093 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime 1094 || !mBootCompleted || !mSystemReady) { 1095 return false; 1096 } 1097 1098 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity"); 1099 try { 1100 if (eventTime > mLastInteractivePowerHintTime) { 1101 powerHintInternal(POWER_HINT_INTERACTION, 0); 1102 mLastInteractivePowerHintTime = eventTime; 1103 } 1104 1105 mNotifier.onUserActivity(event, uid); 1106 1107 if (mUserInactiveOverrideFromWindowManager) { 1108 mUserInactiveOverrideFromWindowManager = false; 1109 mOverriddenTimeout = -1; 1110 } 1111 1112 if (mWakefulness == WAKEFULNESS_ASLEEP 1113 || mWakefulness == WAKEFULNESS_DOZING 1114 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) { 1115 return false; 1116 } 1117 1118 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) { 1119 if (eventTime > mLastUserActivityTimeNoChangeLights 1120 && eventTime > mLastUserActivityTime) { 1121 mLastUserActivityTimeNoChangeLights = eventTime; 1122 mDirty |= DIRTY_USER_ACTIVITY; 1123 return true; 1124 } 1125 } else { 1126 if (eventTime > mLastUserActivityTime) { 1127 mLastUserActivityTime = eventTime; 1128 mDirty |= DIRTY_USER_ACTIVITY; 1129 return true; 1130 } 1131 } 1132 } finally { 1133 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1134 } 1135 return false; 1136 } 1137 1138 private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName, 1139 int opUid) { 1140 synchronized (mLock) { 1141 if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) { 1142 updatePowerStateLocked(); 1143 } 1144 } 1145 } 1146 1147 private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid, 1148 String opPackageName, int opUid) { 1149 if (DEBUG_SPEW) { 1150 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid); 1151 } 1152 1153 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE 1154 || !mBootCompleted || !mSystemReady) { 1155 return false; 1156 } 1157 1158 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp"); 1159 try { 1160 switch (mWakefulness) { 1161 case WAKEFULNESS_ASLEEP: 1162 Slog.i(TAG, "Waking up from sleep (uid " + reasonUid +")..."); 1163 break; 1164 case WAKEFULNESS_DREAMING: 1165 Slog.i(TAG, "Waking up from dream (uid " + reasonUid +")..."); 1166 break; 1167 case WAKEFULNESS_DOZING: 1168 Slog.i(TAG, "Waking up from dozing (uid " + reasonUid +")..."); 1169 break; 1170 } 1171 1172 mLastWakeTime = eventTime; 1173 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0); 1174 1175 mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid); 1176 userActivityNoUpdateLocked( 1177 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid); 1178 } finally { 1179 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1180 } 1181 return true; 1182 } 1183 1184 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) { 1185 synchronized (mLock) { 1186 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) { 1187 updatePowerStateLocked(); 1188 } 1189 } 1190 } 1191 1192 // This method is called goToSleep for historical reasons but we actually start 1193 // dozing before really going to sleep. 1194 @SuppressWarnings("deprecation") 1195 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) { 1196 if (DEBUG_SPEW) { 1197 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime 1198 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid); 1199 } 1200 1201 if (eventTime < mLastWakeTime 1202 || mWakefulness == WAKEFULNESS_ASLEEP 1203 || mWakefulness == WAKEFULNESS_DOZING 1204 || !mBootCompleted || !mSystemReady) { 1205 return false; 1206 } 1207 1208 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep"); 1209 try { 1210 switch (reason) { 1211 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN: 1212 Slog.i(TAG, "Going to sleep due to device administration policy " 1213 + "(uid " + uid +")..."); 1214 break; 1215 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT: 1216 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")..."); 1217 break; 1218 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH: 1219 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")..."); 1220 break; 1221 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON: 1222 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")..."); 1223 break; 1224 case PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON: 1225 Slog.i(TAG, "Going to sleep due to sleep button (uid " + uid +")..."); 1226 break; 1227 case PowerManager.GO_TO_SLEEP_REASON_HDMI: 1228 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")..."); 1229 break; 1230 default: 1231 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")..."); 1232 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION; 1233 break; 1234 } 1235 1236 mLastSleepTime = eventTime; 1237 mSandmanSummoned = true; 1238 setWakefulnessLocked(WAKEFULNESS_DOZING, reason); 1239 1240 // Report the number of wake locks that will be cleared by going to sleep. 1241 int numWakeLocksCleared = 0; 1242 final int numWakeLocks = mWakeLocks.size(); 1243 for (int i = 0; i < numWakeLocks; i++) { 1244 final WakeLock wakeLock = mWakeLocks.get(i); 1245 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1246 case PowerManager.FULL_WAKE_LOCK: 1247 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1248 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1249 numWakeLocksCleared += 1; 1250 break; 1251 } 1252 } 1253 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared); 1254 1255 // Skip dozing if requested. 1256 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) { 1257 reallyGoToSleepNoUpdateLocked(eventTime, uid); 1258 } 1259 } finally { 1260 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1261 } 1262 return true; 1263 } 1264 1265 private void napInternal(long eventTime, int uid) { 1266 synchronized (mLock) { 1267 if (napNoUpdateLocked(eventTime, uid)) { 1268 updatePowerStateLocked(); 1269 } 1270 } 1271 } 1272 1273 private boolean napNoUpdateLocked(long eventTime, int uid) { 1274 if (DEBUG_SPEW) { 1275 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid); 1276 } 1277 1278 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE 1279 || !mBootCompleted || !mSystemReady) { 1280 return false; 1281 } 1282 1283 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap"); 1284 try { 1285 Slog.i(TAG, "Nap time (uid " + uid +")..."); 1286 1287 mSandmanSummoned = true; 1288 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0); 1289 } finally { 1290 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1291 } 1292 return true; 1293 } 1294 1295 // Done dozing, drop everything and go to sleep. 1296 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) { 1297 if (DEBUG_SPEW) { 1298 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime 1299 + ", uid=" + uid); 1300 } 1301 1302 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP 1303 || !mBootCompleted || !mSystemReady) { 1304 return false; 1305 } 1306 1307 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep"); 1308 try { 1309 Slog.i(TAG, "Sleeping (uid " + uid +")..."); 1310 1311 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); 1312 } finally { 1313 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1314 } 1315 return true; 1316 } 1317 1318 private void setWakefulnessLocked(int wakefulness, int reason) { 1319 if (mWakefulness != wakefulness) { 1320 mWakefulness = wakefulness; 1321 mWakefulnessChanging = true; 1322 mDirty |= DIRTY_WAKEFULNESS; 1323 mNotifier.onWakefulnessChangeStarted(wakefulness, reason); 1324 } 1325 } 1326 1327 /** 1328 * Logs the time the device would have spent awake before user activity timeout, 1329 * had the system not been told the user was inactive. 1330 */ 1331 private void logSleepTimeoutRecapturedLocked() { 1332 final long now = SystemClock.uptimeMillis(); 1333 final long savedWakeTimeMs = mOverriddenTimeout - now; 1334 if (savedWakeTimeMs >= 0) { 1335 EventLog.writeEvent(EventLogTags.POWER_SOFT_SLEEP_REQUESTED, savedWakeTimeMs); 1336 mOverriddenTimeout = -1; 1337 } 1338 } 1339 1340 private void finishWakefulnessChangeIfNeededLocked() { 1341 if (mWakefulnessChanging && mDisplayReady) { 1342 if (mWakefulness == WAKEFULNESS_DOZING 1343 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) { 1344 return; // wait until dream has enabled dozing 1345 } 1346 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) { 1347 logSleepTimeoutRecapturedLocked(); 1348 } 1349 mWakefulnessChanging = false; 1350 mNotifier.onWakefulnessChangeFinished(); 1351 } 1352 } 1353 1354 /** 1355 * Updates the global power state based on dirty bits recorded in mDirty. 1356 * 1357 * This is the main function that performs power state transitions. 1358 * We centralize them here so that we can recompute the power state completely 1359 * each time something important changes, and ensure that we do it the same 1360 * way each time. The point is to gather all of the transition logic here. 1361 */ 1362 private void updatePowerStateLocked() { 1363 if (!mSystemReady || mDirty == 0) { 1364 return; 1365 } 1366 if (!Thread.holdsLock(mLock)) { 1367 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked"); 1368 } 1369 1370 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState"); 1371 try { 1372 // Phase 0: Basic state updates. 1373 updateIsPoweredLocked(mDirty); 1374 updateStayOnLocked(mDirty); 1375 updateScreenBrightnessBoostLocked(mDirty); 1376 1377 // Phase 1: Update wakefulness. 1378 // Loop because the wake lock and user activity computations are influenced 1379 // by changes in wakefulness. 1380 final long now = SystemClock.uptimeMillis(); 1381 int dirtyPhase2 = 0; 1382 for (;;) { 1383 int dirtyPhase1 = mDirty; 1384 dirtyPhase2 |= dirtyPhase1; 1385 mDirty = 0; 1386 1387 updateWakeLockSummaryLocked(dirtyPhase1); 1388 updateUserActivitySummaryLocked(now, dirtyPhase1); 1389 if (!updateWakefulnessLocked(dirtyPhase1)) { 1390 break; 1391 } 1392 } 1393 1394 // Phase 2: Update display power state. 1395 boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2); 1396 1397 // Phase 3: Update dream state (depends on display ready signal). 1398 updateDreamLocked(dirtyPhase2, displayBecameReady); 1399 1400 // Phase 4: Send notifications, if needed. 1401 finishWakefulnessChangeIfNeededLocked(); 1402 1403 // Phase 5: Update suspend blocker. 1404 // Because we might release the last suspend blocker here, we need to make sure 1405 // we finished everything else first! 1406 updateSuspendBlockerLocked(); 1407 } finally { 1408 Trace.traceEnd(Trace.TRACE_TAG_POWER); 1409 } 1410 } 1411 1412 /** 1413 * Updates the value of mIsPowered. 1414 * Sets DIRTY_IS_POWERED if a change occurred. 1415 */ 1416 private void updateIsPoweredLocked(int dirty) { 1417 if ((dirty & DIRTY_BATTERY_STATE) != 0) { 1418 final boolean wasPowered = mIsPowered; 1419 final int oldPlugType = mPlugType; 1420 final boolean oldLevelLow = mBatteryLevelLow; 1421 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY); 1422 mPlugType = mBatteryManagerInternal.getPlugType(); 1423 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel(); 1424 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow(); 1425 1426 if (DEBUG_SPEW) { 1427 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered 1428 + ", mIsPowered=" + mIsPowered 1429 + ", oldPlugType=" + oldPlugType 1430 + ", mPlugType=" + mPlugType 1431 + ", mBatteryLevel=" + mBatteryLevel); 1432 } 1433 1434 if (wasPowered != mIsPowered || oldPlugType != mPlugType) { 1435 mDirty |= DIRTY_IS_POWERED; 1436 1437 // Update wireless dock detection state. 1438 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update( 1439 mIsPowered, mPlugType, mBatteryLevel); 1440 1441 // Treat plugging and unplugging the devices as a user activity. 1442 // Users find it disconcerting when they plug or unplug the device 1443 // and it shuts off right away. 1444 // Some devices also wake the device when plugged or unplugged because 1445 // they don't have a charging LED. 1446 final long now = SystemClock.uptimeMillis(); 1447 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType, 1448 dockedOnWirelessCharger)) { 1449 wakeUpNoUpdateLocked(now, "android.server.power:POWER", Process.SYSTEM_UID, 1450 mContext.getOpPackageName(), Process.SYSTEM_UID); 1451 } 1452 userActivityNoUpdateLocked( 1453 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 1454 1455 // Tell the notifier whether wireless charging has started so that 1456 // it can provide feedback to the user. 1457 if (dockedOnWirelessCharger) { 1458 mNotifier.onWirelessChargingStarted(); 1459 } 1460 } 1461 1462 if (wasPowered != mIsPowered || oldLevelLow != mBatteryLevelLow) { 1463 if (oldLevelLow != mBatteryLevelLow && !mBatteryLevelLow) { 1464 if (DEBUG_SPEW) { 1465 Slog.d(TAG, "updateIsPoweredLocked: resetting low power snooze"); 1466 } 1467 mAutoLowPowerModeSnoozing = false; 1468 } 1469 updateLowPowerModeLocked(); 1470 } 1471 } 1472 } 1473 1474 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked( 1475 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) { 1476 // Don't wake when powered unless configured to do so. 1477 if (!mWakeUpWhenPluggedOrUnpluggedConfig) { 1478 return false; 1479 } 1480 1481 // Don't wake when undocked from wireless charger. 1482 // See WirelessChargerDetector for justification. 1483 if (wasPowered && !mIsPowered 1484 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 1485 return false; 1486 } 1487 1488 // Don't wake when docked on wireless charger unless we are certain of it. 1489 // See WirelessChargerDetector for justification. 1490 if (!wasPowered && mIsPowered 1491 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS 1492 && !dockedOnWirelessCharger) { 1493 return false; 1494 } 1495 1496 // If already dreaming and becoming powered, then don't wake. 1497 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) { 1498 return false; 1499 } 1500 1501 // Don't wake while theater mode is enabled. 1502 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) { 1503 return false; 1504 } 1505 1506 // Otherwise wake up! 1507 return true; 1508 } 1509 1510 /** 1511 * Updates the value of mStayOn. 1512 * Sets DIRTY_STAY_ON if a change occurred. 1513 */ 1514 private void updateStayOnLocked(int dirty) { 1515 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) { 1516 final boolean wasStayOn = mStayOn; 1517 if (mStayOnWhilePluggedInSetting != 0 1518 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1519 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting); 1520 } else { 1521 mStayOn = false; 1522 } 1523 1524 if (mStayOn != wasStayOn) { 1525 mDirty |= DIRTY_STAY_ON; 1526 } 1527 } 1528 } 1529 1530 /** 1531 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks. 1532 * Note that most wake-locks are ignored when the system is asleep. 1533 * 1534 * This function must have no other side-effects. 1535 */ 1536 @SuppressWarnings("deprecation") 1537 private void updateWakeLockSummaryLocked(int dirty) { 1538 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) { 1539 mWakeLockSummary = 0; 1540 1541 final int numWakeLocks = mWakeLocks.size(); 1542 for (int i = 0; i < numWakeLocks; i++) { 1543 final WakeLock wakeLock = mWakeLocks.get(i); 1544 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 1545 case PowerManager.PARTIAL_WAKE_LOCK: 1546 if (!wakeLock.mDisabled) { 1547 // We only respect this if the wake lock is not disabled. 1548 mWakeLockSummary |= WAKE_LOCK_CPU; 1549 } 1550 break; 1551 case PowerManager.FULL_WAKE_LOCK: 1552 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT; 1553 break; 1554 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1555 mWakeLockSummary |= WAKE_LOCK_SCREEN_BRIGHT; 1556 break; 1557 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1558 mWakeLockSummary |= WAKE_LOCK_SCREEN_DIM; 1559 break; 1560 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1561 mWakeLockSummary |= WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1562 break; 1563 case PowerManager.DOZE_WAKE_LOCK: 1564 mWakeLockSummary |= WAKE_LOCK_DOZE; 1565 break; 1566 case PowerManager.DRAW_WAKE_LOCK: 1567 mWakeLockSummary |= WAKE_LOCK_DRAW; 1568 case PowerManager.SUSTAINED_PERFORMANCE_WAKE_LOCK: 1569 if (!wakeLock.mDisabled) { 1570 mWakeLockSummary |= WAKE_LOCK_SUSTAINED_PERFORMANCE; 1571 } 1572 break; 1573 } 1574 } 1575 1576 // Cancel wake locks that make no sense based on the current state. 1577 if (mWakefulness != WAKEFULNESS_DOZING) { 1578 mWakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW); 1579 } 1580 if (mWakefulness == WAKEFULNESS_ASLEEP 1581 || (mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 1582 mWakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM 1583 | WAKE_LOCK_BUTTON_BRIGHT); 1584 if (mWakefulness == WAKEFULNESS_ASLEEP) { 1585 mWakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF; 1586 } 1587 } 1588 1589 // Infer implied wake locks where necessary based on the current state. 1590 if ((mWakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) { 1591 if (mWakefulness == WAKEFULNESS_AWAKE) { 1592 mWakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE; 1593 } else if (mWakefulness == WAKEFULNESS_DREAMING) { 1594 mWakeLockSummary |= WAKE_LOCK_CPU; 1595 } 1596 } 1597 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 1598 mWakeLockSummary |= WAKE_LOCK_CPU; 1599 } 1600 1601 if (DEBUG_SPEW) { 1602 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness=" 1603 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1604 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 1605 } 1606 } 1607 } 1608 1609 /** 1610 * Updates the value of mUserActivitySummary to summarize the user requested 1611 * state of the system such as whether the screen should be bright or dim. 1612 * Note that user activity is ignored when the system is asleep. 1613 * 1614 * This function must have no other side-effects. 1615 */ 1616 private void updateUserActivitySummaryLocked(long now, int dirty) { 1617 // Update the status of the user activity timeout timer. 1618 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY 1619 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) { 1620 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT); 1621 1622 long nextTimeout = 0; 1623 if (mWakefulness == WAKEFULNESS_AWAKE 1624 || mWakefulness == WAKEFULNESS_DREAMING 1625 || mWakefulness == WAKEFULNESS_DOZING) { 1626 final int sleepTimeout = getSleepTimeoutLocked(); 1627 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 1628 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 1629 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager; 1630 1631 mUserActivitySummary = 0; 1632 if (mLastUserActivityTime >= mLastWakeTime) { 1633 nextTimeout = mLastUserActivityTime 1634 + screenOffTimeout - screenDimDuration; 1635 if (now < nextTimeout) { 1636 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1637 } else { 1638 nextTimeout = mLastUserActivityTime + screenOffTimeout; 1639 if (now < nextTimeout) { 1640 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1641 } 1642 } 1643 } 1644 if (mUserActivitySummary == 0 1645 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) { 1646 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout; 1647 if (now < nextTimeout) { 1648 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT) { 1649 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT; 1650 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) { 1651 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM; 1652 } 1653 } 1654 } 1655 1656 if (mUserActivitySummary == 0) { 1657 if (sleepTimeout >= 0) { 1658 final long anyUserActivity = Math.max(mLastUserActivityTime, 1659 mLastUserActivityTimeNoChangeLights); 1660 if (anyUserActivity >= mLastWakeTime) { 1661 nextTimeout = anyUserActivity + sleepTimeout; 1662 if (now < nextTimeout) { 1663 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1664 } 1665 } 1666 } else { 1667 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1668 nextTimeout = -1; 1669 } 1670 } 1671 1672 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) { 1673 if ((mUserActivitySummary & 1674 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) { 1675 // Device is being kept awake by recent user activity 1676 if (nextTimeout >= now && mOverriddenTimeout == -1) { 1677 // Save when the next timeout would have occurred 1678 mOverriddenTimeout = nextTimeout; 1679 } 1680 } 1681 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM; 1682 nextTimeout = -1; 1683 } 1684 1685 if (mUserActivitySummary != 0 && nextTimeout >= 0) { 1686 Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT); 1687 msg.setAsynchronous(true); 1688 mHandler.sendMessageAtTime(msg, nextTimeout); 1689 } 1690 } else { 1691 mUserActivitySummary = 0; 1692 } 1693 1694 if (DEBUG_SPEW) { 1695 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness=" 1696 + PowerManagerInternal.wakefulnessToString(mWakefulness) 1697 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 1698 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout)); 1699 } 1700 } 1701 } 1702 1703 /** 1704 * Called when a user activity timeout has occurred. 1705 * Simply indicates that something about user activity has changed so that the new 1706 * state can be recomputed when the power state is updated. 1707 * 1708 * This function must have no other side-effects besides setting the dirty 1709 * bit and calling update power state. Wakefulness transitions are handled elsewhere. 1710 */ 1711 private void handleUserActivityTimeout() { // runs on handler thread 1712 synchronized (mLock) { 1713 if (DEBUG_SPEW) { 1714 Slog.d(TAG, "handleUserActivityTimeout"); 1715 } 1716 1717 mDirty |= DIRTY_USER_ACTIVITY; 1718 updatePowerStateLocked(); 1719 } 1720 } 1721 1722 private int getSleepTimeoutLocked() { 1723 int timeout = mSleepTimeoutSetting; 1724 if (timeout <= 0) { 1725 return -1; 1726 } 1727 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1728 } 1729 1730 private int getScreenOffTimeoutLocked(int sleepTimeout) { 1731 int timeout = mScreenOffTimeoutSetting; 1732 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) { 1733 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin); 1734 } 1735 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) { 1736 timeout = (int)Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager); 1737 } 1738 if (sleepTimeout >= 0) { 1739 timeout = Math.min(timeout, sleepTimeout); 1740 } 1741 return Math.max(timeout, mMinimumScreenOffTimeoutConfig); 1742 } 1743 1744 private int getScreenDimDurationLocked(int screenOffTimeout) { 1745 return Math.min(mMaximumScreenDimDurationConfig, 1746 (int)(screenOffTimeout * mMaximumScreenDimRatioConfig)); 1747 } 1748 1749 /** 1750 * Updates the wakefulness of the device. 1751 * 1752 * This is the function that decides whether the device should start dreaming 1753 * based on the current wake locks and user activity state. It may modify mDirty 1754 * if the wakefulness changes. 1755 * 1756 * Returns true if the wakefulness changed and we need to restart power state calculation. 1757 */ 1758 private boolean updateWakefulnessLocked(int dirty) { 1759 boolean changed = false; 1760 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED 1761 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE 1762 | DIRTY_DOCK_STATE)) != 0) { 1763 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) { 1764 if (DEBUG_SPEW) { 1765 Slog.d(TAG, "updateWakefulnessLocked: Bed time..."); 1766 } 1767 final long time = SystemClock.uptimeMillis(); 1768 if (shouldNapAtBedTimeLocked()) { 1769 changed = napNoUpdateLocked(time, Process.SYSTEM_UID); 1770 } else { 1771 changed = goToSleepNoUpdateLocked(time, 1772 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1773 } 1774 } 1775 } 1776 return changed; 1777 } 1778 1779 /** 1780 * Returns true if the device should automatically nap and start dreaming when the user 1781 * activity timeout has expired and it's bedtime. 1782 */ 1783 private boolean shouldNapAtBedTimeLocked() { 1784 return mDreamsActivateOnSleepSetting 1785 || (mDreamsActivateOnDockSetting 1786 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED); 1787 } 1788 1789 /** 1790 * Returns true if the device should go to sleep now. 1791 * Also used when exiting a dream to determine whether we should go back 1792 * to being fully awake or else go to sleep for good. 1793 */ 1794 private boolean isItBedTimeYetLocked() { 1795 return mBootCompleted && !isBeingKeptAwakeLocked(); 1796 } 1797 1798 /** 1799 * Returns true if the device is being kept awake by a wake lock, user activity 1800 * or the stay on while powered setting. We also keep the phone awake when 1801 * the proximity sensor returns a positive result so that the device does not 1802 * lock while in a phone call. This function only controls whether the device 1803 * will go to sleep or dream which is independent of whether it will be allowed 1804 * to suspend. 1805 */ 1806 private boolean isBeingKeptAwakeLocked() { 1807 return mStayOn 1808 || mProximityPositive 1809 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0 1810 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1811 | USER_ACTIVITY_SCREEN_DIM)) != 0 1812 || mScreenBrightnessBoostInProgress; 1813 } 1814 1815 /** 1816 * Determines whether to post a message to the sandman to update the dream state. 1817 */ 1818 private void updateDreamLocked(int dirty, boolean displayBecameReady) { 1819 if ((dirty & (DIRTY_WAKEFULNESS 1820 | DIRTY_USER_ACTIVITY 1821 | DIRTY_WAKE_LOCKS 1822 | DIRTY_BOOT_COMPLETED 1823 | DIRTY_SETTINGS 1824 | DIRTY_IS_POWERED 1825 | DIRTY_STAY_ON 1826 | DIRTY_PROXIMITY_POSITIVE 1827 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) { 1828 if (mDisplayReady) { 1829 scheduleSandmanLocked(); 1830 } 1831 } 1832 } 1833 1834 private void scheduleSandmanLocked() { 1835 if (!mSandmanScheduled) { 1836 mSandmanScheduled = true; 1837 Message msg = mHandler.obtainMessage(MSG_SANDMAN); 1838 msg.setAsynchronous(true); 1839 mHandler.sendMessage(msg); 1840 } 1841 } 1842 1843 /** 1844 * Called when the device enters or exits a dreaming or dozing state. 1845 * 1846 * We do this asynchronously because we must call out of the power manager to start 1847 * the dream and we don't want to hold our lock while doing so. There is a risk that 1848 * the device will wake or go to sleep in the meantime so we have to handle that case. 1849 */ 1850 private void handleSandman() { // runs on handler thread 1851 // Handle preconditions. 1852 final boolean startDreaming; 1853 final int wakefulness; 1854 synchronized (mLock) { 1855 mSandmanScheduled = false; 1856 wakefulness = mWakefulness; 1857 if (mSandmanSummoned && mDisplayReady) { 1858 startDreaming = canDreamLocked() || canDozeLocked(); 1859 mSandmanSummoned = false; 1860 } else { 1861 startDreaming = false; 1862 } 1863 } 1864 1865 // Start dreaming if needed. 1866 // We only control the dream on the handler thread, so we don't need to worry about 1867 // concurrent attempts to start or stop the dream. 1868 final boolean isDreaming; 1869 if (mDreamManager != null) { 1870 // Restart the dream whenever the sandman is summoned. 1871 if (startDreaming) { 1872 mDreamManager.stopDream(false /*immediate*/); 1873 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING); 1874 } 1875 isDreaming = mDreamManager.isDreaming(); 1876 } else { 1877 isDreaming = false; 1878 } 1879 1880 // Update dream state. 1881 synchronized (mLock) { 1882 // Remember the initial battery level when the dream started. 1883 if (startDreaming && isDreaming) { 1884 mBatteryLevelWhenDreamStarted = mBatteryLevel; 1885 if (wakefulness == WAKEFULNESS_DOZING) { 1886 Slog.i(TAG, "Dozing..."); 1887 } else { 1888 Slog.i(TAG, "Dreaming..."); 1889 } 1890 } 1891 1892 // If preconditions changed, wait for the next iteration to determine 1893 // whether the dream should continue (or be restarted). 1894 if (mSandmanSummoned || mWakefulness != wakefulness) { 1895 return; // wait for next cycle 1896 } 1897 1898 // Determine whether the dream should continue. 1899 if (wakefulness == WAKEFULNESS_DREAMING) { 1900 if (isDreaming && canDreamLocked()) { 1901 if (mDreamsBatteryLevelDrainCutoffConfig >= 0 1902 && mBatteryLevel < mBatteryLevelWhenDreamStarted 1903 - mDreamsBatteryLevelDrainCutoffConfig 1904 && !isBeingKeptAwakeLocked()) { 1905 // If the user activity timeout expired and the battery appears 1906 // to be draining faster than it is charging then stop dreaming 1907 // and go to sleep. 1908 Slog.i(TAG, "Stopping dream because the battery appears to " 1909 + "be draining faster than it is charging. " 1910 + "Battery level when dream started: " 1911 + mBatteryLevelWhenDreamStarted + "%. " 1912 + "Battery level now: " + mBatteryLevel + "%."); 1913 } else { 1914 return; // continue dreaming 1915 } 1916 } 1917 1918 // Dream has ended or will be stopped. Update the power state. 1919 if (isItBedTimeYetLocked()) { 1920 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(), 1921 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID); 1922 updatePowerStateLocked(); 1923 } else { 1924 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), "android.server.power:DREAM", 1925 Process.SYSTEM_UID, mContext.getOpPackageName(), Process.SYSTEM_UID); 1926 updatePowerStateLocked(); 1927 } 1928 } else if (wakefulness == WAKEFULNESS_DOZING) { 1929 if (isDreaming) { 1930 return; // continue dozing 1931 } 1932 1933 // Doze has ended or will be stopped. Update the power state. 1934 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID); 1935 updatePowerStateLocked(); 1936 } 1937 } 1938 1939 // Stop dream. 1940 if (isDreaming) { 1941 mDreamManager.stopDream(false /*immediate*/); 1942 } 1943 } 1944 1945 /** 1946 * Returns true if the device is allowed to dream in its current state. 1947 */ 1948 private boolean canDreamLocked() { 1949 if (mWakefulness != WAKEFULNESS_DREAMING 1950 || !mDreamsSupportedConfig 1951 || !mDreamsEnabledSetting 1952 || !mDisplayPowerRequest.isBrightOrDim() 1953 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT 1954 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0 1955 || !mBootCompleted) { 1956 return false; 1957 } 1958 if (!isBeingKeptAwakeLocked()) { 1959 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) { 1960 return false; 1961 } 1962 if (!mIsPowered 1963 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0 1964 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) { 1965 return false; 1966 } 1967 if (mIsPowered 1968 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0 1969 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) { 1970 return false; 1971 } 1972 } 1973 return true; 1974 } 1975 1976 /** 1977 * Returns true if the device is allowed to doze in its current state. 1978 */ 1979 private boolean canDozeLocked() { 1980 return mWakefulness == WAKEFULNESS_DOZING; 1981 } 1982 1983 /** 1984 * Updates the display power state asynchronously. 1985 * When the update is finished, mDisplayReady will be set to true. The display 1986 * controller posts a message to tell us when the actual display power state 1987 * has been updated so we come back here to double-check and finish up. 1988 * 1989 * This function recalculates the display power state each time. 1990 * 1991 * @return True if the display became ready. 1992 */ 1993 private boolean updateDisplayPowerStateLocked(int dirty) { 1994 final boolean oldDisplayReady = mDisplayReady; 1995 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS 1996 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED 1997 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) { 1998 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked(); 1999 2000 // Determine appropriate screen brightness and auto-brightness adjustments. 2001 boolean brightnessSetByUser = true; 2002 int screenBrightness = mScreenBrightnessSettingDefault; 2003 float screenAutoBrightnessAdjustment = 0.0f; 2004 boolean autoBrightness = (mScreenBrightnessModeSetting == 2005 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 2006 if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) { 2007 screenBrightness = mScreenBrightnessOverrideFromWindowManager; 2008 autoBrightness = false; 2009 brightnessSetByUser = false; 2010 } else if (isValidBrightness(mTemporaryScreenBrightnessSettingOverride)) { 2011 screenBrightness = mTemporaryScreenBrightnessSettingOverride; 2012 } else if (isValidBrightness(mScreenBrightnessSetting)) { 2013 screenBrightness = mScreenBrightnessSetting; 2014 } 2015 if (autoBrightness) { 2016 screenBrightness = mScreenBrightnessSettingDefault; 2017 if (isValidAutoBrightnessAdjustment( 2018 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride)) { 2019 screenAutoBrightnessAdjustment = 2020 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride; 2021 } else if (isValidAutoBrightnessAdjustment( 2022 mScreenAutoBrightnessAdjustmentSetting)) { 2023 screenAutoBrightnessAdjustment = mScreenAutoBrightnessAdjustmentSetting; 2024 } 2025 } 2026 screenBrightness = Math.max(Math.min(screenBrightness, 2027 mScreenBrightnessSettingMaximum), mScreenBrightnessSettingMinimum); 2028 screenAutoBrightnessAdjustment = Math.max(Math.min( 2029 screenAutoBrightnessAdjustment, 1.0f), -1.0f); 2030 2031 // Update display power request. 2032 mDisplayPowerRequest.screenBrightness = screenBrightness; 2033 mDisplayPowerRequest.screenAutoBrightnessAdjustment = 2034 screenAutoBrightnessAdjustment; 2035 mDisplayPowerRequest.brightnessSetByUser = brightnessSetByUser; 2036 mDisplayPowerRequest.useAutoBrightness = autoBrightness; 2037 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked(); 2038 mDisplayPowerRequest.lowPowerMode = mLowPowerModeEnabled; 2039 mDisplayPowerRequest.boostScreenBrightness = mScreenBrightnessBoostInProgress; 2040 mDisplayPowerRequest.useTwilight = mBrightnessUseTwilight; 2041 2042 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) { 2043 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager; 2044 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND 2045 && (mWakeLockSummary & WAKE_LOCK_DRAW) != 0) { 2046 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE; 2047 } 2048 mDisplayPowerRequest.dozeScreenBrightness = 2049 mDozeScreenBrightnessOverrideFromDreamManager; 2050 } else { 2051 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN; 2052 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 2053 } 2054 2055 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest, 2056 mRequestWaitForNegativeProximity); 2057 mRequestWaitForNegativeProximity = false; 2058 2059 if (DEBUG_SPEW) { 2060 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady 2061 + ", policy=" + mDisplayPowerRequest.policy 2062 + ", mWakefulness=" + mWakefulness 2063 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary) 2064 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary) 2065 + ", mBootCompleted=" + mBootCompleted 2066 + ", mScreenBrightnessBoostInProgress=" 2067 + mScreenBrightnessBoostInProgress); 2068 } 2069 } 2070 return mDisplayReady && !oldDisplayReady; 2071 } 2072 2073 private void updateScreenBrightnessBoostLocked(int dirty) { 2074 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) { 2075 if (mScreenBrightnessBoostInProgress) { 2076 final long now = SystemClock.uptimeMillis(); 2077 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 2078 if (mLastScreenBrightnessBoostTime > mLastSleepTime) { 2079 final long boostTimeout = mLastScreenBrightnessBoostTime + 2080 SCREEN_BRIGHTNESS_BOOST_TIMEOUT; 2081 if (boostTimeout > now) { 2082 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT); 2083 msg.setAsynchronous(true); 2084 mHandler.sendMessageAtTime(msg, boostTimeout); 2085 return; 2086 } 2087 } 2088 mScreenBrightnessBoostInProgress = false; 2089 mNotifier.onScreenBrightnessBoostChanged(); 2090 userActivityNoUpdateLocked(now, 2091 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 2092 } 2093 } 2094 } 2095 2096 private static boolean isValidBrightness(int value) { 2097 return value >= 0 && value <= 255; 2098 } 2099 2100 private static boolean isValidAutoBrightnessAdjustment(float value) { 2101 // Handles NaN by always returning false. 2102 return value >= -1.0f && value <= 1.0f; 2103 } 2104 2105 private int getDesiredScreenPolicyLocked() { 2106 if (mWakefulness == WAKEFULNESS_ASLEEP) { 2107 return DisplayPowerRequest.POLICY_OFF; 2108 } 2109 2110 if (mWakefulness == WAKEFULNESS_DOZING) { 2111 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) { 2112 return DisplayPowerRequest.POLICY_DOZE; 2113 } 2114 if (mDozeAfterScreenOffConfig) { 2115 return DisplayPowerRequest.POLICY_OFF; 2116 } 2117 // Fall through and preserve the current screen policy if not configured to 2118 // doze after screen off. This causes the screen off transition to be skipped. 2119 } 2120 2121 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0 2122 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0 2123 || !mBootCompleted 2124 || mScreenBrightnessBoostInProgress) { 2125 return DisplayPowerRequest.POLICY_BRIGHT; 2126 } 2127 2128 return DisplayPowerRequest.POLICY_DIM; 2129 } 2130 2131 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks = 2132 new DisplayManagerInternal.DisplayPowerCallbacks() { 2133 private int mDisplayState = Display.STATE_UNKNOWN; 2134 2135 @Override 2136 public void onStateChanged() { 2137 synchronized (mLock) { 2138 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED; 2139 updatePowerStateLocked(); 2140 } 2141 } 2142 2143 @Override 2144 public void onProximityPositive() { 2145 synchronized (mLock) { 2146 mProximityPositive = true; 2147 mDirty |= DIRTY_PROXIMITY_POSITIVE; 2148 updatePowerStateLocked(); 2149 } 2150 } 2151 2152 @Override 2153 public void onProximityNegative() { 2154 synchronized (mLock) { 2155 mProximityPositive = false; 2156 mDirty |= DIRTY_PROXIMITY_POSITIVE; 2157 userActivityNoUpdateLocked(SystemClock.uptimeMillis(), 2158 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID); 2159 updatePowerStateLocked(); 2160 } 2161 } 2162 2163 @Override 2164 public void onDisplayStateChange(int state) { 2165 // This method is only needed to support legacy display blanking behavior 2166 // where the display's power state is coupled to suspend or to the power HAL. 2167 // The order of operations matters here. 2168 synchronized (mLock) { 2169 if (mDisplayState != state) { 2170 mDisplayState = state; 2171 if (state == Display.STATE_OFF) { 2172 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 2173 setHalInteractiveModeLocked(false); 2174 } 2175 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2176 setHalAutoSuspendModeLocked(true); 2177 } 2178 } else { 2179 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2180 setHalAutoSuspendModeLocked(false); 2181 } 2182 if (!mDecoupleHalInteractiveModeFromDisplayConfig) { 2183 setHalInteractiveModeLocked(true); 2184 } 2185 } 2186 } 2187 } 2188 } 2189 2190 @Override 2191 public void acquireSuspendBlocker() { 2192 mDisplaySuspendBlocker.acquire(); 2193 } 2194 2195 @Override 2196 public void releaseSuspendBlocker() { 2197 mDisplaySuspendBlocker.release(); 2198 } 2199 2200 @Override 2201 public String toString() { 2202 synchronized (this) { 2203 return "state=" + Display.stateToString(mDisplayState); 2204 } 2205 } 2206 }; 2207 2208 private boolean shouldUseProximitySensorLocked() { 2209 return (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0; 2210 } 2211 2212 /** 2213 * Updates the suspend blocker that keeps the CPU alive. 2214 * 2215 * This function must have no other side-effects. 2216 */ 2217 private void updateSuspendBlockerLocked() { 2218 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0); 2219 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked(); 2220 final boolean autoSuspend = !needDisplaySuspendBlocker; 2221 final boolean interactive = mDisplayPowerRequest.isBrightOrDim(); 2222 2223 // Disable auto-suspend if needed. 2224 // FIXME We should consider just leaving auto-suspend enabled forever since 2225 // we already hold the necessary wakelocks. 2226 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2227 setHalAutoSuspendModeLocked(false); 2228 } 2229 2230 // First acquire suspend blockers if needed. 2231 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) { 2232 mWakeLockSuspendBlocker.acquire(); 2233 mHoldingWakeLockSuspendBlocker = true; 2234 } 2235 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) { 2236 mDisplaySuspendBlocker.acquire(); 2237 mHoldingDisplaySuspendBlocker = true; 2238 } 2239 2240 // Inform the power HAL about interactive mode. 2241 // Although we could set interactive strictly based on the wakefulness 2242 // as reported by isInteractive(), it is actually more desirable to track 2243 // the display policy state instead so that the interactive state observed 2244 // by the HAL more accurately tracks transitions between AWAKE and DOZING. 2245 // Refer to getDesiredScreenPolicyLocked() for details. 2246 if (mDecoupleHalInteractiveModeFromDisplayConfig) { 2247 // When becoming non-interactive, we want to defer sending this signal 2248 // until the display is actually ready so that all transitions have 2249 // completed. This is probably a good sign that things have gotten 2250 // too tangled over here... 2251 if (interactive || mDisplayReady) { 2252 setHalInteractiveModeLocked(interactive); 2253 } 2254 } 2255 2256 // Then release suspend blockers if needed. 2257 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) { 2258 mWakeLockSuspendBlocker.release(); 2259 mHoldingWakeLockSuspendBlocker = false; 2260 } 2261 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) { 2262 mDisplaySuspendBlocker.release(); 2263 mHoldingDisplaySuspendBlocker = false; 2264 } 2265 2266 // Enable auto-suspend if needed. 2267 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) { 2268 setHalAutoSuspendModeLocked(true); 2269 } 2270 2271 if (mSustainedPerformanceMode 2272 && (mWakeLockSummary & WAKE_LOCK_SUSTAINED_PERFORMANCE) == 0) { 2273 setSustainedPerformanceModeLocked(false); 2274 } else if (!mSustainedPerformanceMode 2275 && (mWakeLockSummary & WAKE_LOCK_SUSTAINED_PERFORMANCE) != 0) { 2276 setSustainedPerformanceModeLocked(true); 2277 } 2278 } 2279 2280 /** 2281 * Return true if we must keep a suspend blocker active on behalf of the display. 2282 * We do so if the screen is on or is in transition between states. 2283 */ 2284 private boolean needDisplaySuspendBlockerLocked() { 2285 if (!mDisplayReady) { 2286 return true; 2287 } 2288 if (mDisplayPowerRequest.isBrightOrDim()) { 2289 // If we asked for the screen to be on but it is off due to the proximity 2290 // sensor then we may suspend but only if the configuration allows it. 2291 // On some hardware it may not be safe to suspend because the proximity 2292 // sensor may not be correctly configured as a wake-up source. 2293 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive 2294 || !mSuspendWhenScreenOffDueToProximityConfig) { 2295 return true; 2296 } 2297 } 2298 if (mScreenBrightnessBoostInProgress) { 2299 return true; 2300 } 2301 // Let the system suspend if the screen is off or dozing. 2302 return false; 2303 } 2304 2305 private void setHalAutoSuspendModeLocked(boolean enable) { 2306 if (enable != mHalAutoSuspendModeEnabled) { 2307 if (DEBUG) { 2308 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable); 2309 } 2310 mHalAutoSuspendModeEnabled = enable; 2311 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")"); 2312 try { 2313 nativeSetAutoSuspend(enable); 2314 } finally { 2315 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2316 } 2317 } 2318 } 2319 2320 private void setHalInteractiveModeLocked(boolean enable) { 2321 if (enable != mHalInteractiveModeEnabled) { 2322 if (DEBUG) { 2323 Slog.d(TAG, "Setting HAL interactive mode to " + enable); 2324 } 2325 mHalInteractiveModeEnabled = enable; 2326 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")"); 2327 try { 2328 nativeSetInteractive(enable); 2329 } finally { 2330 Trace.traceEnd(Trace.TRACE_TAG_POWER); 2331 } 2332 } 2333 } 2334 2335 private boolean isInteractiveInternal() { 2336 synchronized (mLock) { 2337 return PowerManagerInternal.isInteractive(mWakefulness); 2338 } 2339 } 2340 2341 private boolean isLowPowerModeInternal() { 2342 synchronized (mLock) { 2343 return mLowPowerModeEnabled; 2344 } 2345 } 2346 2347 private boolean setLowPowerModeInternal(boolean mode) { 2348 synchronized (mLock) { 2349 if (DEBUG) Slog.d(TAG, "setLowPowerModeInternal " + mode + " mIsPowered=" + mIsPowered); 2350 if (mIsPowered) { 2351 return false; 2352 } 2353 Settings.Global.putInt(mContext.getContentResolver(), 2354 Settings.Global.LOW_POWER_MODE, mode ? 1 : 0); 2355 mLowPowerModeSetting = mode; 2356 2357 if (mAutoLowPowerModeConfigured && mBatteryLevelLow) { 2358 if (mode && mAutoLowPowerModeSnoozing) { 2359 if (DEBUG_SPEW) { 2360 Slog.d(TAG, "setLowPowerModeInternal: clearing low power mode snooze"); 2361 } 2362 mAutoLowPowerModeSnoozing = false; 2363 } else if (!mode && !mAutoLowPowerModeSnoozing) { 2364 if (DEBUG_SPEW) { 2365 Slog.d(TAG, "setLowPowerModeInternal: snoozing low power mode"); 2366 } 2367 mAutoLowPowerModeSnoozing = true; 2368 } 2369 } 2370 2371 updateLowPowerModeLocked(); 2372 return true; 2373 } 2374 } 2375 2376 private void setSustainedPerformanceModeLocked(boolean mode) { 2377 mSustainedPerformanceMode = mode; 2378 powerHintInternal(POWER_HINT_SUSTAINED_PERFORMANCE, 2379 mSustainedPerformanceMode ? 1 : 0); 2380 } 2381 2382 boolean isDeviceIdleModeInternal() { 2383 synchronized (mLock) { 2384 return mDeviceIdleMode; 2385 } 2386 } 2387 2388 boolean isLightDeviceIdleModeInternal() { 2389 synchronized (mLock) { 2390 return mLightDeviceIdleMode; 2391 } 2392 } 2393 2394 private void handleBatteryStateChangedLocked() { 2395 mDirty |= DIRTY_BATTERY_STATE; 2396 updatePowerStateLocked(); 2397 } 2398 2399 private void shutdownOrRebootInternal(final boolean shutdown, final boolean confirm, 2400 final String reason, boolean wait) { 2401 if (mHandler == null || !mSystemReady) { 2402 throw new IllegalStateException("Too early to call shutdown() or reboot()"); 2403 } 2404 2405 Runnable runnable = new Runnable() { 2406 @Override 2407 public void run() { 2408 synchronized (this) { 2409 if (shutdown) { 2410 ShutdownThread.shutdown(mContext, reason, confirm); 2411 } else { 2412 ShutdownThread.reboot(mContext, reason, confirm); 2413 } 2414 } 2415 } 2416 }; 2417 2418 // ShutdownThread must run on a looper capable of displaying the UI. 2419 Message msg = Message.obtain(mHandler, runnable); 2420 msg.setAsynchronous(true); 2421 mHandler.sendMessage(msg); 2422 2423 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 2424 if (wait) { 2425 synchronized (runnable) { 2426 while (true) { 2427 try { 2428 runnable.wait(); 2429 } catch (InterruptedException e) { 2430 } 2431 } 2432 } 2433 } 2434 } 2435 2436 private void crashInternal(final String message) { 2437 Thread t = new Thread("PowerManagerService.crash()") { 2438 @Override 2439 public void run() { 2440 throw new RuntimeException(message); 2441 } 2442 }; 2443 try { 2444 t.start(); 2445 t.join(); 2446 } catch (InterruptedException e) { 2447 Slog.wtf(TAG, e); 2448 } 2449 } 2450 2451 void setStayOnSettingInternal(int val) { 2452 Settings.Global.putInt(mContext.getContentResolver(), 2453 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val); 2454 } 2455 2456 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(int timeMs) { 2457 synchronized (mLock) { 2458 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs; 2459 mDirty |= DIRTY_SETTINGS; 2460 updatePowerStateLocked(); 2461 } 2462 } 2463 2464 boolean setDeviceIdleModeInternal(boolean enabled) { 2465 synchronized (mLock) { 2466 if (mDeviceIdleMode != enabled) { 2467 mDeviceIdleMode = enabled; 2468 updateWakeLockDisabledStatesLocked(); 2469 if (enabled) { 2470 EventLogTags.writeDeviceIdleOnPhase("power"); 2471 } else { 2472 EventLogTags.writeDeviceIdleOffPhase("power"); 2473 } 2474 return true; 2475 } 2476 return false; 2477 } 2478 } 2479 2480 boolean setLightDeviceIdleModeInternal(boolean enabled) { 2481 synchronized (mLock) { 2482 if (mLightDeviceIdleMode != enabled) { 2483 mLightDeviceIdleMode = enabled; 2484 return true; 2485 } 2486 return false; 2487 } 2488 } 2489 2490 void setDeviceIdleWhitelistInternal(int[] appids) { 2491 synchronized (mLock) { 2492 mDeviceIdleWhitelist = appids; 2493 if (mDeviceIdleMode) { 2494 updateWakeLockDisabledStatesLocked(); 2495 } 2496 } 2497 } 2498 2499 void setDeviceIdleTempWhitelistInternal(int[] appids) { 2500 synchronized (mLock) { 2501 mDeviceIdleTempWhitelist = appids; 2502 if (mDeviceIdleMode) { 2503 updateWakeLockDisabledStatesLocked(); 2504 } 2505 } 2506 } 2507 2508 void updateUidProcStateInternal(int uid, int procState) { 2509 synchronized (mLock) { 2510 mUidState.put(uid, procState); 2511 if (mDeviceIdleMode || mSustainedPerformanceUid.get(uid) != 0) { 2512 updateWakeLockDisabledStatesLocked(); 2513 } 2514 } 2515 } 2516 2517 void uidGoneInternal(int uid) { 2518 synchronized (mLock) { 2519 mUidState.delete(uid); 2520 if (mDeviceIdleMode) { 2521 updateWakeLockDisabledStatesLocked(); 2522 } 2523 } 2524 } 2525 2526 private void updateWakeLockDisabledStatesLocked() { 2527 boolean changed = false; 2528 final int numWakeLocks = mWakeLocks.size(); 2529 for (int i = 0; i < numWakeLocks; i++) { 2530 final WakeLock wakeLock = mWakeLocks.get(i); 2531 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2532 == PowerManager.PARTIAL_WAKE_LOCK 2533 || (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2534 == PowerManager.SUSTAINED_PERFORMANCE_WAKE_LOCK) { 2535 if (setWakeLockDisabledStateLocked(wakeLock)) { 2536 changed = true; 2537 if (wakeLock.mDisabled) { 2538 // This wake lock is no longer being respected. 2539 notifyWakeLockReleasedLocked(wakeLock); 2540 } else { 2541 notifyWakeLockAcquiredLocked(wakeLock); 2542 } 2543 } 2544 } 2545 } 2546 if (changed) { 2547 mDirty |= DIRTY_WAKE_LOCKS; 2548 updatePowerStateLocked(); 2549 } 2550 } 2551 2552 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) { 2553 boolean disabled = false; 2554 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2555 == PowerManager.PARTIAL_WAKE_LOCK) { 2556 if (mDeviceIdleMode) { 2557 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid); 2558 // If we are in idle mode, we will ignore all partial wake locks that are 2559 // for application uids that are not whitelisted. 2560 if (appid >= Process.FIRST_APPLICATION_UID && 2561 Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 && 2562 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 && 2563 mUidState.get(wakeLock.mOwnerUid, 2564 ActivityManager.PROCESS_STATE_CACHED_EMPTY) 2565 > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) { 2566 disabled = true; 2567 } 2568 } 2569 } else if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) 2570 == PowerManager.SUSTAINED_PERFORMANCE_WAKE_LOCK 2571 && mUidState.get(wakeLock.mOwnerUid, 2572 ActivityManager.PROCESS_STATE_CACHED_EMPTY) 2573 > ActivityManager.PROCESS_STATE_TOP) { 2574 disabled = true; 2575 } 2576 if (wakeLock.mDisabled != disabled) { 2577 wakeLock.mDisabled = disabled; 2578 return true; 2579 } 2580 return false; 2581 } 2582 2583 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() { 2584 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0 2585 && mMaximumScreenOffTimeoutFromDeviceAdmin < Integer.MAX_VALUE; 2586 } 2587 2588 private void setAttentionLightInternal(boolean on, int color) { 2589 Light light; 2590 synchronized (mLock) { 2591 if (!mSystemReady) { 2592 return; 2593 } 2594 light = mAttentionLight; 2595 } 2596 2597 // Control light outside of lock. 2598 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 2599 } 2600 2601 private void boostScreenBrightnessInternal(long eventTime, int uid) { 2602 synchronized (mLock) { 2603 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP 2604 || eventTime < mLastScreenBrightnessBoostTime) { 2605 return; 2606 } 2607 2608 Slog.i(TAG, "Brightness boost activated (uid " + uid +")..."); 2609 mLastScreenBrightnessBoostTime = eventTime; 2610 if (!mScreenBrightnessBoostInProgress) { 2611 mScreenBrightnessBoostInProgress = true; 2612 mNotifier.onScreenBrightnessBoostChanged(); 2613 } 2614 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2615 2616 userActivityNoUpdateLocked(eventTime, 2617 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid); 2618 updatePowerStateLocked(); 2619 } 2620 } 2621 2622 private boolean isScreenBrightnessBoostedInternal() { 2623 synchronized (mLock) { 2624 return mScreenBrightnessBoostInProgress; 2625 } 2626 } 2627 2628 /** 2629 * Called when a screen brightness boost timeout has occurred. 2630 * 2631 * This function must have no other side-effects besides setting the dirty 2632 * bit and calling update power state. 2633 */ 2634 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread 2635 synchronized (mLock) { 2636 if (DEBUG_SPEW) { 2637 Slog.d(TAG, "handleScreenBrightnessBoostTimeout"); 2638 } 2639 2640 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST; 2641 updatePowerStateLocked(); 2642 } 2643 } 2644 2645 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) { 2646 synchronized (mLock) { 2647 if (mScreenBrightnessOverrideFromWindowManager != brightness) { 2648 mScreenBrightnessOverrideFromWindowManager = brightness; 2649 mDirty |= DIRTY_SETTINGS; 2650 updatePowerStateLocked(); 2651 } 2652 } 2653 } 2654 2655 private void setUserInactiveOverrideFromWindowManagerInternal() { 2656 synchronized (mLock) { 2657 mUserInactiveOverrideFromWindowManager = true; 2658 mDirty |= DIRTY_USER_ACTIVITY; 2659 updatePowerStateLocked(); 2660 } 2661 } 2662 2663 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) { 2664 synchronized (mLock) { 2665 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) { 2666 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis; 2667 mDirty |= DIRTY_SETTINGS; 2668 updatePowerStateLocked(); 2669 } 2670 } 2671 } 2672 2673 private void setTemporaryScreenBrightnessSettingOverrideInternal(int brightness) { 2674 synchronized (mLock) { 2675 if (mTemporaryScreenBrightnessSettingOverride != brightness) { 2676 mTemporaryScreenBrightnessSettingOverride = brightness; 2677 mDirty |= DIRTY_SETTINGS; 2678 updatePowerStateLocked(); 2679 } 2680 } 2681 } 2682 2683 private void setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(float adj) { 2684 synchronized (mLock) { 2685 // Note: This condition handles NaN because NaN is not equal to any other 2686 // value, including itself. 2687 if (mTemporaryScreenAutoBrightnessAdjustmentSettingOverride != adj) { 2688 mTemporaryScreenAutoBrightnessAdjustmentSettingOverride = adj; 2689 mDirty |= DIRTY_SETTINGS; 2690 updatePowerStateLocked(); 2691 } 2692 } 2693 } 2694 2695 private void setDozeOverrideFromDreamManagerInternal( 2696 int screenState, int screenBrightness) { 2697 synchronized (mLock) { 2698 if (mDozeScreenStateOverrideFromDreamManager != screenState 2699 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) { 2700 mDozeScreenStateOverrideFromDreamManager = screenState; 2701 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness; 2702 mDirty |= DIRTY_SETTINGS; 2703 updatePowerStateLocked(); 2704 } 2705 } 2706 } 2707 2708 private void powerHintInternal(int hintId, int data) { 2709 nativeSendPowerHint(hintId, data); 2710 } 2711 2712 /** 2713 * Low-level function turn the device off immediately, without trying 2714 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown. 2715 * 2716 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null. 2717 */ 2718 public static void lowLevelShutdown(String reason) { 2719 if (reason == null) { 2720 reason = ""; 2721 } 2722 SystemProperties.set("sys.powerctl", "shutdown," + reason); 2723 } 2724 2725 /** 2726 * Low-level function to reboot the device. On success, this 2727 * function doesn't return. If more than 20 seconds passes from 2728 * the time a reboot is requested, this method returns. 2729 * 2730 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 2731 */ 2732 public static void lowLevelReboot(String reason) { 2733 if (reason == null) { 2734 reason = ""; 2735 } 2736 if (reason.equals(PowerManager.REBOOT_RECOVERY) 2737 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) { 2738 SystemProperties.set("sys.powerctl", "reboot,recovery"); 2739 } else { 2740 SystemProperties.set("sys.powerctl", "reboot," + reason); 2741 } 2742 try { 2743 Thread.sleep(20 * 1000L); 2744 } catch (InterruptedException e) { 2745 Thread.currentThread().interrupt(); 2746 } 2747 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!"); 2748 } 2749 2750 @Override // Watchdog.Monitor implementation 2751 public void monitor() { 2752 // Grab and release lock for watchdog monitor to detect deadlocks. 2753 synchronized (mLock) { 2754 } 2755 } 2756 2757 private void dumpInternal(PrintWriter pw) { 2758 pw.println("POWER MANAGER (dumpsys power)\n"); 2759 2760 final WirelessChargerDetector wcd; 2761 synchronized (mLock) { 2762 pw.println("Power Manager State:"); 2763 pw.println(" mDirty=0x" + Integer.toHexString(mDirty)); 2764 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness)); 2765 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging); 2766 pw.println(" mIsPowered=" + mIsPowered); 2767 pw.println(" mPlugType=" + mPlugType); 2768 pw.println(" mBatteryLevel=" + mBatteryLevel); 2769 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted); 2770 pw.println(" mDockState=" + mDockState); 2771 pw.println(" mStayOn=" + mStayOn); 2772 pw.println(" mProximityPositive=" + mProximityPositive); 2773 pw.println(" mBootCompleted=" + mBootCompleted); 2774 pw.println(" mSystemReady=" + mSystemReady); 2775 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled); 2776 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled); 2777 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)); 2778 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)); 2779 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity); 2780 pw.println(" mSandmanScheduled=" + mSandmanScheduled); 2781 pw.println(" mSandmanSummoned=" + mSandmanSummoned); 2782 pw.println(" mLowPowerModeEnabled=" + mLowPowerModeEnabled); 2783 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow); 2784 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode); 2785 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode); 2786 pw.println(" mSustainedPerformanceMode=" + mSustainedPerformanceMode); 2787 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist)); 2788 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist)); 2789 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime)); 2790 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime)); 2791 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime)); 2792 pw.println(" mLastUserActivityTimeNoChangeLights=" 2793 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights)); 2794 pw.println(" mLastInteractivePowerHintTime=" 2795 + TimeUtils.formatUptime(mLastInteractivePowerHintTime)); 2796 pw.println(" mLastScreenBrightnessBoostTime=" 2797 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime)); 2798 pw.println(" mScreenBrightnessBoostInProgress=" 2799 + mScreenBrightnessBoostInProgress); 2800 pw.println(" mDisplayReady=" + mDisplayReady); 2801 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker); 2802 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker); 2803 2804 pw.println(); 2805 pw.println("Settings and Configuration:"); 2806 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig=" 2807 + mDecoupleHalAutoSuspendModeFromDisplayConfig); 2808 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig=" 2809 + mDecoupleHalInteractiveModeFromDisplayConfig); 2810 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig=" 2811 + mWakeUpWhenPluggedOrUnpluggedConfig); 2812 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig=" 2813 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig); 2814 pw.println(" mTheaterModeEnabled=" 2815 + mTheaterModeEnabled); 2816 pw.println(" mSuspendWhenScreenOffDueToProximityConfig=" 2817 + mSuspendWhenScreenOffDueToProximityConfig); 2818 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig); 2819 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig); 2820 pw.println(" mDreamsActivatedOnSleepByDefaultConfig=" 2821 + mDreamsActivatedOnSleepByDefaultConfig); 2822 pw.println(" mDreamsActivatedOnDockByDefaultConfig=" 2823 + mDreamsActivatedOnDockByDefaultConfig); 2824 pw.println(" mDreamsEnabledOnBatteryConfig=" 2825 + mDreamsEnabledOnBatteryConfig); 2826 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig=" 2827 + mDreamsBatteryLevelMinimumWhenPoweredConfig); 2828 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig=" 2829 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig); 2830 pw.println(" mDreamsBatteryLevelDrainCutoffConfig=" 2831 + mDreamsBatteryLevelDrainCutoffConfig); 2832 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting); 2833 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting); 2834 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting); 2835 pw.println(" mDozeAfterScreenOffConfig=" + mDozeAfterScreenOffConfig); 2836 pw.println(" mLowPowerModeSetting=" + mLowPowerModeSetting); 2837 pw.println(" mAutoLowPowerModeConfigured=" + mAutoLowPowerModeConfigured); 2838 pw.println(" mAutoLowPowerModeSnoozing=" + mAutoLowPowerModeSnoozing); 2839 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig); 2840 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig); 2841 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig); 2842 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting); 2843 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting); 2844 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin=" 2845 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced=" 2846 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")"); 2847 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting); 2848 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting); 2849 pw.println(" mScreenAutoBrightnessAdjustmentSetting=" 2850 + mScreenAutoBrightnessAdjustmentSetting); 2851 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting); 2852 pw.println(" mScreenBrightnessOverrideFromWindowManager=" 2853 + mScreenBrightnessOverrideFromWindowManager); 2854 pw.println(" mUserActivityTimeoutOverrideFromWindowManager=" 2855 + mUserActivityTimeoutOverrideFromWindowManager); 2856 pw.println(" mUserInactiveOverrideFromWindowManager=" 2857 + mUserInactiveOverrideFromWindowManager); 2858 pw.println(" mTemporaryScreenBrightnessSettingOverride=" 2859 + mTemporaryScreenBrightnessSettingOverride); 2860 pw.println(" mTemporaryScreenAutoBrightnessAdjustmentSettingOverride=" 2861 + mTemporaryScreenAutoBrightnessAdjustmentSettingOverride); 2862 pw.println(" mDozeScreenStateOverrideFromDreamManager=" 2863 + mDozeScreenStateOverrideFromDreamManager); 2864 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager=" 2865 + mDozeScreenBrightnessOverrideFromDreamManager); 2866 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum); 2867 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum); 2868 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault); 2869 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled); 2870 2871 final int sleepTimeout = getSleepTimeoutLocked(); 2872 final int screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout); 2873 final int screenDimDuration = getScreenDimDurationLocked(screenOffTimeout); 2874 pw.println(); 2875 pw.println("Sleep timeout: " + sleepTimeout + " ms"); 2876 pw.println("Screen off timeout: " + screenOffTimeout + " ms"); 2877 pw.println("Screen dim duration: " + screenDimDuration + " ms"); 2878 2879 pw.println(); 2880 pw.println("UID states:"); 2881 for (int i=0; i<mUidState.size(); i++) { 2882 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i)); 2883 pw.print(": "); pw.println(mUidState.valueAt(i)); 2884 } 2885 2886 pw.println(); 2887 pw.println("Wake Locks: size=" + mWakeLocks.size()); 2888 for (WakeLock wl : mWakeLocks) { 2889 pw.println(" " + wl); 2890 } 2891 2892 pw.println(); 2893 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size()); 2894 for (SuspendBlocker sb : mSuspendBlockers) { 2895 pw.println(" " + sb); 2896 } 2897 2898 pw.println(); 2899 pw.println("Display Power: " + mDisplayPowerCallbacks); 2900 2901 pw.println(); 2902 pw.println("Sustained Performance UIDs:"); 2903 for (int i=0; i<mSustainedPerformanceUid.size(); i++) { 2904 pw.print(" UID "); UserHandle.formatUid(pw, mSustainedPerformanceUid.keyAt(i)); 2905 pw.print(": "); pw.println(mSustainedPerformanceUid.valueAt(i)); 2906 } 2907 2908 2909 wcd = mWirelessChargerDetector; 2910 } 2911 2912 if (wcd != null) { 2913 wcd.dump(pw); 2914 } 2915 } 2916 2917 private SuspendBlocker createSuspendBlockerLocked(String name) { 2918 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name); 2919 mSuspendBlockers.add(suspendBlocker); 2920 return suspendBlocker; 2921 } 2922 2923 private void incrementBootCount() { 2924 synchronized (mLock) { 2925 int count; 2926 try { 2927 count = Settings.Global.getInt( 2928 getContext().getContentResolver(), Settings.Global.BOOT_COUNT); 2929 } catch (SettingNotFoundException e) { 2930 count = 0; 2931 } 2932 Settings.Global.putInt( 2933 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1); 2934 } 2935 } 2936 2937 private static WorkSource copyWorkSource(WorkSource workSource) { 2938 return workSource != null ? new WorkSource(workSource) : null; 2939 } 2940 2941 private final class BatteryReceiver extends BroadcastReceiver { 2942 @Override 2943 public void onReceive(Context context, Intent intent) { 2944 synchronized (mLock) { 2945 handleBatteryStateChangedLocked(); 2946 } 2947 } 2948 } 2949 2950 private final class DreamReceiver extends BroadcastReceiver { 2951 @Override 2952 public void onReceive(Context context, Intent intent) { 2953 synchronized (mLock) { 2954 scheduleSandmanLocked(); 2955 } 2956 } 2957 } 2958 2959 private final class UserSwitchedReceiver extends BroadcastReceiver { 2960 @Override 2961 public void onReceive(Context context, Intent intent) { 2962 synchronized (mLock) { 2963 handleSettingsChangedLocked(); 2964 } 2965 } 2966 } 2967 2968 private final class DockReceiver extends BroadcastReceiver { 2969 @Override 2970 public void onReceive(Context context, Intent intent) { 2971 synchronized (mLock) { 2972 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2973 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2974 if (mDockState != dockState) { 2975 mDockState = dockState; 2976 mDirty |= DIRTY_DOCK_STATE; 2977 updatePowerStateLocked(); 2978 } 2979 } 2980 } 2981 } 2982 2983 private final class SettingsObserver extends ContentObserver { 2984 public SettingsObserver(Handler handler) { 2985 super(handler); 2986 } 2987 2988 @Override 2989 public void onChange(boolean selfChange, Uri uri) { 2990 synchronized (mLock) { 2991 handleSettingsChangedLocked(); 2992 } 2993 } 2994 } 2995 2996 private final VrStateListener mVrStateListener = new VrStateListener() { 2997 @Override 2998 public void onVrStateChanged(boolean enabled) { 2999 powerHintInternal(POWER_HINT_VR_MODE, enabled ? 1 : 0); 3000 } 3001 }; 3002 3003 /** 3004 * Handler for asynchronous operations performed by the power manager. 3005 */ 3006 private final class PowerManagerHandler extends Handler { 3007 public PowerManagerHandler(Looper looper) { 3008 super(looper, null, true /*async*/); 3009 } 3010 3011 @Override 3012 public void handleMessage(Message msg) { 3013 switch (msg.what) { 3014 case MSG_USER_ACTIVITY_TIMEOUT: 3015 handleUserActivityTimeout(); 3016 break; 3017 case MSG_SANDMAN: 3018 handleSandman(); 3019 break; 3020 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT: 3021 handleScreenBrightnessBoostTimeout(); 3022 break; 3023 } 3024 } 3025 } 3026 3027 /** 3028 * Represents a wake lock that has been acquired by an application. 3029 */ 3030 private final class WakeLock implements IBinder.DeathRecipient { 3031 public final IBinder mLock; 3032 public int mFlags; 3033 public String mTag; 3034 public final String mPackageName; 3035 public WorkSource mWorkSource; 3036 public String mHistoryTag; 3037 public final int mOwnerUid; 3038 public final int mOwnerPid; 3039 public boolean mNotifiedAcquired; 3040 public boolean mDisabled; 3041 3042 public WakeLock(IBinder lock, int flags, String tag, String packageName, 3043 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 3044 mLock = lock; 3045 mFlags = flags; 3046 mTag = tag; 3047 mPackageName = packageName; 3048 mWorkSource = copyWorkSource(workSource); 3049 mHistoryTag = historyTag; 3050 mOwnerUid = ownerUid; 3051 mOwnerPid = ownerPid; 3052 } 3053 3054 @Override 3055 public void binderDied() { 3056 PowerManagerService.this.handleWakeLockDeath(this); 3057 } 3058 3059 public boolean hasSameProperties(int flags, String tag, WorkSource workSource, 3060 int ownerUid, int ownerPid) { 3061 return mFlags == flags 3062 && mTag.equals(tag) 3063 && hasSameWorkSource(workSource) 3064 && mOwnerUid == ownerUid 3065 && mOwnerPid == ownerPid; 3066 } 3067 3068 public void updateProperties(int flags, String tag, String packageName, 3069 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) { 3070 if (!mPackageName.equals(packageName)) { 3071 throw new IllegalStateException("Existing wake lock package name changed: " 3072 + mPackageName + " to " + packageName); 3073 } 3074 if (mOwnerUid != ownerUid) { 3075 throw new IllegalStateException("Existing wake lock uid changed: " 3076 + mOwnerUid + " to " + ownerUid); 3077 } 3078 if (mOwnerPid != ownerPid) { 3079 throw new IllegalStateException("Existing wake lock pid changed: " 3080 + mOwnerPid + " to " + ownerPid); 3081 } 3082 mFlags = flags; 3083 mTag = tag; 3084 updateWorkSource(workSource); 3085 mHistoryTag = historyTag; 3086 } 3087 3088 public boolean hasSameWorkSource(WorkSource workSource) { 3089 return Objects.equal(mWorkSource, workSource); 3090 } 3091 3092 public void updateWorkSource(WorkSource workSource) { 3093 mWorkSource = copyWorkSource(workSource); 3094 } 3095 3096 @Override 3097 public String toString() { 3098 return getLockLevelString() 3099 + " '" + mTag + "'" + getLockFlagsString() + (mDisabled ? " DISABLED" : "") 3100 + " (uid=" + mOwnerUid + ", pid=" + mOwnerPid + ", ws=" + mWorkSource + ")"; 3101 } 3102 3103 @SuppressWarnings("deprecation") 3104 private String getLockLevelString() { 3105 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) { 3106 case PowerManager.FULL_WAKE_LOCK: 3107 return "FULL_WAKE_LOCK "; 3108 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 3109 return "SCREEN_BRIGHT_WAKE_LOCK "; 3110 case PowerManager.SCREEN_DIM_WAKE_LOCK: 3111 return "SCREEN_DIM_WAKE_LOCK "; 3112 case PowerManager.PARTIAL_WAKE_LOCK: 3113 return "PARTIAL_WAKE_LOCK "; 3114 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 3115 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 3116 case PowerManager.DOZE_WAKE_LOCK: 3117 return "DOZE_WAKE_LOCK "; 3118 case PowerManager.DRAW_WAKE_LOCK: 3119 return "DRAW_WAKE_LOCK "; 3120 default: 3121 return "??? "; 3122 } 3123 } 3124 3125 private String getLockFlagsString() { 3126 String result = ""; 3127 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 3128 result += " ACQUIRE_CAUSES_WAKEUP"; 3129 } 3130 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) { 3131 result += " ON_AFTER_RELEASE"; 3132 } 3133 return result; 3134 } 3135 } 3136 3137 private final class SuspendBlockerImpl implements SuspendBlocker { 3138 private final String mName; 3139 private final String mTraceName; 3140 private int mReferenceCount; 3141 3142 public SuspendBlockerImpl(String name) { 3143 mName = name; 3144 mTraceName = "SuspendBlocker (" + name + ")"; 3145 } 3146 3147 @Override 3148 protected void finalize() throws Throwable { 3149 try { 3150 if (mReferenceCount != 0) { 3151 Slog.wtf(TAG, "Suspend blocker \"" + mName 3152 + "\" was finalized without being released!"); 3153 mReferenceCount = 0; 3154 nativeReleaseSuspendBlocker(mName); 3155 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 3156 } 3157 } finally { 3158 super.finalize(); 3159 } 3160 } 3161 3162 @Override 3163 public void acquire() { 3164 synchronized (this) { 3165 mReferenceCount += 1; 3166 if (mReferenceCount == 1) { 3167 if (DEBUG_SPEW) { 3168 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\"."); 3169 } 3170 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0); 3171 nativeAcquireSuspendBlocker(mName); 3172 } 3173 } 3174 } 3175 3176 @Override 3177 public void release() { 3178 synchronized (this) { 3179 mReferenceCount -= 1; 3180 if (mReferenceCount == 0) { 3181 if (DEBUG_SPEW) { 3182 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\"."); 3183 } 3184 nativeReleaseSuspendBlocker(mName); 3185 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0); 3186 } else if (mReferenceCount < 0) { 3187 Slog.wtf(TAG, "Suspend blocker \"" + mName 3188 + "\" was released without being acquired!", new Throwable()); 3189 mReferenceCount = 0; 3190 } 3191 } 3192 } 3193 3194 @Override 3195 public String toString() { 3196 synchronized (this) { 3197 return mName + ": ref count=" + mReferenceCount; 3198 } 3199 } 3200 } 3201 3202 private final class BinderService extends IPowerManager.Stub { 3203 @Override // Binder call 3204 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag, 3205 String packageName, int uid) { 3206 if (uid < 0) { 3207 uid = Binder.getCallingUid(); 3208 } 3209 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null); 3210 } 3211 3212 @Override // Binder call 3213 public void powerHint(int hintId, int data) { 3214 if (!mSystemReady) { 3215 // Service not ready yet, so who the heck cares about power hints, bah. 3216 return; 3217 } 3218 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 3219 powerHintInternal(hintId, data); 3220 } 3221 3222 @Override // Binder call 3223 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName, 3224 WorkSource ws, String historyTag) { 3225 if (lock == null) { 3226 throw new IllegalArgumentException("lock must not be null"); 3227 } 3228 if (packageName == null) { 3229 throw new IllegalArgumentException("packageName must not be null"); 3230 } 3231 PowerManager.validateWakeLockParameters(flags, tag); 3232 3233 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3234 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) { 3235 mContext.enforceCallingOrSelfPermission( 3236 android.Manifest.permission.DEVICE_POWER, null); 3237 } 3238 if (ws != null && ws.size() != 0) { 3239 mContext.enforceCallingOrSelfPermission( 3240 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 3241 } else { 3242 ws = null; 3243 } 3244 3245 final int uid = Binder.getCallingUid(); 3246 final int pid = Binder.getCallingPid(); 3247 final long ident = Binder.clearCallingIdentity(); 3248 try { 3249 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid); 3250 } finally { 3251 Binder.restoreCallingIdentity(ident); 3252 } 3253 } 3254 3255 @Override // Binder call 3256 public void releaseWakeLock(IBinder lock, int flags) { 3257 if (lock == null) { 3258 throw new IllegalArgumentException("lock must not be null"); 3259 } 3260 3261 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3262 3263 final long ident = Binder.clearCallingIdentity(); 3264 try { 3265 releaseWakeLockInternal(lock, flags); 3266 } finally { 3267 Binder.restoreCallingIdentity(ident); 3268 } 3269 } 3270 3271 @Override // Binder call 3272 public void updateWakeLockUids(IBinder lock, int[] uids) { 3273 WorkSource ws = null; 3274 3275 if (uids != null) { 3276 ws = new WorkSource(); 3277 // XXX should WorkSource have a way to set uids as an int[] instead of adding them 3278 // one at a time? 3279 for (int i = 0; i < uids.length; i++) { 3280 ws.add(uids[i]); 3281 } 3282 } 3283 updateWakeLockWorkSource(lock, ws, null); 3284 } 3285 3286 @Override // Binder call 3287 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) { 3288 if (lock == null) { 3289 throw new IllegalArgumentException("lock must not be null"); 3290 } 3291 3292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 3293 if (ws != null && ws.size() != 0) { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.UPDATE_DEVICE_STATS, null); 3296 } else { 3297 ws = null; 3298 } 3299 3300 final int callingUid = Binder.getCallingUid(); 3301 final long ident = Binder.clearCallingIdentity(); 3302 try { 3303 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid); 3304 } finally { 3305 Binder.restoreCallingIdentity(ident); 3306 } 3307 } 3308 3309 @Override // Binder call 3310 public boolean isWakeLockLevelSupported(int level) { 3311 final long ident = Binder.clearCallingIdentity(); 3312 try { 3313 return isWakeLockLevelSupportedInternal(level); 3314 } finally { 3315 Binder.restoreCallingIdentity(ident); 3316 } 3317 } 3318 3319 @Override // Binder call 3320 public void userActivity(long eventTime, int event, int flags) { 3321 final long now = SystemClock.uptimeMillis(); 3322 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 3323 != PackageManager.PERMISSION_GRANTED 3324 && mContext.checkCallingOrSelfPermission( 3325 android.Manifest.permission.USER_ACTIVITY) 3326 != PackageManager.PERMISSION_GRANTED) { 3327 // Once upon a time applications could call userActivity(). 3328 // Now we require the DEVICE_POWER permission. Log a warning and ignore the 3329 // request instead of throwing a SecurityException so we don't break old apps. 3330 synchronized (mLock) { 3331 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) { 3332 mLastWarningAboutUserActivityPermission = now; 3333 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the " 3334 + "caller does not have DEVICE_POWER or USER_ACTIVITY " 3335 + "permission. Please fix your app! " 3336 + " pid=" + Binder.getCallingPid() 3337 + " uid=" + Binder.getCallingUid()); 3338 } 3339 } 3340 return; 3341 } 3342 3343 if (eventTime > now) { 3344 throw new IllegalArgumentException("event time must not be in the future"); 3345 } 3346 3347 final int uid = Binder.getCallingUid(); 3348 final long ident = Binder.clearCallingIdentity(); 3349 try { 3350 userActivityInternal(eventTime, event, flags, uid); 3351 } finally { 3352 Binder.restoreCallingIdentity(ident); 3353 } 3354 } 3355 3356 @Override // Binder call 3357 public void wakeUp(long eventTime, String reason, String opPackageName) { 3358 if (eventTime > SystemClock.uptimeMillis()) { 3359 throw new IllegalArgumentException("event time must not be in the future"); 3360 } 3361 3362 mContext.enforceCallingOrSelfPermission( 3363 android.Manifest.permission.DEVICE_POWER, null); 3364 3365 final int uid = Binder.getCallingUid(); 3366 final long ident = Binder.clearCallingIdentity(); 3367 try { 3368 wakeUpInternal(eventTime, reason, uid, opPackageName, uid); 3369 } finally { 3370 Binder.restoreCallingIdentity(ident); 3371 } 3372 } 3373 3374 @Override // Binder call 3375 public void goToSleep(long eventTime, int reason, int flags) { 3376 if (eventTime > SystemClock.uptimeMillis()) { 3377 throw new IllegalArgumentException("event time must not be in the future"); 3378 } 3379 3380 mContext.enforceCallingOrSelfPermission( 3381 android.Manifest.permission.DEVICE_POWER, null); 3382 3383 final int uid = Binder.getCallingUid(); 3384 final long ident = Binder.clearCallingIdentity(); 3385 try { 3386 goToSleepInternal(eventTime, reason, flags, uid); 3387 } finally { 3388 Binder.restoreCallingIdentity(ident); 3389 } 3390 } 3391 3392 @Override // Binder call 3393 public void nap(long eventTime) { 3394 if (eventTime > SystemClock.uptimeMillis()) { 3395 throw new IllegalArgumentException("event time must not be in the future"); 3396 } 3397 3398 mContext.enforceCallingOrSelfPermission( 3399 android.Manifest.permission.DEVICE_POWER, null); 3400 3401 final int uid = Binder.getCallingUid(); 3402 final long ident = Binder.clearCallingIdentity(); 3403 try { 3404 napInternal(eventTime, uid); 3405 } finally { 3406 Binder.restoreCallingIdentity(ident); 3407 } 3408 } 3409 3410 @Override // Binder call 3411 public boolean isInteractive() { 3412 final long ident = Binder.clearCallingIdentity(); 3413 try { 3414 return isInteractiveInternal(); 3415 } finally { 3416 Binder.restoreCallingIdentity(ident); 3417 } 3418 } 3419 3420 @Override // Binder call 3421 public boolean isPowerSaveMode() { 3422 final long ident = Binder.clearCallingIdentity(); 3423 try { 3424 return isLowPowerModeInternal(); 3425 } finally { 3426 Binder.restoreCallingIdentity(ident); 3427 } 3428 } 3429 3430 @Override // Binder call 3431 public boolean setPowerSaveMode(boolean mode) { 3432 mContext.enforceCallingOrSelfPermission( 3433 android.Manifest.permission.DEVICE_POWER, null); 3434 final long ident = Binder.clearCallingIdentity(); 3435 try { 3436 return setLowPowerModeInternal(mode); 3437 } finally { 3438 Binder.restoreCallingIdentity(ident); 3439 } 3440 } 3441 3442 @Override // Binder call 3443 public boolean isDeviceIdleMode() { 3444 final long ident = Binder.clearCallingIdentity(); 3445 try { 3446 return isDeviceIdleModeInternal(); 3447 } finally { 3448 Binder.restoreCallingIdentity(ident); 3449 } 3450 } 3451 3452 @Override // Binder call 3453 public boolean isLightDeviceIdleMode() { 3454 final long ident = Binder.clearCallingIdentity(); 3455 try { 3456 return isLightDeviceIdleModeInternal(); 3457 } finally { 3458 Binder.restoreCallingIdentity(ident); 3459 } 3460 } 3461 3462 /** 3463 * Reboots the device. 3464 * 3465 * @param confirm If true, shows a reboot confirmation dialog. 3466 * @param reason The reason for the reboot, or null if none. 3467 * @param wait If true, this call waits for the reboot to complete and does not return. 3468 */ 3469 @Override // Binder call 3470 public void reboot(boolean confirm, String reason, boolean wait) { 3471 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3472 if (PowerManager.REBOOT_RECOVERY.equals(reason) 3473 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) { 3474 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null); 3475 } 3476 3477 final long ident = Binder.clearCallingIdentity(); 3478 try { 3479 shutdownOrRebootInternal(false, confirm, reason, wait); 3480 } finally { 3481 Binder.restoreCallingIdentity(ident); 3482 } 3483 } 3484 3485 /** 3486 * Shuts down the device. 3487 * 3488 * @param confirm If true, shows a shutdown confirmation dialog. 3489 * @param wait If true, this call waits for the shutdown to complete and does not return. 3490 */ 3491 @Override // Binder call 3492 public void shutdown(boolean confirm, String reason, boolean wait) { 3493 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3494 3495 final long ident = Binder.clearCallingIdentity(); 3496 try { 3497 shutdownOrRebootInternal(true, confirm, reason, wait); 3498 } finally { 3499 Binder.restoreCallingIdentity(ident); 3500 } 3501 } 3502 3503 /** 3504 * Crash the runtime (causing a complete restart of the Android framework). 3505 * Requires REBOOT permission. Mostly for testing. Should not return. 3506 */ 3507 @Override // Binder call 3508 public void crash(String message) { 3509 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 3510 3511 final long ident = Binder.clearCallingIdentity(); 3512 try { 3513 crashInternal(message); 3514 } finally { 3515 Binder.restoreCallingIdentity(ident); 3516 } 3517 } 3518 3519 /** 3520 * Set the setting that determines whether the device stays on when plugged in. 3521 * The argument is a bit string, with each bit specifying a power source that, 3522 * when the device is connected to that source, causes the device to stay on. 3523 * See {@link android.os.BatteryManager} for the list of power sources that 3524 * can be specified. Current values include 3525 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 3526 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 3527 * 3528 * Used by "adb shell svc power stayon ..." 3529 * 3530 * @param val an {@code int} containing the bits that specify which power sources 3531 * should cause the device to stay on. 3532 */ 3533 @Override // Binder call 3534 public void setStayOnSetting(int val) { 3535 int uid = Binder.getCallingUid(); 3536 // if uid is of root's, we permit this operation straight away 3537 if (uid != Process.ROOT_UID) { 3538 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 3539 Settings.getPackageNameForUid(mContext, uid), true)) { 3540 return; 3541 } 3542 } 3543 3544 final long ident = Binder.clearCallingIdentity(); 3545 try { 3546 setStayOnSettingInternal(val); 3547 } finally { 3548 Binder.restoreCallingIdentity(ident); 3549 } 3550 } 3551 3552 /** 3553 * Used by the settings application and brightness control widgets to 3554 * temporarily override the current screen brightness setting so that the 3555 * user can observe the effect of an intended settings change without applying 3556 * it immediately. 3557 * 3558 * The override will be canceled when the setting value is next updated. 3559 * 3560 * @param brightness The overridden brightness. 3561 * 3562 * @see android.provider.Settings.System#SCREEN_BRIGHTNESS 3563 */ 3564 @Override // Binder call 3565 public void setTemporaryScreenBrightnessSettingOverride(int brightness) { 3566 mContext.enforceCallingOrSelfPermission( 3567 android.Manifest.permission.DEVICE_POWER, null); 3568 3569 final long ident = Binder.clearCallingIdentity(); 3570 try { 3571 setTemporaryScreenBrightnessSettingOverrideInternal(brightness); 3572 } finally { 3573 Binder.restoreCallingIdentity(ident); 3574 } 3575 } 3576 3577 /** 3578 * Used by the settings application and brightness control widgets to 3579 * temporarily override the current screen auto-brightness adjustment setting so that the 3580 * user can observe the effect of an intended settings change without applying 3581 * it immediately. 3582 * 3583 * The override will be canceled when the setting value is next updated. 3584 * 3585 * @param adj The overridden brightness, or Float.NaN to disable the override. 3586 * 3587 * @see android.provider.Settings.System#SCREEN_AUTO_BRIGHTNESS_ADJ 3588 */ 3589 @Override // Binder call 3590 public void setTemporaryScreenAutoBrightnessAdjustmentSettingOverride(float adj) { 3591 mContext.enforceCallingOrSelfPermission( 3592 android.Manifest.permission.DEVICE_POWER, null); 3593 3594 final long ident = Binder.clearCallingIdentity(); 3595 try { 3596 setTemporaryScreenAutoBrightnessAdjustmentSettingOverrideInternal(adj); 3597 } finally { 3598 Binder.restoreCallingIdentity(ident); 3599 } 3600 } 3601 3602 /** 3603 * Used by the phone application to make the attention LED flash when ringing. 3604 */ 3605 @Override // Binder call 3606 public void setAttentionLight(boolean on, int color) { 3607 mContext.enforceCallingOrSelfPermission( 3608 android.Manifest.permission.DEVICE_POWER, null); 3609 3610 final long ident = Binder.clearCallingIdentity(); 3611 try { 3612 setAttentionLightInternal(on, color); 3613 } finally { 3614 Binder.restoreCallingIdentity(ident); 3615 } 3616 } 3617 3618 @Override // Binder call 3619 public void boostScreenBrightness(long eventTime) { 3620 if (eventTime > SystemClock.uptimeMillis()) { 3621 throw new IllegalArgumentException("event time must not be in the future"); 3622 } 3623 3624 mContext.enforceCallingOrSelfPermission( 3625 android.Manifest.permission.DEVICE_POWER, null); 3626 3627 final int uid = Binder.getCallingUid(); 3628 final long ident = Binder.clearCallingIdentity(); 3629 try { 3630 boostScreenBrightnessInternal(eventTime, uid); 3631 } finally { 3632 Binder.restoreCallingIdentity(ident); 3633 } 3634 } 3635 3636 @Override // Binder call 3637 public boolean isScreenBrightnessBoosted() { 3638 final long ident = Binder.clearCallingIdentity(); 3639 try { 3640 return isScreenBrightnessBoostedInternal(); 3641 } finally { 3642 Binder.restoreCallingIdentity(ident); 3643 } 3644 } 3645 3646 @Override // Binder call 3647 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3648 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP) 3649 != PackageManager.PERMISSION_GRANTED) { 3650 pw.println("Permission Denial: can't dump PowerManager from from pid=" 3651 + Binder.getCallingPid() 3652 + ", uid=" + Binder.getCallingUid()); 3653 return; 3654 } 3655 3656 final long ident = Binder.clearCallingIdentity(); 3657 try { 3658 dumpInternal(pw); 3659 } finally { 3660 Binder.restoreCallingIdentity(ident); 3661 } 3662 } 3663 } 3664 3665 private final class LocalService extends PowerManagerInternal { 3666 @Override 3667 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) { 3668 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3669 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3670 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3671 } 3672 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness); 3673 } 3674 3675 @Override 3676 public void setButtonBrightnessOverrideFromWindowManager(int screenBrightness) { 3677 // Do nothing. 3678 // Button lights are not currently supported in the new implementation. 3679 } 3680 3681 @Override 3682 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) { 3683 switch (screenState) { 3684 case Display.STATE_UNKNOWN: 3685 case Display.STATE_OFF: 3686 case Display.STATE_DOZE: 3687 case Display.STATE_DOZE_SUSPEND: 3688 case Display.STATE_ON: 3689 break; 3690 default: 3691 screenState = Display.STATE_UNKNOWN; 3692 break; 3693 } 3694 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT 3695 || screenBrightness > PowerManager.BRIGHTNESS_ON) { 3696 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT; 3697 } 3698 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness); 3699 } 3700 3701 @Override 3702 public void setUserInactiveOverrideFromWindowManager() { 3703 setUserInactiveOverrideFromWindowManagerInternal(); 3704 } 3705 3706 @Override 3707 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) { 3708 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis); 3709 } 3710 3711 @Override 3712 public void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { 3713 setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); 3714 } 3715 3716 @Override 3717 public boolean getLowPowerModeEnabled() { 3718 synchronized (mLock) { 3719 return mLowPowerModeEnabled; 3720 } 3721 } 3722 3723 @Override 3724 public void registerLowPowerModeObserver(LowPowerModeListener listener) { 3725 synchronized (mLock) { 3726 mLowPowerModeListeners.add(listener); 3727 } 3728 } 3729 3730 @Override 3731 public boolean setDeviceIdleMode(boolean enabled) { 3732 return setDeviceIdleModeInternal(enabled); 3733 } 3734 3735 @Override 3736 public boolean setLightDeviceIdleMode(boolean enabled) { 3737 return setLightDeviceIdleModeInternal(enabled); 3738 } 3739 3740 @Override 3741 public void setDeviceIdleWhitelist(int[] appids) { 3742 setDeviceIdleWhitelistInternal(appids); 3743 } 3744 3745 @Override 3746 public void setDeviceIdleTempWhitelist(int[] appids) { 3747 setDeviceIdleTempWhitelistInternal(appids); 3748 } 3749 3750 @Override 3751 public void updateUidProcState(int uid, int procState) { 3752 updateUidProcStateInternal(uid, procState); 3753 } 3754 3755 @Override 3756 public void uidGone(int uid) { 3757 uidGoneInternal(uid); 3758 } 3759 3760 @Override 3761 public void powerHint(int hintId, int data) { 3762 powerHintInternal(hintId, data); 3763 } 3764 } 3765} 3766