PowerManagerService.java revision b9ba2b6768063b4a4135143bc5b6219fb9b3b22f
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.power; 18 19import com.android.internal.app.IBatteryStats; 20import com.android.server.BatteryService; 21import com.android.server.EventLogTags; 22import com.android.server.LightsService; 23import com.android.server.Watchdog; 24import com.android.server.am.BatteryStatsService; 25import com.android.server.display.DisplayManagerService; 26 27import android.app.ActivityManagerNative; 28import android.app.IActivityManager; 29import android.content.BroadcastReceiver; 30import android.content.ContentQueryMap; 31import android.content.ContentResolver; 32import android.content.ContentValues; 33import android.content.Context; 34import android.content.Intent; 35import android.content.IntentFilter; 36import android.content.pm.PackageManager; 37import android.content.res.Resources; 38import android.database.ContentObserver; 39import android.database.Cursor; 40import android.hardware.Sensor; 41import android.hardware.SensorEvent; 42import android.hardware.SensorEventListener; 43import android.hardware.SensorManager; 44import android.hardware.SystemSensorManager; 45import android.os.BatteryManager; 46import android.os.BatteryStats; 47import android.os.Binder; 48import android.os.Handler; 49import android.os.HandlerThread; 50import android.os.IBinder; 51import android.os.IPowerManager; 52import android.os.LocalPowerManager; 53import android.os.Message; 54import android.os.PowerManager; 55import android.os.Process; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.os.WorkSource; 60import android.provider.Settings; 61import android.util.EventLog; 62import android.util.Log; 63import android.util.Slog; 64import android.view.WindowManagerPolicy; 65import static android.view.WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR; 66import static android.provider.Settings.System.DIM_SCREEN; 67import static android.provider.Settings.System.SCREEN_BRIGHTNESS; 68import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE; 69import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; 70import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT; 71import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN; 72import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE; 73import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE; 74 75import java.io.FileDescriptor; 76import java.io.IOException; 77import java.io.PrintWriter; 78import java.util.ArrayList; 79import java.util.HashMap; 80import java.util.Observable; 81import java.util.Observer; 82 83public class PowerManagerService extends IPowerManager.Stub 84 implements LocalPowerManager, Watchdog.Monitor { 85 private static final int NOMINAL_FRAME_TIME_MS = 1000/60; 86 87 private static final String TAG = "PowerManagerService"; 88 static final String PARTIAL_NAME = "PowerManagerService"; 89 90 // could be either static or controllable at runtime 91 private static final boolean DEBUG = false; 92 private static final boolean DEBUG_PROXIMITY_SENSOR = (false || DEBUG); 93 private static final boolean DEBUG_LIGHT_SENSOR = (false || DEBUG); 94 private static final boolean DEBUG_LIGHT_ANIMATION = (false || DEBUG); 95 private static final boolean DEBUG_SCREEN_ON = false; 96 97 // Wake lock that ensures that the CPU is running. The screen might not be on. 98 private static final int PARTIAL_WAKE_LOCK_ID = 1; 99 100 // Wake lock that ensures that the screen is on. 101 private static final int FULL_WAKE_LOCK_ID = 2; 102 103 private static final boolean LOG_PARTIAL_WL = false; 104 105 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK 106 | PowerManager.SCREEN_DIM_WAKE_LOCK 107 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK 108 | PowerManager.FULL_WAKE_LOCK 109 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK; 110 111 // time since last state: time since last event: 112 // The short keylight delay comes from secure settings; this is the default. 113 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec 114 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec 115 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec 116 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec 117 118 // How long to wait to debounce light sensor changes in milliseconds 119 private static final int LIGHT_SENSOR_DELAY = 2000; 120 121 // light sensor events rate in microseconds 122 private static final int LIGHT_SENSOR_RATE = 1000000; 123 124 // Expansion of range of light values when applying scale from light 125 // sensor brightness setting, in the [0..255] brightness range. 126 private static final int LIGHT_SENSOR_RANGE_EXPANSION = 20; 127 128 // Scaling factor of the light sensor brightness setting when applying 129 // it to the final brightness. 130 private static final int LIGHT_SENSOR_OFFSET_SCALE = 8; 131 132 // For debouncing the proximity sensor in milliseconds 133 private static final int PROXIMITY_SENSOR_DELAY = 1000; 134 135 // trigger proximity if distance is less than 5 cm 136 private static final float PROXIMITY_THRESHOLD = 5.0f; 137 138 // Cached secure settings; see updateSettingsValues() 139 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT; 140 141 // Default timeout for screen off, if not found in settings database = 15 seconds. 142 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000; 143 144 // Screen brightness should always have a value, but just in case... 145 private static final int DEFAULT_SCREEN_BRIGHTNESS = 192; 146 147 // Threshold for BRIGHTNESS_LOW_BATTERY (percentage) 148 // Screen will stay dim if battery level is <= LOW_BATTERY_THRESHOLD 149 private static final int LOW_BATTERY_THRESHOLD = 10; 150 151 // flags for setPowerState 152 private static final int ALL_LIGHTS_OFF = 0x00000000; 153 private static final int SCREEN_ON_BIT = 0x00000001; 154 private static final int SCREEN_BRIGHT_BIT = 0x00000002; 155 private static final int BUTTON_BRIGHT_BIT = 0x00000004; 156 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008; 157 private static final int BATTERY_LOW_BIT = 0x00000010; 158 159 // values for setPowerState 160 161 // SCREEN_OFF == everything off 162 private static final int SCREEN_OFF = 0x00000000; 163 164 // SCREEN_DIM == screen on, screen backlight dim 165 private static final int SCREEN_DIM = SCREEN_ON_BIT; 166 167 // SCREEN_BRIGHT == screen on, screen backlight bright 168 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT; 169 170 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright 171 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT; 172 173 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright 174 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT; 175 176 // used for noChangeLights in setPowerState() 177 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT; 178 179 // animate screen lights in PowerManager (as opposed to SurfaceFlinger) 180 boolean mAnimateScreenLights = true; 181 182 static final int ANIM_STEPS = 60; // nominal # of frames at 60Hz 183 // Slower animation for autobrightness changes 184 static final int AUTOBRIGHTNESS_ANIM_STEPS = 2 * ANIM_STEPS; 185 // Even slower animation for autodimness changes. Set to max to effectively disable dimming. 186 // Note 100 is used to keep the mWindowScaleAnimation scaling below from overflowing an int. 187 static final int AUTODIMNESS_ANIM_STEPS = Integer.MAX_VALUE / (NOMINAL_FRAME_TIME_MS * 100); 188 // Number of steps when performing a more immediate brightness change. 189 static final int IMMEDIATE_ANIM_STEPS = 4; 190 191 // These magic numbers are the initial state of the LEDs at boot. Ideally 192 // we should read them from the driver, but our current hardware returns 0 193 // for the initial value. Oops! 194 static final int INITIAL_SCREEN_BRIGHTNESS = 255; 195 static final int INITIAL_BUTTON_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF; 196 static final int INITIAL_KEYBOARD_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF; 197 198 private final int MY_UID; 199 private final int MY_PID; 200 201 private boolean mDoneBooting = false; 202 private boolean mBootCompleted = false; 203 private boolean mHeadless = false; 204 private int mStayOnConditions = 0; 205 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 }; 206 private final int[] mBroadcastWhy = new int[3]; 207 private boolean mPreparingForScreenOn = false; 208 private boolean mSkippedScreenOn = false; 209 private boolean mInitialized = false; 210 private int mPartialCount = 0; 211 private int mPowerState; 212 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER, 213 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR 214 private int mScreenOffReason; 215 private int mUserState; 216 private boolean mKeyboardVisible = false; 217 private boolean mUserActivityAllowed = true; 218 private int mProximityWakeLockCount = 0; 219 private boolean mProximitySensorEnabled = false; 220 private boolean mProximitySensorActive = false; 221 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active 222 private long mLastProximityEventTime; 223 private int mScreenOffTimeoutSetting; 224 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE; 225 private int mKeylightDelay; 226 private int mDimDelay; 227 private int mScreenOffDelay; 228 private int mWakeLockState; 229 private long mLastEventTime = 0; 230 private long mScreenOffTime; 231 private volatile WindowManagerPolicy mPolicy; 232 private final LockList mLocks = new LockList(); 233 private Intent mScreenOffIntent; 234 private Intent mScreenOnIntent; 235 private LightsService mLightsService; 236 private Context mContext; 237 private LightsService.Light mLcdLight; 238 private LightsService.Light mButtonLight; 239 private LightsService.Light mKeyboardLight; 240 private LightsService.Light mAttentionLight; 241 private UnsynchronizedWakeLock mBroadcastWakeLock; 242 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock; 243 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock; 244 private UnsynchronizedWakeLock mPreventScreenOnPartialLock; 245 private UnsynchronizedWakeLock mProximityPartialLock; 246 private HandlerThread mHandlerThread; 247 private Handler mScreenOffHandler; 248 private Handler mScreenBrightnessHandler; 249 private Handler mHandler; 250 private final TimeoutTask mTimeoutTask = new TimeoutTask(); 251 private ScreenBrightnessAnimator mScreenBrightnessAnimator; 252 private boolean mWaitingForFirstLightSensor = false; 253 private boolean mStillNeedSleepNotification; 254 private boolean mIsPowered = false; 255 private IActivityManager mActivityService; 256 private IBatteryStats mBatteryStats; 257 private BatteryService mBatteryService; 258 private DisplayManagerService mDisplayManagerService; 259 private SensorManager mSensorManager; 260 private Sensor mProximitySensor; 261 private Sensor mLightSensor; 262 private boolean mLightSensorEnabled; 263 private float mLightSensorValue = -1; 264 private boolean mProxIgnoredBecauseScreenTurnedOff = false; 265 private int mHighestLightSensorValue = -1; 266 private boolean mLightSensorPendingDecrease = false; 267 private boolean mLightSensorPendingIncrease = false; 268 private float mLightSensorPendingValue = -1; 269 private float mLightSensorAdjustSetting = 0; 270 private int mLightSensorScreenBrightness = -1; 271 private int mLightSensorButtonBrightness = -1; 272 private int mLightSensorKeyboardBrightness = -1; 273 private boolean mDimScreen = true; 274 private boolean mIsDocked = false; 275 private long mNextTimeout; 276 private volatile int mPokey = 0; 277 private volatile boolean mPokeAwakeOnSet = false; 278 private volatile boolean mInitComplete = false; 279 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>(); 280 // mLastScreenOnTime is the time the screen was last turned on 281 private long mLastScreenOnTime; 282 private boolean mPreventScreenOn; 283 private int mScreenBrightnessSetting = DEFAULT_SCREEN_BRIGHTNESS; 284 private int mScreenBrightnessOverride = -1; 285 private int mButtonBrightnessOverride = -1; 286 private int mScreenBrightnessDim; 287 private boolean mUseSoftwareAutoBrightness; 288 private boolean mAutoBrightessEnabled; 289 private int[] mAutoBrightnessLevels; 290 private int[] mLcdBacklightValues; 291 private int[] mButtonBacklightValues; 292 private int[] mKeyboardBacklightValues; 293 private int mLightSensorWarmupTime; 294 boolean mUnplugTurnsOnScreen; 295 private int mWarningSpewThrottleCount; 296 private long mWarningSpewThrottleTime; 297 private int mAnimationSetting = ANIM_SETTING_OFF; 298 private float mWindowScaleAnimation; 299 300 // Must match with the ISurfaceComposer constants in C++. 301 private static final int ANIM_SETTING_ON = 0x01; 302 private static final int ANIM_SETTING_OFF = 0x10; 303 304 private native void nativeInit(); 305 private native void nativeSetPowerState(boolean screenOn, boolean screenBright); 306 private native void nativeStartSurfaceFlingerAnimation(int mode); 307 private static native void nativeAcquireWakeLock(int lock, String id); 308 private static native void nativeReleaseWakeLock(String id); 309 private static native int nativeSetScreenState(boolean on); 310 private static native void nativeShutdown(); 311 private static native void nativeReboot(String reason) throws IOException; 312 313 /* 314 static PrintStream mLog; 315 static { 316 try { 317 mLog = new PrintStream("/data/power.log"); 318 } 319 catch (FileNotFoundException e) { 320 android.util.Slog.e(TAG, "Life is hard", e); 321 } 322 } 323 static class Log { 324 static void d(String tag, String s) { 325 mLog.println(s); 326 android.util.Slog.d(tag, s); 327 } 328 static void i(String tag, String s) { 329 mLog.println(s); 330 android.util.Slog.i(tag, s); 331 } 332 static void w(String tag, String s) { 333 mLog.println(s); 334 android.util.Slog.w(tag, s); 335 } 336 static void e(String tag, String s) { 337 mLog.println(s); 338 android.util.Slog.e(tag, s); 339 } 340 } 341 */ 342 343 /** 344 * This class works around a deadlock between the lock in PowerManager.WakeLock 345 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its 346 * mToken object so it can be accessed from any thread, but it calls into here 347 * with its lock held. This class is essentially a reimplementation of 348 * PowerManager.WakeLock, but without that extra synchronized block, because we'll 349 * only call it with our own locks held. 350 */ 351 private class UnsynchronizedWakeLock { 352 int mFlags; 353 String mTag; 354 IBinder mToken; 355 int mCount = 0; 356 boolean mRefCounted; 357 boolean mHeld; 358 359 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) { 360 mFlags = flags; 361 mTag = tag; 362 mToken = new Binder(); 363 mRefCounted = refCounted; 364 } 365 366 public void acquire() { 367 if (!mRefCounted || mCount++ == 0) { 368 long ident = Binder.clearCallingIdentity(); 369 try { 370 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken, 371 MY_UID, MY_PID, mTag, null); 372 mHeld = true; 373 } finally { 374 Binder.restoreCallingIdentity(ident); 375 } 376 } 377 } 378 379 public void release() { 380 if (!mRefCounted || --mCount == 0) { 381 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false); 382 mHeld = false; 383 } 384 if (mCount < 0) { 385 throw new RuntimeException("WakeLock under-locked " + mTag); 386 } 387 } 388 389 public boolean isHeld() 390 { 391 return mHeld; 392 } 393 394 public String toString() { 395 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags) 396 + " mCount=" + mCount + " mHeld=" + mHeld + ")"; 397 } 398 } 399 400 private final class BatteryReceiver extends BroadcastReceiver { 401 @Override 402 public void onReceive(Context context, Intent intent) { 403 synchronized (mLocks) { 404 boolean wasPowered = mIsPowered; 405 mIsPowered = mBatteryService.isPowered(); 406 407 if (mIsPowered != wasPowered) { 408 // update mStayOnWhilePluggedIn wake lock 409 updateWakeLockLocked(); 410 411 // treat plugging and unplugging the devices as a user activity. 412 // users find it disconcerting when they unplug the device 413 // and it shuts off right away. 414 // to avoid turning on the screen when unplugging, we only trigger 415 // user activity when screen was already on. 416 // temporarily set mUserActivityAllowed to true so this will work 417 // even when the keyguard is on. 418 // However, you can also set config_unplugTurnsOnScreen to have it 419 // turn on. Some devices want this because they don't have a 420 // charging LED. 421 synchronized (mLocks) { 422 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 || 423 mUnplugTurnsOnScreen) { 424 forceUserActivityLocked(); 425 } 426 } 427 428 // stop the screensaver if we're now unplugged 429 if (mPolicy != null && wasPowered) { 430 mPolicy.stopScreenSaver(); 431 } 432 } 433 } 434 } 435 } 436 437 private final class BootCompletedReceiver extends BroadcastReceiver { 438 @Override 439 public void onReceive(Context context, Intent intent) { 440 bootCompleted(); 441 } 442 } 443 444 private final class DockReceiver extends BroadcastReceiver { 445 @Override 446 public void onReceive(Context context, Intent intent) { 447 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 448 Intent.EXTRA_DOCK_STATE_UNDOCKED); 449 dockStateChanged(state); 450 } 451 } 452 453 /** 454 * Set the setting that determines whether the device stays on when plugged in. 455 * The argument is a bit string, with each bit specifying a power source that, 456 * when the device is connected to that source, causes the device to stay on. 457 * See {@link android.os.BatteryManager} for the list of power sources that 458 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC} 459 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB} 460 * @param val an {@code int} containing the bits that specify which power sources 461 * should cause the device to stay on. 462 */ 463 public void setStayOnSetting(int val) { 464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null); 465 Settings.System.putInt(mContext.getContentResolver(), 466 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val); 467 } 468 469 public void setMaximumScreenOffTimeount(int timeMs) { 470 mContext.enforceCallingOrSelfPermission( 471 android.Manifest.permission.WRITE_SECURE_SETTINGS, null); 472 synchronized (mLocks) { 473 mMaximumScreenOffTimeout = timeMs; 474 // recalculate everything 475 setScreenOffTimeoutsLocked(); 476 } 477 } 478 479 int getStayOnConditionsLocked() { 480 return mMaximumScreenOffTimeout <= 0 || mMaximumScreenOffTimeout == Integer.MAX_VALUE 481 ? mStayOnConditions : 0; 482 } 483 484 private class SettingsObserver implements Observer { 485 private int getInt(String name, int defValue) { 486 ContentValues values = mSettings.getValues(name); 487 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null; 488 return iVal != null ? iVal : defValue; 489 } 490 491 private float getFloat(String name, float defValue) { 492 ContentValues values = mSettings.getValues(name); 493 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null; 494 return fVal != null ? fVal : defValue; 495 } 496 497 public void update(Observable o, Object arg) { 498 synchronized (mLocks) { 499 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC 500 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN, 501 BatteryManager.BATTERY_PLUGGED_AC); 502 updateWakeLockLocked(); 503 504 // SCREEN_OFF_TIMEOUT, default to 15 seconds 505 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT); 506 507 // DIM_SCREEN 508 //mDimScreen = getInt(DIM_SCREEN) != 0; 509 510 mScreenBrightnessSetting = getInt(SCREEN_BRIGHTNESS, DEFAULT_SCREEN_BRIGHTNESS); 511 mLightSensorAdjustSetting = 0; //getFloat(SCREEN_AUTO_BRIGHTNESS_ADJ, 0); 512 513 // SCREEN_BRIGHTNESS_MODE, default to manual 514 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE, 515 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)); 516 517 // recalculate everything 518 setScreenOffTimeoutsLocked(); 519 520 mWindowScaleAnimation = getFloat(WINDOW_ANIMATION_SCALE, 1.0f); 521 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f); 522 mAnimationSetting = 0; 523 if (mWindowScaleAnimation > 0.5f) { 524 mAnimationSetting |= ANIM_SETTING_OFF; 525 } 526 if (transitionScale > 0.5f) { 527 // Uncomment this if you want the screen-on animation. 528 // mAnimationSetting |= ANIM_SETTING_ON; 529 } 530 } 531 } 532 } 533 534 public PowerManagerService() { 535 // Hack to get our uid... should have a func for this. 536 long token = Binder.clearCallingIdentity(); 537 MY_UID = Process.myUid(); 538 MY_PID = Process.myPid(); 539 Binder.restoreCallingIdentity(token); 540 541 // assume nothing is on yet 542 mUserState = mPowerState = 0; 543 544 // Add ourself to the Watchdog monitors. 545 Watchdog.getInstance().addMonitor(this); 546 547 nativeInit(); 548 } 549 550 private ContentQueryMap mSettings; 551 552 public void init(Context context, LightsService lights, IActivityManager activity, 553 BatteryService battery, DisplayManagerService displayManagerService) { 554 mLightsService = lights; 555 mContext = context; 556 mActivityService = activity; 557 mBatteryStats = BatteryStatsService.getService(); 558 mBatteryService = battery; 559 mDisplayManagerService = displayManagerService; 560 561 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT); 562 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS); 563 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD); 564 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION); 565 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0")); 566 567 mInitComplete = false; 568 mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread", 569 Process.THREAD_PRIORITY_DISPLAY); 570 mScreenBrightnessAnimator.start(); 571 572 synchronized (mScreenBrightnessAnimator) { 573 while (!mInitComplete) { 574 try { 575 mScreenBrightnessAnimator.wait(); 576 } catch (InterruptedException e) { 577 // Ignore 578 } 579 } 580 } 581 582 mInitComplete = false; 583 mHandlerThread = new HandlerThread("PowerManagerService") { 584 @Override 585 protected void onLooperPrepared() { 586 super.onLooperPrepared(); 587 initInThread(); 588 } 589 }; 590 mHandlerThread.start(); 591 592 synchronized (mHandlerThread) { 593 while (!mInitComplete) { 594 try { 595 mHandlerThread.wait(); 596 } catch (InterruptedException e) { 597 // Ignore 598 } 599 } 600 } 601 602 synchronized (mLocks) { 603 updateNativePowerStateLocked(); 604 // We make sure to start out with the screen on due to user activity. 605 // (They did just boot their device, after all.) 606 forceUserActivityLocked(); 607 mInitialized = true; 608 } 609 } 610 611 void initInThread() { 612 mHandler = new Handler(); 613 614 mBroadcastWakeLock = new UnsynchronizedWakeLock( 615 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true); 616 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock( 617 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false); 618 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock( 619 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false); 620 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock( 621 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false); 622 mProximityPartialLock = new UnsynchronizedWakeLock( 623 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false); 624 625 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON); 626 mScreenOnIntent.addFlags( 627 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); 628 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF); 629 mScreenOffIntent.addFlags( 630 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); 631 632 Resources resources = mContext.getResources(); 633 634 mAnimateScreenLights = resources.getBoolean( 635 com.android.internal.R.bool.config_animateScreenLights); 636 637 mUnplugTurnsOnScreen = resources.getBoolean( 638 com.android.internal.R.bool.config_unplugTurnsOnScreen); 639 640 mScreenBrightnessDim = resources.getInteger( 641 com.android.internal.R.integer.config_screenBrightnessDim); 642 643 // read settings for auto-brightness 644 mUseSoftwareAutoBrightness = resources.getBoolean( 645 com.android.internal.R.bool.config_automatic_brightness_available); 646 if (mUseSoftwareAutoBrightness) { 647 mAutoBrightnessLevels = resources.getIntArray( 648 com.android.internal.R.array.config_autoBrightnessLevels); 649 mLcdBacklightValues = resources.getIntArray( 650 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues); 651 mButtonBacklightValues = resources.getIntArray( 652 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues); 653 mKeyboardBacklightValues = resources.getIntArray( 654 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues); 655 mLightSensorWarmupTime = resources.getInteger( 656 com.android.internal.R.integer.config_lightSensorWarmupTime); 657 } 658 659 ContentResolver resolver = mContext.getContentResolver(); 660 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null, 661 "(" + Settings.System.NAME + "=?) or (" 662 + Settings.System.NAME + "=?) or (" 663 + Settings.System.NAME + "=?) or (" 664 + Settings.System.NAME + "=?) or (" 665 + Settings.System.NAME + "=?) or (" 666 + Settings.System.NAME + "=?) or (" 667 + Settings.System.NAME + "=?) or (" 668 + Settings.System.NAME + "=?)", 669 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS, 670 SCREEN_BRIGHTNESS_MODE, /*SCREEN_AUTO_BRIGHTNESS_ADJ,*/ 671 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE}, 672 null); 673 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler); 674 SettingsObserver settingsObserver = new SettingsObserver(); 675 mSettings.addObserver(settingsObserver); 676 677 // pretend that the settings changed so we will get their initial state 678 settingsObserver.update(mSettings, null); 679 680 // register for the battery changed notifications 681 IntentFilter filter = new IntentFilter(); 682 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 683 mContext.registerReceiver(new BatteryReceiver(), filter); 684 filter = new IntentFilter(); 685 filter.addAction(Intent.ACTION_BOOT_COMPLETED); 686 mContext.registerReceiver(new BootCompletedReceiver(), filter); 687 filter = new IntentFilter(); 688 filter.addAction(Intent.ACTION_DOCK_EVENT); 689 mContext.registerReceiver(new DockReceiver(), filter); 690 691 // Listen for secure settings changes 692 mContext.getContentResolver().registerContentObserver( 693 Settings.Secure.CONTENT_URI, true, 694 new ContentObserver(new Handler()) { 695 public void onChange(boolean selfChange) { 696 updateSettingsValues(); 697 } 698 }); 699 updateSettingsValues(); 700 701 synchronized (mHandlerThread) { 702 mInitComplete = true; 703 mHandlerThread.notifyAll(); 704 } 705 } 706 707 /** 708 * Low-level function turn the device off immediately, without trying 709 * to be clean. Most people should use 710 * {@link com.android.server.power.internal.app.ShutdownThread} for a clean shutdown. 711 */ 712 public static void lowLevelShutdown() { 713 nativeShutdown(); 714 } 715 716 /** 717 * Low-level function to reboot the device. 718 * 719 * @param reason code to pass to the kernel (e.g. "recovery"), or null. 720 * @throws IOException if reboot fails for some reason (eg, lack of 721 * permission) 722 */ 723 public static void lowLevelReboot(String reason) throws IOException { 724 nativeReboot(reason); 725 } 726 727 private class WakeLock implements IBinder.DeathRecipient 728 { 729 WakeLock(int f, IBinder b, String t, int u, int p) { 730 super(); 731 flags = f; 732 binder = b; 733 tag = t; 734 uid = u == MY_UID ? Process.SYSTEM_UID : u; 735 pid = p; 736 if (u != MY_UID || ( 737 !"KEEP_SCREEN_ON_FLAG".equals(tag) 738 && !"KeyInputQueue".equals(tag))) { 739 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK 740 ? BatteryStats.WAKE_TYPE_PARTIAL 741 : BatteryStats.WAKE_TYPE_FULL; 742 } else { 743 monitorType = -1; 744 } 745 try { 746 b.linkToDeath(this, 0); 747 } catch (RemoteException e) { 748 binderDied(); 749 } 750 } 751 public void binderDied() { 752 synchronized (mLocks) { 753 releaseWakeLockLocked(this.binder, 0, true); 754 } 755 } 756 final int flags; 757 final IBinder binder; 758 final String tag; 759 final int uid; 760 final int pid; 761 final int monitorType; 762 WorkSource ws; 763 boolean activated = true; 764 int minState; 765 } 766 767 private void updateWakeLockLocked() { 768 final int stayOnConditions = getStayOnConditionsLocked(); 769 if (stayOnConditions != 0 && mBatteryService.isPowered(stayOnConditions)) { 770 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set. 771 mStayOnWhilePluggedInScreenDimLock.acquire(); 772 mStayOnWhilePluggedInPartialLock.acquire(); 773 } else { 774 mStayOnWhilePluggedInScreenDimLock.release(); 775 mStayOnWhilePluggedInPartialLock.release(); 776 } 777 } 778 779 private boolean isScreenLock(int flags) 780 { 781 int n = flags & LOCK_MASK; 782 return n == PowerManager.FULL_WAKE_LOCK 783 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK 784 || n == PowerManager.SCREEN_DIM_WAKE_LOCK 785 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK; 786 } 787 788 void enforceWakeSourcePermission(int uid, int pid) { 789 if (uid == Process.myUid()) { 790 return; 791 } 792 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS, 793 pid, uid, null); 794 } 795 796 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) { 797 int uid = Binder.getCallingUid(); 798 int pid = Binder.getCallingPid(); 799 if (uid != Process.myUid()) { 800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 801 } 802 if (ws != null) { 803 enforceWakeSourcePermission(uid, pid); 804 } 805 long ident = Binder.clearCallingIdentity(); 806 try { 807 synchronized (mLocks) { 808 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws); 809 } 810 } finally { 811 Binder.restoreCallingIdentity(ident); 812 } 813 } 814 815 void noteStartWakeLocked(WakeLock wl, WorkSource ws) { 816 if (wl.monitorType >= 0) { 817 long origId = Binder.clearCallingIdentity(); 818 try { 819 if (ws != null) { 820 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag, 821 wl.monitorType); 822 } else { 823 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType); 824 } 825 } catch (RemoteException e) { 826 // Ignore 827 } finally { 828 Binder.restoreCallingIdentity(origId); 829 } 830 } 831 } 832 833 void noteStopWakeLocked(WakeLock wl, WorkSource ws) { 834 if (wl.monitorType >= 0) { 835 long origId = Binder.clearCallingIdentity(); 836 try { 837 if (ws != null) { 838 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag, 839 wl.monitorType); 840 } else { 841 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType); 842 } 843 } catch (RemoteException e) { 844 // Ignore 845 } finally { 846 Binder.restoreCallingIdentity(origId); 847 } 848 } 849 } 850 851 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag, 852 WorkSource ws) { 853 if (DEBUG) { 854 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag); 855 } 856 857 if (ws != null && ws.size() == 0) { 858 ws = null; 859 } 860 861 int index = mLocks.getIndex(lock); 862 WakeLock wl; 863 boolean newlock; 864 boolean diffsource; 865 WorkSource oldsource; 866 if (index < 0) { 867 wl = new WakeLock(flags, lock, tag, uid, pid); 868 switch (wl.flags & LOCK_MASK) 869 { 870 case PowerManager.FULL_WAKE_LOCK: 871 if (mUseSoftwareAutoBrightness) { 872 wl.minState = SCREEN_BRIGHT; 873 } else { 874 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT); 875 } 876 break; 877 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 878 wl.minState = SCREEN_BRIGHT; 879 break; 880 case PowerManager.SCREEN_DIM_WAKE_LOCK: 881 wl.minState = SCREEN_DIM; 882 break; 883 case PowerManager.PARTIAL_WAKE_LOCK: 884 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 885 break; 886 default: 887 // just log and bail. we're in the server, so don't 888 // throw an exception. 889 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' " 890 + " flags=" + flags); 891 return; 892 } 893 mLocks.addLock(wl); 894 if (ws != null) { 895 wl.ws = new WorkSource(ws); 896 } 897 newlock = true; 898 diffsource = false; 899 oldsource = null; 900 } else { 901 wl = mLocks.get(index); 902 newlock = false; 903 oldsource = wl.ws; 904 if (oldsource != null) { 905 if (ws == null) { 906 wl.ws = null; 907 diffsource = true; 908 } else { 909 diffsource = oldsource.diff(ws); 910 } 911 } else if (ws != null) { 912 diffsource = true; 913 } else { 914 diffsource = false; 915 } 916 if (diffsource) { 917 wl.ws = new WorkSource(ws); 918 } 919 } 920 if (isScreenLock(flags)) { 921 // if this causes a wakeup, we reactivate all of the locks and 922 // set it to whatever they want. otherwise, we modulate that 923 // by the current state so we never turn it more on than 924 // it already is. 925 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) { 926 mProximityWakeLockCount++; 927 if (mProximityWakeLockCount == 1) { 928 enableProximityLockLocked(); 929 } 930 } else { 931 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 932 int oldWakeLockState = mWakeLockState; 933 mWakeLockState = mLocks.reactivateScreenLocksLocked(); 934 935 // Disable proximity sensor if if user presses power key while we are in the 936 // "waiting for proximity sensor to go negative" state. 937 if ((mWakeLockState & SCREEN_ON_BIT) != 0 938 && mProximitySensorActive && mProximityWakeLockCount == 0) { 939 mProximitySensorActive = false; 940 } 941 942 if (DEBUG) { 943 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState) 944 + " mWakeLockState=0x" 945 + Integer.toHexString(mWakeLockState) 946 + " previous wakeLockState=0x" 947 + Integer.toHexString(oldWakeLockState)); 948 } 949 } else { 950 if (DEBUG) { 951 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState) 952 + " mLocks.gatherState()=0x" 953 + Integer.toHexString(mLocks.gatherState()) 954 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)); 955 } 956 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState(); 957 } 958 setPowerState(mWakeLockState | mUserState); 959 } 960 } 961 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) { 962 if (newlock) { 963 mPartialCount++; 964 if (mPartialCount == 1) { 965 if (LOG_PARTIAL_WL) { 966 EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag); 967 } 968 } 969 } 970 nativeAcquireWakeLock(PARTIAL_WAKE_LOCK_ID, PARTIAL_NAME); 971 } 972 973 if (diffsource) { 974 // If the lock sources have changed, need to first release the 975 // old ones. 976 noteStopWakeLocked(wl, oldsource); 977 } 978 if (newlock || diffsource) { 979 noteStartWakeLocked(wl, ws); 980 } 981 } 982 983 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) { 984 int uid = Binder.getCallingUid(); 985 int pid = Binder.getCallingPid(); 986 if (ws != null && ws.size() == 0) { 987 ws = null; 988 } 989 if (ws != null) { 990 enforceWakeSourcePermission(uid, pid); 991 } 992 synchronized (mLocks) { 993 int index = mLocks.getIndex(lock); 994 if (index < 0) { 995 throw new IllegalArgumentException("Wake lock not active"); 996 } 997 WakeLock wl = mLocks.get(index); 998 WorkSource oldsource = wl.ws; 999 wl.ws = ws != null ? new WorkSource(ws) : null; 1000 noteStopWakeLocked(wl, oldsource); 1001 noteStartWakeLocked(wl, ws); 1002 } 1003 } 1004 1005 public void releaseWakeLock(IBinder lock, int flags) { 1006 int uid = Binder.getCallingUid(); 1007 if (uid != Process.myUid()) { 1008 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null); 1009 } 1010 1011 synchronized (mLocks) { 1012 releaseWakeLockLocked(lock, flags, false); 1013 } 1014 } 1015 1016 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) { 1017 WakeLock wl = mLocks.removeLock(lock); 1018 if (wl == null) { 1019 return; 1020 } 1021 1022 if (DEBUG) { 1023 Slog.d(TAG, "releaseWakeLock flags=0x" 1024 + Integer.toHexString(wl.flags) + " tag=" + wl.tag); 1025 } 1026 1027 if (isScreenLock(wl.flags)) { 1028 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) { 1029 mProximityWakeLockCount--; 1030 if (mProximityWakeLockCount == 0) { 1031 if (mProximitySensorActive && 1032 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) { 1033 // wait for proximity sensor to go negative before disabling sensor 1034 if (DEBUG_PROXIMITY_SENSOR) { 1035 Slog.d(TAG, "waiting for proximity sensor to go negative"); 1036 } 1037 } else { 1038 disableProximityLockLocked(); 1039 } 1040 } 1041 } else { 1042 mWakeLockState = mLocks.gatherState(); 1043 // goes in the middle to reduce flicker 1044 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) { 1045 userActivity(SystemClock.uptimeMillis(), -1, false, PowerManager.USER_ACTIVITY_EVENT_OTHER, false, true); 1046 } 1047 setPowerState(mWakeLockState | mUserState); 1048 } 1049 } 1050 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) { 1051 mPartialCount--; 1052 if (mPartialCount == 0) { 1053 if (LOG_PARTIAL_WL) { 1054 EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag); 1055 } 1056 nativeReleaseWakeLock(PARTIAL_NAME); 1057 } 1058 } 1059 // Unlink the lock from the binder. 1060 wl.binder.unlinkToDeath(wl, 0); 1061 1062 noteStopWakeLocked(wl, wl.ws); 1063 } 1064 1065 private class PokeLock implements IBinder.DeathRecipient 1066 { 1067 PokeLock(int p, IBinder b, String t) { 1068 super(); 1069 this.pokey = p; 1070 this.binder = b; 1071 this.tag = t; 1072 try { 1073 b.linkToDeath(this, 0); 1074 } catch (RemoteException e) { 1075 binderDied(); 1076 } 1077 } 1078 public void binderDied() { 1079 setPokeLock(0, this.binder, this.tag); 1080 } 1081 int pokey; 1082 IBinder binder; 1083 String tag; 1084 boolean awakeOnSet; 1085 } 1086 1087 public void setPokeLock(int pokey, IBinder token, String tag) { 1088 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1089 if (token == null) { 1090 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'"); 1091 return; 1092 } 1093 1094 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) { 1095 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT" 1096 + " and POKE_LOCK_MEDIUM_TIMEOUT"); 1097 } 1098 1099 synchronized (mLocks) { 1100 if (pokey != 0) { 1101 PokeLock p = mPokeLocks.get(token); 1102 int oldPokey = 0; 1103 if (p != null) { 1104 oldPokey = p.pokey; 1105 p.pokey = pokey; 1106 } else { 1107 p = new PokeLock(pokey, token, tag); 1108 mPokeLocks.put(token, p); 1109 } 1110 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK; 1111 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK; 1112 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) { 1113 p.awakeOnSet = true; 1114 } 1115 } else { 1116 PokeLock rLock = mPokeLocks.remove(token); 1117 if (rLock != null) { 1118 token.unlinkToDeath(rLock, 0); 1119 } 1120 } 1121 1122 int oldPokey = mPokey; 1123 int cumulative = 0; 1124 boolean awakeOnSet = false; 1125 for (PokeLock p: mPokeLocks.values()) { 1126 cumulative |= p.pokey; 1127 if (p.awakeOnSet) { 1128 awakeOnSet = true; 1129 } 1130 } 1131 mPokey = cumulative; 1132 mPokeAwakeOnSet = awakeOnSet; 1133 1134 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK; 1135 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK; 1136 1137 if (oldCumulativeTimeout != newCumulativeTimeout) { 1138 setScreenOffTimeoutsLocked(); 1139 // reset the countdown timer, but use the existing nextState so it doesn't 1140 // change anything 1141 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState); 1142 } 1143 } 1144 } 1145 1146 private static String lockType(int type) 1147 { 1148 switch (type) 1149 { 1150 case PowerManager.FULL_WAKE_LOCK: 1151 return "FULL_WAKE_LOCK "; 1152 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK: 1153 return "SCREEN_BRIGHT_WAKE_LOCK "; 1154 case PowerManager.SCREEN_DIM_WAKE_LOCK: 1155 return "SCREEN_DIM_WAKE_LOCK "; 1156 case PowerManager.PARTIAL_WAKE_LOCK: 1157 return "PARTIAL_WAKE_LOCK "; 1158 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK: 1159 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK"; 1160 default: 1161 return "??? "; 1162 } 1163 } 1164 1165 private static String dumpPowerState(int state) { 1166 return (((state & KEYBOARD_BRIGHT_BIT) != 0) 1167 ? "KEYBOARD_BRIGHT_BIT " : "") 1168 + (((state & SCREEN_BRIGHT_BIT) != 0) 1169 ? "SCREEN_BRIGHT_BIT " : "") 1170 + (((state & SCREEN_ON_BIT) != 0) 1171 ? "SCREEN_ON_BIT " : "") 1172 + (((state & BUTTON_BRIGHT_BIT) != 0) 1173 ? "BUTTON_BRIGHT_BIT " : "") 1174 + (((state & BATTERY_LOW_BIT) != 0) 1175 ? "BATTERY_LOW_BIT " : ""); 1176 } 1177 1178 @Override 1179 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1180 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1181 != PackageManager.PERMISSION_GRANTED) { 1182 pw.println("Permission Denial: can't dump PowerManager from from pid=" 1183 + Binder.getCallingPid() 1184 + ", uid=" + Binder.getCallingUid()); 1185 return; 1186 } 1187 1188 long now = SystemClock.uptimeMillis(); 1189 1190 synchronized (mLocks) { 1191 pw.println("Power Manager State:"); 1192 pw.println(" mIsPowered=" + mIsPowered 1193 + " mPowerState=" + mPowerState 1194 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime) 1195 + " ms"); 1196 pw.println(" mPartialCount=" + mPartialCount); 1197 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState)); 1198 pw.println(" mUserState=" + dumpPowerState(mUserState)); 1199 pw.println(" mPowerState=" + dumpPowerState(mPowerState)); 1200 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState())); 1201 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now 1202 + " " + ((mNextTimeout-now)/1000) + "s from now"); 1203 pw.println(" mDimScreen=" + mDimScreen 1204 + " mStayOnConditions=" + mStayOnConditions 1205 + " mPreparingForScreenOn=" + mPreparingForScreenOn 1206 + " mSkippedScreenOn=" + mSkippedScreenOn); 1207 pw.println(" mScreenOffReason=" + mScreenOffReason 1208 + " mUserState=" + mUserState); 1209 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1] 1210 + ',' + mBroadcastQueue[2] + "}"); 1211 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1] 1212 + ',' + mBroadcastWhy[2] + "}"); 1213 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet); 1214 pw.println(" mKeyboardVisible=" + mKeyboardVisible 1215 + " mUserActivityAllowed=" + mUserActivityAllowed); 1216 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay 1217 + " mScreenOffDelay=" + mScreenOffDelay); 1218 pw.println(" mPreventScreenOn=" + mPreventScreenOn 1219 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride 1220 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride); 1221 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting 1222 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout); 1223 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime); 1224 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock); 1225 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock); 1226 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock); 1227 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock); 1228 pw.println(" mProximityPartialLock=" + mProximityPartialLock); 1229 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount); 1230 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled); 1231 pw.println(" mProximitySensorActive=" + mProximitySensorActive); 1232 pw.println(" mProximityPendingValue=" + mProximityPendingValue); 1233 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime); 1234 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled 1235 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting); 1236 pw.println(" mLightSensorValue=" + mLightSensorValue 1237 + " mLightSensorPendingValue=" + mLightSensorPendingValue); 1238 pw.println(" mHighestLightSensorValue=" + mHighestLightSensorValue 1239 + " mWaitingForFirstLightSensor=" + mWaitingForFirstLightSensor); 1240 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease 1241 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease); 1242 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness 1243 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness 1244 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness); 1245 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness); 1246 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled); 1247 mScreenBrightnessAnimator.dump(pw, "mScreenBrightnessAnimator: "); 1248 1249 int N = mLocks.size(); 1250 pw.println(); 1251 pw.println("mLocks.size=" + N + ":"); 1252 for (int i=0; i<N; i++) { 1253 WakeLock wl = mLocks.get(i); 1254 String type = lockType(wl.flags & LOCK_MASK); 1255 String acquireCausesWakeup = ""; 1256 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) { 1257 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP "; 1258 } 1259 String activated = ""; 1260 if (wl.activated) { 1261 activated = " activated"; 1262 } 1263 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup 1264 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid 1265 + ", pid=" + wl.pid + ")"); 1266 } 1267 1268 pw.println(); 1269 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":"); 1270 for (PokeLock p: mPokeLocks.values()) { 1271 pw.println(" poke lock '" + p.tag + "':" 1272 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0 1273 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "") 1274 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0 1275 ? " POKE_LOCK_SHORT_TIMEOUT" : "") 1276 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0 1277 ? " POKE_LOCK_MEDIUM_TIMEOUT" : "")); 1278 } 1279 1280 pw.println(); 1281 } 1282 } 1283 1284 private void setTimeoutLocked(long now, int nextState) { 1285 setTimeoutLocked(now, -1, nextState); 1286 } 1287 1288 // If they gave a timeoutOverride it is the number of seconds 1289 // to screen-off. Figure out where in the countdown cycle we 1290 // should jump to. 1291 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) { 1292 long timeoutOverride = originalTimeoutOverride; 1293 if (mBootCompleted) { 1294 synchronized (mLocks) { 1295 long when = 0; 1296 if (timeoutOverride <= 0) { 1297 switch (nextState) 1298 { 1299 case SCREEN_BRIGHT: 1300 when = now + mKeylightDelay; 1301 break; 1302 case SCREEN_DIM: 1303 if (mDimDelay >= 0) { 1304 when = now + mDimDelay; 1305 break; 1306 } else { 1307 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim"); 1308 } 1309 case SCREEN_OFF: 1310 synchronized (mLocks) { 1311 when = now + mScreenOffDelay; 1312 } 1313 break; 1314 default: 1315 when = now; 1316 break; 1317 } 1318 } else { 1319 override: { 1320 if (timeoutOverride <= mScreenOffDelay) { 1321 when = now + timeoutOverride; 1322 nextState = SCREEN_OFF; 1323 break override; 1324 } 1325 timeoutOverride -= mScreenOffDelay; 1326 1327 if (mDimDelay >= 0) { 1328 if (timeoutOverride <= mDimDelay) { 1329 when = now + timeoutOverride; 1330 nextState = SCREEN_DIM; 1331 break override; 1332 } 1333 timeoutOverride -= mDimDelay; 1334 } 1335 1336 when = now + timeoutOverride; 1337 nextState = SCREEN_BRIGHT; 1338 } 1339 } 1340 if (DEBUG) { 1341 Slog.d(TAG, "setTimeoutLocked now=" + now 1342 + " timeoutOverride=" + timeoutOverride 1343 + " nextState=" + nextState + " when=" + when); 1344 } 1345 1346 mHandler.removeCallbacks(mTimeoutTask); 1347 mTimeoutTask.nextState = nextState; 1348 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0 1349 ? (originalTimeoutOverride - timeoutOverride) 1350 : -1; 1351 mHandler.postAtTime(mTimeoutTask, when); 1352 mNextTimeout = when; // for debugging 1353 } 1354 } 1355 } 1356 1357 private void cancelTimerLocked() 1358 { 1359 mHandler.removeCallbacks(mTimeoutTask); 1360 mTimeoutTask.nextState = -1; 1361 } 1362 1363 private class TimeoutTask implements Runnable 1364 { 1365 int nextState; // access should be synchronized on mLocks 1366 long remainingTimeoutOverride; 1367 public void run() 1368 { 1369 synchronized (mLocks) { 1370 if (DEBUG) { 1371 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState); 1372 } 1373 1374 if (nextState == -1) { 1375 return; 1376 } 1377 1378 mUserState = this.nextState; 1379 setPowerState(this.nextState | mWakeLockState); 1380 1381 long now = SystemClock.uptimeMillis(); 1382 1383 switch (this.nextState) 1384 { 1385 case SCREEN_BRIGHT: 1386 if (mDimDelay >= 0) { 1387 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM); 1388 break; 1389 } 1390 case SCREEN_DIM: 1391 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF); 1392 break; 1393 } 1394 } 1395 } 1396 } 1397 1398 private void sendNotificationLocked(boolean on, int why) { 1399 if (!mInitialized) { 1400 // No notifications sent until first initialization is done. 1401 // This is so that when we are moving from our initial state 1402 // which looks like the screen was off to it being on, we do not 1403 // go through the process of waiting for the higher-level user 1404 // space to be ready before turning up the display brightness. 1405 // (And also do not send needless broadcasts about the screen.) 1406 return; 1407 } 1408 1409 if (DEBUG_SCREEN_ON) { 1410 RuntimeException here = new RuntimeException("here"); 1411 here.fillInStackTrace(); 1412 Slog.i(TAG, "sendNotificationLocked: " + on, here); 1413 } 1414 1415 if (!on) { 1416 mStillNeedSleepNotification = false; 1417 } 1418 1419 // Add to the queue. 1420 int index = 0; 1421 while (mBroadcastQueue[index] != -1) { 1422 index++; 1423 } 1424 mBroadcastQueue[index] = on ? 1 : 0; 1425 mBroadcastWhy[index] = why; 1426 1427 // If we added it position 2, then there is a pair that can be stripped. 1428 // If we added it position 1 and we're turning the screen off, we can strip 1429 // the pair and do nothing, because the screen is already off, and therefore 1430 // keyguard has already been enabled. 1431 // However, if we added it at position 1 and we're turning it on, then position 1432 // 0 was to turn it off, and we can't strip that, because keyguard needs to come 1433 // on, so have to run the queue then. 1434 if (index == 2) { 1435 // While we're collapsing them, if it's going off, and the new reason 1436 // is more significant than the first, then use the new one. 1437 if (!on && mBroadcastWhy[0] > why) { 1438 mBroadcastWhy[0] = why; 1439 } 1440 mBroadcastQueue[0] = on ? 1 : 0; 1441 mBroadcastQueue[1] = -1; 1442 mBroadcastQueue[2] = -1; 1443 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount); 1444 mBroadcastWakeLock.release(); 1445 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount); 1446 mBroadcastWakeLock.release(); 1447 index = 0; 1448 } 1449 if (index == 1 && !on) { 1450 mBroadcastQueue[0] = -1; 1451 mBroadcastQueue[1] = -1; 1452 index = -1; 1453 // The wake lock was being held, but we're not actually going to do any 1454 // broadcasts, so release the wake lock. 1455 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount); 1456 mBroadcastWakeLock.release(); 1457 } 1458 1459 // The broadcast queue has changed; make sure the screen is on if it 1460 // is now possible for it to be. 1461 if (mSkippedScreenOn) { 1462 updateLightsLocked(mPowerState, SCREEN_ON_BIT); 1463 } 1464 1465 // Now send the message. 1466 if (index >= 0) { 1467 // Acquire the broadcast wake lock before changing the power 1468 // state. It will be release after the broadcast is sent. 1469 // We always increment the ref count for each notification in the queue 1470 // and always decrement when that notification is handled. 1471 mBroadcastWakeLock.acquire(); 1472 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount); 1473 mHandler.post(mNotificationTask); 1474 } 1475 } 1476 1477 private WindowManagerPolicy.ScreenOnListener mScreenOnListener = 1478 new WindowManagerPolicy.ScreenOnListener() { 1479 public void onScreenOn() { 1480 synchronized (mLocks) { 1481 if (mPreparingForScreenOn) { 1482 mPreparingForScreenOn = false; 1483 updateLightsLocked(mPowerState, SCREEN_ON_BIT); 1484 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1485 4, mBroadcastWakeLock.mCount); 1486 mBroadcastWakeLock.release(); 1487 } 1488 } 1489 } 1490 }; 1491 1492 private Runnable mNotificationTask = new Runnable() 1493 { 1494 public void run() 1495 { 1496 while (true) { 1497 int value; 1498 int why; 1499 WindowManagerPolicy policy; 1500 synchronized (mLocks) { 1501 value = mBroadcastQueue[0]; 1502 why = mBroadcastWhy[0]; 1503 for (int i=0; i<2; i++) { 1504 mBroadcastQueue[i] = mBroadcastQueue[i+1]; 1505 mBroadcastWhy[i] = mBroadcastWhy[i+1]; 1506 } 1507 policy = getPolicyLocked(); 1508 if (value == 1 && !mPreparingForScreenOn) { 1509 mPreparingForScreenOn = true; 1510 mBroadcastWakeLock.acquire(); 1511 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, 1512 mBroadcastWakeLock.mCount); 1513 } 1514 } 1515 if (value == 1) { 1516 mScreenOnStart = SystemClock.uptimeMillis(); 1517 1518 policy.screenTurningOn(mScreenOnListener); 1519 try { 1520 ActivityManagerNative.getDefault().wakingUp(); 1521 } catch (RemoteException e) { 1522 // ignore it 1523 } 1524 1525 if (DEBUG) { 1526 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock); 1527 } 1528 if (mContext != null && ActivityManagerNative.isSystemReady()) { 1529 mContext.sendOrderedBroadcast(mScreenOnIntent, null, 1530 mScreenOnBroadcastDone, mHandler, 0, null, null); 1531 } else { 1532 synchronized (mLocks) { 1533 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2, 1534 mBroadcastWakeLock.mCount); 1535 mBroadcastWakeLock.release(); 1536 } 1537 } 1538 } 1539 else if (value == 0) { 1540 mScreenOffStart = SystemClock.uptimeMillis(); 1541 1542 policy.screenTurnedOff(why); 1543 try { 1544 ActivityManagerNative.getDefault().goingToSleep(); 1545 } catch (RemoteException e) { 1546 // ignore it. 1547 } 1548 1549 if (mContext != null && ActivityManagerNative.isSystemReady()) { 1550 mContext.sendOrderedBroadcast(mScreenOffIntent, null, 1551 mScreenOffBroadcastDone, mHandler, 0, null, null); 1552 } else { 1553 synchronized (mLocks) { 1554 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3, 1555 mBroadcastWakeLock.mCount); 1556 updateLightsLocked(mPowerState, SCREEN_ON_BIT); 1557 mBroadcastWakeLock.release(); 1558 } 1559 } 1560 } 1561 else { 1562 // If we're in this case, then this handler is running for a previous 1563 // paired transaction. mBroadcastWakeLock will already have been released. 1564 break; 1565 } 1566 } 1567 } 1568 }; 1569 1570 long mScreenOnStart; 1571 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() { 1572 public void onReceive(Context context, Intent intent) { 1573 synchronized (mLocks) { 1574 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1, 1575 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount); 1576 mBroadcastWakeLock.release(); 1577 } 1578 } 1579 }; 1580 1581 long mScreenOffStart; 1582 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() { 1583 public void onReceive(Context context, Intent intent) { 1584 synchronized (mLocks) { 1585 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0, 1586 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount); 1587 mBroadcastWakeLock.release(); 1588 } 1589 } 1590 }; 1591 1592 /** 1593 * Prevents the screen from turning on even if it *should* turn on due 1594 * to a subsequent full wake lock being acquired. 1595 * <p> 1596 * This is a temporary hack that allows an activity to "cover up" any 1597 * display glitches that happen during the activity's startup 1598 * sequence. (Specifically, this API was added to work around a 1599 * cosmetic bug in the "incoming call" sequence, where the lock screen 1600 * would flicker briefly before the incoming call UI became visible.) 1601 * TODO: There ought to be a more elegant way of doing this, 1602 * probably by having the PowerManager and ActivityManager 1603 * work together to let apps specify that the screen on/off 1604 * state should be synchronized with the Activity lifecycle. 1605 * <p> 1606 * Note that calling preventScreenOn(true) will NOT turn the screen 1607 * off if it's currently on. (This API only affects *future* 1608 * acquisitions of full wake locks.) 1609 * But calling preventScreenOn(false) WILL turn the screen on if 1610 * it's currently off because of a prior preventScreenOn(true) call. 1611 * <p> 1612 * Any call to preventScreenOn(true) MUST be followed promptly by a call 1613 * to preventScreenOn(false). In fact, if the preventScreenOn(false) 1614 * call doesn't occur within 5 seconds, we'll turn the screen back on 1615 * ourselves (and log a warning about it); this prevents a buggy app 1616 * from disabling the screen forever.) 1617 * <p> 1618 * TODO: this feature should really be controlled by a new type of poke 1619 * lock (rather than an IPowerManager call). 1620 */ 1621 public void preventScreenOn(boolean prevent) { 1622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1623 1624 synchronized (mLocks) { 1625 if (prevent) { 1626 // First of all, grab a partial wake lock to 1627 // make sure the CPU stays on during the entire 1628 // preventScreenOn(true) -> preventScreenOn(false) sequence. 1629 mPreventScreenOnPartialLock.acquire(); 1630 1631 // Post a forceReenableScreen() call (for 5 seconds in the 1632 // future) to make sure the matching preventScreenOn(false) call 1633 // has happened by then. 1634 mHandler.removeCallbacks(mForceReenableScreenTask); 1635 mHandler.postDelayed(mForceReenableScreenTask, 5000); 1636 1637 // Finally, set the flag that prevents the screen from turning on. 1638 // (Below, in setPowerState(), we'll check mPreventScreenOn and 1639 // we *won't* call setScreenStateLocked(true) if it's set.) 1640 mPreventScreenOn = true; 1641 } else { 1642 // (Re)enable the screen. 1643 mPreventScreenOn = false; 1644 1645 // We're "undoing" a the prior preventScreenOn(true) call, so we 1646 // no longer need the 5-second safeguard. 1647 mHandler.removeCallbacks(mForceReenableScreenTask); 1648 1649 // Forcibly turn on the screen if it's supposed to be on. (This 1650 // handles the case where the screen is currently off because of 1651 // a prior preventScreenOn(true) call.) 1652 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) { 1653 if (DEBUG) { 1654 Slog.d(TAG, 1655 "preventScreenOn: turning on after a prior preventScreenOn(true)!"); 1656 } 1657 int err = setScreenStateLocked(true); 1658 if (err != 0) { 1659 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err); 1660 } 1661 } 1662 1663 // Release the partial wake lock that we held during the 1664 // preventScreenOn(true) -> preventScreenOn(false) sequence. 1665 mPreventScreenOnPartialLock.release(); 1666 } 1667 } 1668 } 1669 1670 public void setScreenBrightnessOverride(int brightness) { 1671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1672 1673 if (DEBUG) Slog.d(TAG, "setScreenBrightnessOverride " + brightness); 1674 synchronized (mLocks) { 1675 if (mScreenBrightnessOverride != brightness) { 1676 mScreenBrightnessOverride = brightness; 1677 if (isScreenOn()) { 1678 updateLightsLocked(mPowerState, SCREEN_ON_BIT); 1679 } 1680 } 1681 } 1682 } 1683 1684 public void setButtonBrightnessOverride(int brightness) { 1685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 1686 1687 if (DEBUG) Slog.d(TAG, "setButtonBrightnessOverride " + brightness); 1688 synchronized (mLocks) { 1689 if (mButtonBrightnessOverride != brightness) { 1690 mButtonBrightnessOverride = brightness; 1691 if (isScreenOn()) { 1692 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT); 1693 } 1694 } 1695 } 1696 } 1697 1698 /** 1699 * Sanity-check that gets called 5 seconds after any call to 1700 * preventScreenOn(true). This ensures that the original call 1701 * is followed promptly by a call to preventScreenOn(false). 1702 */ 1703 private void forceReenableScreen() { 1704 // We shouldn't get here at all if mPreventScreenOn is false, since 1705 // we should have already removed any existing 1706 // mForceReenableScreenTask messages... 1707 if (!mPreventScreenOn) { 1708 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do"); 1709 return; 1710 } 1711 1712 // Uh oh. It's been 5 seconds since a call to 1713 // preventScreenOn(true) and we haven't re-enabled the screen yet. 1714 // This means the app that called preventScreenOn(true) is either 1715 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)), 1716 // or buggy (i.e. it forgot to call preventScreenOn(false), or 1717 // crashed before doing so.) 1718 1719 // Log a warning, and forcibly turn the screen back on. 1720 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! " 1721 + "Forcing the screen back on..."); 1722 preventScreenOn(false); 1723 } 1724 1725 private Runnable mForceReenableScreenTask = new Runnable() { 1726 public void run() { 1727 forceReenableScreen(); 1728 } 1729 }; 1730 1731 private int setScreenStateLocked(boolean on) { 1732 if (DEBUG_SCREEN_ON) { 1733 RuntimeException e = new RuntimeException("here"); 1734 e.fillInStackTrace(); 1735 Slog.i(TAG, "Set screen state: " + on, e); 1736 } 1737 if (on) { 1738 if (mInitialized && ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn)) { 1739 // If we are turning the screen state on, but the screen 1740 // light is currently off, then make sure that we set the 1741 // light at this point to 0. This is the case where we are 1742 // turning on the screen and waiting for the UI to be drawn 1743 // before showing it to the user. We want the light off 1744 // until it is ready to be shown to the user, not it using 1745 // whatever the last value it had. 1746 // Skip this if the screen is being turned on for the first time 1747 // after boot (mInitialized is false). 1748 if (DEBUG_SCREEN_ON) { 1749 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x" 1750 + Integer.toHexString(mPowerState) 1751 + " mSkippedScreenOn=" + mSkippedScreenOn); 1752 } 1753 mScreenBrightnessAnimator.animateTo(PowerManager.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0); 1754 } 1755 } 1756 int err = nativeSetScreenState(on); 1757 if (err == 0) { 1758 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0); 1759 if (mUseSoftwareAutoBrightness) { 1760 enableLightSensorLocked(on); 1761 if (on) { 1762 // If AutoBrightness is enabled, set the brightness immediately after the 1763 // next sensor value is received. 1764 mWaitingForFirstLightSensor = mAutoBrightessEnabled; 1765 } else { 1766 // make sure button and key backlights are off too 1767 mButtonLight.turnOff(); 1768 mKeyboardLight.turnOff(); 1769 } 1770 } 1771 } 1772 return err; 1773 } 1774 1775 private void setPowerState(int state) 1776 { 1777 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT); 1778 } 1779 1780 private void setPowerState(int newState, boolean noChangeLights, int reason) 1781 { 1782 synchronized (mLocks) { 1783 int err; 1784 1785 if (DEBUG) { 1786 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState) 1787 + " newState=0x" + Integer.toHexString(newState) 1788 + " noChangeLights=" + noChangeLights 1789 + " reason=" + reason); 1790 } 1791 1792 if (noChangeLights) { 1793 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK); 1794 } 1795 if (mProximitySensorActive) { 1796 // don't turn on the screen when the proximity sensor lock is held 1797 newState = (newState & ~SCREEN_BRIGHT); 1798 } 1799 1800 if (batteryIsLow()) { 1801 newState |= BATTERY_LOW_BIT; 1802 } else { 1803 newState &= ~BATTERY_LOW_BIT; 1804 } 1805 if (newState == mPowerState && mInitialized) { 1806 return; 1807 } 1808 1809 if (!mBootCompleted && !mUseSoftwareAutoBrightness) { 1810 newState |= ALL_BRIGHT; 1811 } 1812 1813 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0; 1814 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0; 1815 1816 if (DEBUG) { 1817 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState 1818 + " newState=" + newState + " noChangeLights=" + noChangeLights); 1819 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0) 1820 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0)); 1821 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0) 1822 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0)); 1823 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0) 1824 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0)); 1825 Slog.d(TAG, " oldScreenOn=" + oldScreenOn 1826 + " newScreenOn=" + newScreenOn); 1827 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0) 1828 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0)); 1829 } 1830 1831 final boolean stateChanged = mPowerState != newState; 1832 1833 if (stateChanged && !newScreenOn && reason == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT) { 1834 if (mPolicy != null && mIsPowered && mPolicy.isScreenSaverEnabled()) { 1835 if (DEBUG) { 1836 Slog.d(TAG, "setPowerState: running screen saver instead of turning off screen"); 1837 } 1838 if (mPolicy.startScreenSaver()) { 1839 // was successful 1840 return; 1841 } 1842 } 1843 } 1844 1845 1846 if (oldScreenOn != newScreenOn) { 1847 if (newScreenOn) { 1848 // When the user presses the power button, we need to always send out the 1849 // notification that it's going to sleep so the keyguard goes on. But 1850 // we can't do that until the screen fades out, so we don't show the keyguard 1851 // too early. 1852 if (mStillNeedSleepNotification) { 1853 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER); 1854 } 1855 1856 // Turn on the screen UNLESS there was a prior 1857 // preventScreenOn(true) request. (Note that the lifetime 1858 // of a single preventScreenOn() request is limited to 5 1859 // seconds to prevent a buggy app from disabling the 1860 // screen forever; see forceReenableScreen().) 1861 boolean reallyTurnScreenOn = true; 1862 if (DEBUG) { 1863 Slog.d(TAG, "- turning screen on... mPreventScreenOn = " 1864 + mPreventScreenOn); 1865 } 1866 1867 if (mPreventScreenOn) { 1868 if (DEBUG) { 1869 Slog.d(TAG, "- PREVENTING screen from really turning on!"); 1870 } 1871 reallyTurnScreenOn = false; 1872 } 1873 if (reallyTurnScreenOn) { 1874 err = setScreenStateLocked(true); 1875 long identity = Binder.clearCallingIdentity(); 1876 try { 1877 mBatteryStats.noteScreenBrightness(getPreferredBrightness()); 1878 mBatteryStats.noteScreenOn(); 1879 } catch (RemoteException e) { 1880 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e); 1881 } finally { 1882 Binder.restoreCallingIdentity(identity); 1883 } 1884 } else { 1885 setScreenStateLocked(false); 1886 // But continue as if we really did turn the screen on... 1887 err = 0; 1888 } 1889 1890 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason, 0, 0); 1891 if (err == 0) { 1892 sendNotificationLocked(true, -1); 1893 // Update the lights *after* taking care of turning the 1894 // screen on, so we do this after our notifications are 1895 // enqueued and thus will delay turning on the screen light 1896 // until the windows are correctly displayed. 1897 if (stateChanged) { 1898 updateLightsLocked(newState, 0); 1899 } 1900 mPowerState |= SCREEN_ON_BIT; 1901 } 1902 1903 } else { 1904 // Update the lights *before* taking care of turning the 1905 // screen off, so we can initiate any animations that are desired. 1906 mScreenOffReason = reason; 1907 if (stateChanged) { 1908 updateLightsLocked(newState, 0); 1909 } 1910 1911 // cancel light sensor task 1912 mHandler.removeCallbacks(mAutoBrightnessTask); 1913 mLightSensorPendingDecrease = false; 1914 mLightSensorPendingIncrease = false; 1915 mScreenOffTime = SystemClock.elapsedRealtime(); 1916 long identity = Binder.clearCallingIdentity(); 1917 try { 1918 mBatteryStats.noteScreenOff(); 1919 } catch (RemoteException e) { 1920 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e); 1921 } finally { 1922 Binder.restoreCallingIdentity(identity); 1923 } 1924 mPowerState &= ~SCREEN_ON_BIT; 1925 if (!mScreenBrightnessAnimator.isAnimating()) { 1926 err = screenOffFinishedAnimatingLocked(reason); 1927 } else { 1928 err = 0; 1929 } 1930 1931 // stop the screensaver if user turned screen off 1932 if (stateChanged && reason == WindowManagerPolicy.OFF_BECAUSE_OF_USER) { 1933 if (mPolicy != null) { 1934 mPolicy.stopScreenSaver(); 1935 } 1936 } 1937 } 1938 } else if (stateChanged) { 1939 // Screen on/off didn't change, but lights may have. 1940 updateLightsLocked(newState, 0); 1941 } 1942 1943 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK); 1944 1945 updateNativePowerStateLocked(); 1946 } 1947 } 1948 1949 private void updateNativePowerStateLocked() { 1950 if (!mHeadless) { 1951 nativeSetPowerState( 1952 (mPowerState & SCREEN_ON_BIT) != 0, 1953 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT); 1954 } 1955 } 1956 1957 private int screenOffFinishedAnimatingLocked(int reason) { 1958 // I don't think we need to check the current state here because all of these 1959 // Power.setScreenState and sendNotificationLocked can both handle being 1960 // called multiple times in the same state. -joeo 1961 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, 0, 0); 1962 int err = setScreenStateLocked(false); 1963 if (err == 0) { 1964 mScreenOffReason = reason; 1965 sendNotificationLocked(false, reason); 1966 } 1967 return err; 1968 } 1969 1970 private boolean batteryIsLow() { 1971 return (!mIsPowered && 1972 mBatteryService.getBatteryLevel() <= LOW_BATTERY_THRESHOLD); 1973 } 1974 1975 private boolean shouldDeferScreenOnLocked() { 1976 if (mPreparingForScreenOn) { 1977 // Currently waiting for confirmation from the policy that it 1978 // is okay to turn on the screen. Don't allow the screen to go 1979 // on until that is done. 1980 if (DEBUG_SCREEN_ON) Slog.i(TAG, 1981 "updateLights: delaying screen on due to mPreparingForScreenOn"); 1982 return true; 1983 } else { 1984 // If there is a screen-on command in the notification queue, we 1985 // can't turn the screen on until it has been processed (and we 1986 // have set mPreparingForScreenOn) or it has been dropped. 1987 for (int i=0; i<mBroadcastQueue.length; i++) { 1988 if (mBroadcastQueue[i] == 1) { 1989 if (DEBUG_SCREEN_ON) Slog.i(TAG, 1990 "updateLights: delaying screen on due to notification queue"); 1991 return true; 1992 } 1993 } 1994 } 1995 return false; 1996 } 1997 1998 private void updateLightsLocked(int newState, int forceState) { 1999 final int oldState = mPowerState; 2000 2001 // If the screen is not currently on, we will want to delay actually 2002 // turning the lights on if we are still getting the UI put up. 2003 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) { 2004 // Don't turn screen on until we know we are really ready to. 2005 // This is to avoid letting the screen go on before things like the 2006 // lock screen have been displayed. 2007 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) { 2008 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT); 2009 } 2010 } 2011 2012 if ((newState & SCREEN_ON_BIT) != 0) { 2013 // Only turn on the buttons or keyboard if the screen is also on. 2014 // We should never see the buttons on but not the screen. 2015 newState = applyButtonState(newState); 2016 newState = applyKeyboardState(newState); 2017 } 2018 final int realDifference = (newState ^ oldState); 2019 final int difference = realDifference | forceState; 2020 if (difference == 0) { 2021 return; 2022 } 2023 2024 int offMask = 0; 2025 int dimMask = 0; 2026 int onMask = 0; 2027 2028 int preferredBrightness = getPreferredBrightness(); 2029 2030 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) { 2031 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) { 2032 offMask |= KEYBOARD_BRIGHT_BIT; 2033 } else { 2034 onMask |= KEYBOARD_BRIGHT_BIT; 2035 } 2036 } 2037 2038 if ((difference & BUTTON_BRIGHT_BIT) != 0) { 2039 if ((newState & BUTTON_BRIGHT_BIT) == 0) { 2040 offMask |= BUTTON_BRIGHT_BIT; 2041 } else { 2042 onMask |= BUTTON_BRIGHT_BIT; 2043 } 2044 } 2045 2046 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) { 2047 int nominalCurrentValue = -1; 2048 // If there was an actual difference in the light state, then 2049 // figure out the "ideal" current value based on the previous 2050 // state. Otherwise, this is a change due to the brightness 2051 // override, so we want to animate from whatever the current 2052 // value is. 2053 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) { 2054 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) { 2055 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT: 2056 nominalCurrentValue = preferredBrightness; 2057 break; 2058 case SCREEN_ON_BIT: 2059 nominalCurrentValue = mScreenBrightnessDim; 2060 break; 2061 case 0: 2062 nominalCurrentValue = PowerManager.BRIGHTNESS_OFF; 2063 break; 2064 case SCREEN_BRIGHT_BIT: 2065 default: 2066 // not possible 2067 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness(); 2068 break; 2069 } 2070 } 2071 int brightness = preferredBrightness; 2072 int steps = ANIM_STEPS; 2073 if ((newState & SCREEN_BRIGHT_BIT) == 0) { 2074 // dim or turn off backlight, depending on if the screen is on 2075 // the scale is because the brightness ramp isn't linear and this biases 2076 // it so the later parts take longer. 2077 final float scale = 1.5f; 2078 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness); 2079 if (ratio > 1.0f) ratio = 1.0f; 2080 if ((newState & SCREEN_ON_BIT) == 0) { 2081 if ((oldState & SCREEN_BRIGHT_BIT) != 0) { 2082 // was bright 2083 steps = ANIM_STEPS; 2084 } else { 2085 // was dim 2086 steps = (int)(ANIM_STEPS*ratio*scale); 2087 } 2088 brightness = PowerManager.BRIGHTNESS_OFF; 2089 } else { 2090 if ((oldState & SCREEN_ON_BIT) != 0) { 2091 // was bright 2092 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale); 2093 } else { 2094 // was dim 2095 steps = (int)(ANIM_STEPS*ratio); 2096 } 2097 final int stayOnConditions = getStayOnConditionsLocked(); 2098 if (stayOnConditions != 0 && mBatteryService.isPowered(stayOnConditions)) { 2099 // If the "stay on while plugged in" option is 2100 // turned on, then the screen will often not 2101 // automatically turn off while plugged in. To 2102 // still have a sense of when it is inactive, we 2103 // will then count going dim as turning off. 2104 mScreenOffTime = SystemClock.elapsedRealtime(); 2105 } 2106 brightness = mScreenBrightnessDim; 2107 } 2108 } 2109 if (mWaitingForFirstLightSensor && (newState & SCREEN_ON_BIT) != 0) { 2110 steps = IMMEDIATE_ANIM_STEPS; 2111 } 2112 2113 long identity = Binder.clearCallingIdentity(); 2114 try { 2115 mBatteryStats.noteScreenBrightness(brightness); 2116 } catch (RemoteException e) { 2117 // Nothing interesting to do. 2118 } finally { 2119 Binder.restoreCallingIdentity(identity); 2120 } 2121 if (!mSkippedScreenOn) { 2122 int dt = steps * NOMINAL_FRAME_TIME_MS; 2123 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt); 2124 if (DEBUG_SCREEN_ON) { 2125 RuntimeException e = new RuntimeException("here"); 2126 e.fillInStackTrace(); 2127 Slog.i(TAG, "Setting screen brightness: " + brightness, e); 2128 } 2129 } 2130 } 2131 2132 if (DEBUG) { 2133 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask) 2134 + " dimMask=0x" + Integer.toHexString(dimMask) 2135 + " onMask=0x" + Integer.toHexString(onMask) 2136 + " difference=0x" + Integer.toHexString(difference) 2137 + " realDifference=0x" + Integer.toHexString(realDifference) 2138 + " forceState=0x" + Integer.toHexString(forceState) 2139 ); 2140 } 2141 2142 if (offMask != 0) { 2143 if (DEBUG) Slog.i(TAG, "Setting brightess off: " + offMask); 2144 setLightBrightness(offMask, PowerManager.BRIGHTNESS_OFF); 2145 } 2146 if (dimMask != 0) { 2147 int brightness = mScreenBrightnessDim; 2148 if ((newState & BATTERY_LOW_BIT) != 0 && 2149 brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) { 2150 brightness = PowerManager.BRIGHTNESS_LOW_BATTERY; 2151 } 2152 if (DEBUG) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask); 2153 setLightBrightness(dimMask, brightness); 2154 } 2155 if (onMask != 0) { 2156 int brightness = getPreferredBrightness(); 2157 if ((newState & BATTERY_LOW_BIT) != 0 && 2158 brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) { 2159 brightness = PowerManager.BRIGHTNESS_LOW_BATTERY; 2160 } 2161 if (DEBUG) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask); 2162 setLightBrightness(onMask, brightness); 2163 } 2164 } 2165 2166 /** 2167 * Note: by design this class does not hold mLocks while calling native methods. 2168 * Nor should it. Ever. 2169 */ 2170 class ScreenBrightnessAnimator extends HandlerThread { 2171 static final int ANIMATE_LIGHTS = 10; 2172 static final int ANIMATE_POWER_OFF = 11; 2173 volatile int startValue; 2174 volatile int endValue; 2175 volatile int startSensorValue; 2176 volatile int endSensorValue; 2177 volatile int currentValue; 2178 private int currentMask; 2179 private int duration; 2180 private long startTimeMillis; 2181 private final String prefix; 2182 2183 public ScreenBrightnessAnimator(String name, int priority) { 2184 super(name, priority); 2185 prefix = name; 2186 } 2187 2188 @Override 2189 protected void onLooperPrepared() { 2190 mScreenBrightnessHandler = new Handler() { 2191 public void handleMessage(Message msg) { 2192 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation 2193 ? LightsService.BRIGHTNESS_MODE_SENSOR 2194 : LightsService.BRIGHTNESS_MODE_USER); 2195 if (msg.what == ANIMATE_LIGHTS) { 2196 final int mask = msg.arg1; 2197 int value = msg.arg2; 2198 long tStart = SystemClock.uptimeMillis(); 2199 if ((mask & SCREEN_BRIGHT_BIT) != 0) { 2200 if (DEBUG_LIGHT_ANIMATION) Slog.v(TAG, "Set brightness: " + value); 2201 mLcdLight.setBrightness(value, brightnessMode); 2202 } 2203 long elapsed = SystemClock.uptimeMillis() - tStart; 2204 if ((mask & BUTTON_BRIGHT_BIT) != 0) { 2205 mButtonLight.setBrightness(value); 2206 } 2207 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) { 2208 mKeyboardLight.setBrightness(value); 2209 } 2210 2211 if (elapsed > 100) { 2212 Slog.e(TAG, "Excessive delay setting brightness: " + elapsed 2213 + "ms, mask=" + mask); 2214 } 2215 2216 // Throttle brightness updates to frame refresh rate 2217 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 1; 2218 synchronized(this) { 2219 currentValue = value; 2220 } 2221 animateInternal(mask, false, delay); 2222 } else if (msg.what == ANIMATE_POWER_OFF) { 2223 int mode = msg.arg1; 2224 nativeStartSurfaceFlingerAnimation(mode); 2225 } 2226 } 2227 }; 2228 synchronized (this) { 2229 mInitComplete = true; 2230 notifyAll(); 2231 } 2232 } 2233 2234 private void animateInternal(int mask, boolean turningOff, int delay) { 2235 synchronized (this) { 2236 if (currentValue != endValue) { 2237 final long now = SystemClock.elapsedRealtime(); 2238 final int elapsed = (int) (now - startTimeMillis); 2239 int newValue; 2240 if (elapsed < duration) { 2241 int delta = endValue - startValue; 2242 newValue = startValue + delta * elapsed / duration; 2243 newValue = Math.max(PowerManager.BRIGHTNESS_OFF, newValue); 2244 newValue = Math.min(PowerManager.BRIGHTNESS_ON, newValue); 2245 // Optimization to delay next step until a change will occur. 2246 if (delay > 0 && newValue == currentValue) { 2247 final int timePerStep = duration / Math.abs(delta); 2248 delay = Math.min(duration - elapsed, timePerStep); 2249 newValue += delta < 0 ? -1 : 1; 2250 } 2251 // adjust the peak sensor value until we get to the target sensor value 2252 delta = endSensorValue - startSensorValue; 2253 mHighestLightSensorValue = startSensorValue + delta * elapsed / duration; 2254 } else { 2255 newValue = endValue; 2256 mHighestLightSensorValue = endSensorValue; 2257 if (endValue > 0) { 2258 mInitialAnimation = false; 2259 } 2260 } 2261 2262 if (DEBUG_LIGHT_ANIMATION) { 2263 Slog.v(TAG, "Animating light: " + "start:" + startValue 2264 + ", end:" + endValue + ", elapsed:" + elapsed 2265 + ", duration:" + duration + ", current:" + currentValue 2266 + ", newValue:" + newValue 2267 + ", delay:" + delay 2268 + ", highestSensor:" + mHighestLightSensorValue); 2269 } 2270 2271 if (turningOff && !mHeadless && !mAnimateScreenLights) { 2272 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR 2273 ? 0 : mAnimationSetting; 2274 if (DEBUG_LIGHT_ANIMATION) { 2275 Slog.v(TAG, "Doing power-off anim, mode=" + mode); 2276 } 2277 mScreenBrightnessHandler.obtainMessage(ANIMATE_POWER_OFF, mode, 0) 2278 .sendToTarget(); 2279 } 2280 mScreenBrightnessHandler.removeMessages( 2281 ScreenBrightnessAnimator.ANIMATE_LIGHTS); 2282 Message msg = mScreenBrightnessHandler 2283 .obtainMessage(ANIMATE_LIGHTS, mask, newValue); 2284 mScreenBrightnessHandler.sendMessageDelayed(msg, delay); 2285 } 2286 } 2287 } 2288 2289 public void dump(PrintWriter pw, String string) { 2290 pw.println(string); 2291 pw.println(" animating: " + "start:" + startValue + ", end:" + endValue 2292 + ", duration:" + duration + ", current:" + currentValue); 2293 pw.println(" startSensorValue:" + startSensorValue 2294 + " endSensorValue:" + endSensorValue); 2295 pw.println(" startTimeMillis:" + startTimeMillis 2296 + " now:" + SystemClock.elapsedRealtime()); 2297 pw.println(" currentMask:" + dumpPowerState(currentMask)); 2298 } 2299 2300 public void animateTo(int target, int mask, int animationDuration) { 2301 animateTo(target, mHighestLightSensorValue, mask, animationDuration); 2302 } 2303 2304 public void animateTo(int target, int sensorTarget, int mask, int animationDuration) { 2305 synchronized(this) { 2306 if ((mask & SCREEN_BRIGHT_BIT) == 0) { 2307 // We only animate keyboard and button when passed in with SCREEN_BRIGHT_BIT. 2308 if ((mask & BUTTON_BRIGHT_BIT) != 0) { 2309 mButtonLight.setBrightness(target); 2310 } 2311 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) { 2312 mKeyboardLight.setBrightness(target); 2313 } 2314 return; 2315 } 2316 if (isAnimating() && (mask ^ currentMask) != 0) { 2317 // current animation is unrelated to new animation, jump to final values 2318 cancelAnimation(); 2319 } 2320 if (mInitialAnimation) { 2321 // jump to final value in one step the first time the brightness is set 2322 animationDuration = 0; 2323 if (target > 0) { 2324 mInitialAnimation = false; 2325 } 2326 } 2327 startValue = currentValue; 2328 endValue = target; 2329 startSensorValue = mHighestLightSensorValue; 2330 endSensorValue = sensorTarget; 2331 currentMask = mask; 2332 duration = (int) (mWindowScaleAnimation * animationDuration); 2333 startTimeMillis = SystemClock.elapsedRealtime(); 2334 2335 if (DEBUG_LIGHT_ANIMATION) { 2336 Slog.v(TAG, "animateTo(target=" + target 2337 + ", sensor=" + sensorTarget 2338 + ", mask=" + mask 2339 + ", duration=" + animationDuration +")" 2340 + ", currentValue=" + currentValue 2341 + ", startTime=" + startTimeMillis); 2342 } 2343 2344 if (target != currentValue) { 2345 final boolean doScreenAnim = (mask & (SCREEN_BRIGHT_BIT | SCREEN_ON_BIT)) != 0; 2346 final boolean turningOff = endValue == PowerManager.BRIGHTNESS_OFF; 2347 if (turningOff && doScreenAnim) { 2348 // Cancel all pending animations since we're turning off 2349 mScreenBrightnessHandler.removeCallbacksAndMessages(null); 2350 screenOffFinishedAnimatingLocked(mScreenOffReason); 2351 duration = 200; // TODO: how long should this be? 2352 } 2353 if (doScreenAnim) { 2354 animateInternal(mask, turningOff, 0); 2355 } 2356 // TODO: Handle keyboard light animation when we have devices that support it 2357 } 2358 } 2359 } 2360 2361 public int getCurrentBrightness() { 2362 synchronized (this) { 2363 return currentValue; 2364 } 2365 } 2366 2367 public boolean isAnimating() { 2368 synchronized (this) { 2369 return currentValue != endValue; 2370 } 2371 } 2372 2373 public void cancelAnimation() { 2374 animateTo(endValue, currentMask, 0); 2375 } 2376 } 2377 2378 private void setLightBrightness(int mask, int value) { 2379 mScreenBrightnessAnimator.animateTo(value, mask, 0); 2380 } 2381 2382 private int getPreferredBrightness() { 2383 int brightness = mScreenBrightnessSetting; 2384 if (mScreenBrightnessOverride >= 0) { 2385 brightness = mScreenBrightnessOverride; 2386 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness 2387 && mAutoBrightessEnabled) { 2388 brightness = mLightSensorScreenBrightness; 2389 } 2390 // Don't let applications turn the screen all the way off 2391 return Math.max(brightness, mScreenBrightnessDim); 2392 } 2393 2394 private int applyButtonState(int state) { 2395 int brightness = -1; 2396 if ((state & BATTERY_LOW_BIT) != 0) { 2397 // do not override brightness if the battery is low 2398 return state; 2399 } 2400 if (mButtonBrightnessOverride >= 0) { 2401 brightness = mButtonBrightnessOverride; 2402 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) { 2403 brightness = mLightSensorButtonBrightness; 2404 } 2405 if (brightness > 0) { 2406 return state | BUTTON_BRIGHT_BIT; 2407 } else if (brightness == 0) { 2408 return state & ~BUTTON_BRIGHT_BIT; 2409 } else { 2410 return state; 2411 } 2412 } 2413 2414 private int applyKeyboardState(int state) { 2415 int brightness = -1; 2416 if ((state & BATTERY_LOW_BIT) != 0) { 2417 // do not override brightness if the battery is low 2418 return state; 2419 } 2420 if (!mKeyboardVisible) { 2421 brightness = 0; 2422 } else if (mButtonBrightnessOverride >= 0) { 2423 brightness = mButtonBrightnessOverride; 2424 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) { 2425 brightness = mLightSensorKeyboardBrightness; 2426 } 2427 if (brightness > 0) { 2428 return state | KEYBOARD_BRIGHT_BIT; 2429 } else if (brightness == 0) { 2430 return state & ~KEYBOARD_BRIGHT_BIT; 2431 } else { 2432 return state; 2433 } 2434 } 2435 2436 public boolean isScreenOn() { 2437 synchronized (mLocks) { 2438 return (mPowerState & SCREEN_ON_BIT) != 0; 2439 } 2440 } 2441 2442 boolean isScreenBright() { 2443 synchronized (mLocks) { 2444 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT; 2445 } 2446 } 2447 2448 private boolean isScreenTurningOffLocked() { 2449 return (mScreenBrightnessAnimator.isAnimating() 2450 && mScreenBrightnessAnimator.endValue == PowerManager.BRIGHTNESS_OFF 2451 && (mScreenBrightnessAnimator.currentMask & SCREEN_BRIGHT_BIT) != 0); 2452 } 2453 2454 private boolean shouldLog(long time) { 2455 synchronized (mLocks) { 2456 if (time > (mWarningSpewThrottleTime + (60*60*1000))) { 2457 mWarningSpewThrottleTime = time; 2458 mWarningSpewThrottleCount = 0; 2459 return true; 2460 } else if (mWarningSpewThrottleCount < 30) { 2461 mWarningSpewThrottleCount++; 2462 return true; 2463 } else { 2464 return false; 2465 } 2466 } 2467 } 2468 2469 private void forceUserActivityLocked() { 2470 if (isScreenTurningOffLocked()) { 2471 // cancel animation so userActivity will succeed 2472 mScreenBrightnessAnimator.cancelAnimation(); 2473 } 2474 boolean savedActivityAllowed = mUserActivityAllowed; 2475 mUserActivityAllowed = true; 2476 userActivity(SystemClock.uptimeMillis(), false); 2477 mUserActivityAllowed = savedActivityAllowed; 2478 } 2479 2480 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) { 2481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2482 userActivity(time, -1, noChangeLights, PowerManager.USER_ACTIVITY_EVENT_OTHER, force, false); 2483 } 2484 2485 public void userActivity(long time, boolean noChangeLights) { 2486 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER) 2487 != PackageManager.PERMISSION_GRANTED) { 2488 if (shouldLog(time)) { 2489 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid=" 2490 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid()); 2491 } 2492 return; 2493 } 2494 2495 userActivity(time, -1, noChangeLights, PowerManager.USER_ACTIVITY_EVENT_OTHER, false, false); 2496 } 2497 2498 public void userActivity(long time, boolean noChangeLights, int eventType) { 2499 userActivity(time, -1, noChangeLights, eventType, false, false); 2500 } 2501 2502 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) { 2503 userActivity(time, -1, noChangeLights, eventType, force, false); 2504 } 2505 2506 /* 2507 * Reset the user activity timeout to now + timeout. This overrides whatever else is going 2508 * on with user activity. Don't use this function. 2509 */ 2510 public void clearUserActivityTimeout(long now, long timeout) { 2511 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2512 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now"); 2513 userActivity(now, timeout, false, PowerManager.USER_ACTIVITY_EVENT_OTHER, false, false); 2514 } 2515 2516 private void userActivity(long time, long timeoutOverride, boolean noChangeLights, 2517 int eventType, boolean force, boolean ignoreIfScreenOff) { 2518 2519 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == PowerManager.USER_ACTIVITY_EVENT_TOUCH)) { 2520 if (false) { 2521 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey)); 2522 } 2523 return; 2524 } 2525 2526 synchronized (mLocks) { 2527 if (DEBUG) { 2528 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time 2529 + " mUserActivityAllowed=" + mUserActivityAllowed 2530 + " mUserState=0x" + Integer.toHexString(mUserState) 2531 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState) 2532 + " mProximitySensorActive=" + mProximitySensorActive 2533 + " timeoutOverride=" + timeoutOverride 2534 + " force=" + force); 2535 } 2536 // ignore user activity if we are in the process of turning off the screen 2537 if (isScreenTurningOffLocked()) { 2538 Slog.d(TAG, "ignoring user activity while turning off screen"); 2539 return; 2540 } 2541 // ignore if the caller doesn't want this to allow the screen to turn 2542 // on, and the screen is currently off. 2543 if (ignoreIfScreenOff && (mPowerState & SCREEN_ON_BIT) == 0) { 2544 return; 2545 } 2546 // Disable proximity sensor if if user presses power key while we are in the 2547 // "waiting for proximity sensor to go negative" state. 2548 if (mProximitySensorActive && mProximityWakeLockCount == 0) { 2549 mProximitySensorActive = false; 2550 } 2551 if (mLastEventTime <= time || force) { 2552 mLastEventTime = time; 2553 if ((mUserActivityAllowed && !mProximitySensorActive) || force) { 2554 // Only turn on button backlights if a button was pressed 2555 // and auto brightness is disabled 2556 if (eventType == PowerManager.USER_ACTIVITY_EVENT_BUTTON && !mUseSoftwareAutoBrightness) { 2557 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT); 2558 } else { 2559 // don't clear button/keyboard backlights when the screen is touched. 2560 mUserState |= SCREEN_BRIGHT; 2561 } 2562 2563 int uid = Binder.getCallingUid(); 2564 long ident = Binder.clearCallingIdentity(); 2565 try { 2566 mBatteryStats.noteUserActivity(uid, eventType); 2567 } catch (RemoteException e) { 2568 // Ignore 2569 } finally { 2570 Binder.restoreCallingIdentity(ident); 2571 } 2572 2573 mWakeLockState = mLocks.reactivateScreenLocksLocked(); 2574 setPowerState(mUserState | mWakeLockState, noChangeLights, 2575 WindowManagerPolicy.OFF_BECAUSE_OF_USER); 2576 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT); 2577 } 2578 } 2579 } 2580 2581 if (mPolicy != null) { 2582 mPolicy.userActivity(); 2583 } 2584 } 2585 2586 private int getAutoBrightnessValue(int sensorValue, int[] values) { 2587 try { 2588 int i; 2589 for (i = 0; i < mAutoBrightnessLevels.length; i++) { 2590 if (sensorValue < mAutoBrightnessLevels[i]) { 2591 break; 2592 } 2593 } 2594 // This is the range of brightness values that we can use. 2595 final int minval = values[0]; 2596 final int maxval = values[mAutoBrightnessLevels.length]; 2597 // This is the range we will be scaling. We put some padding 2598 // at the low and high end to give the adjustment a little better 2599 // impact on the actual observed value. 2600 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION; 2601 // This is the desired brightness value from 0.0 to 1.0. 2602 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range); 2603 // Apply a scaling to the value based on the adjustment. 2604 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) { 2605 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting); 2606 if (adj <= .00001) { 2607 valf = 1; 2608 } else { 2609 valf /= adj; 2610 } 2611 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) { 2612 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting); 2613 valf *= adj; 2614 } 2615 // Apply an additional offset to the value based on the adjustment. 2616 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE; 2617 // Convert the 0.0-1.0 value back to a brightness integer. 2618 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2); 2619 if (val < minval) val = minval; 2620 else if (val > maxval) val = maxval; 2621 return val; 2622 } catch (Exception e) { 2623 // guard against null pointer or index out of bounds errors 2624 Slog.e(TAG, "Values array must be non-empty and must be one element longer than " 2625 + "the auto-brightness levels array. Check config.xml.", e); 2626 return 255; 2627 } 2628 } 2629 2630 private Runnable mProximityTask = new Runnable() { 2631 public void run() { 2632 synchronized (mLocks) { 2633 if (mProximityPendingValue != -1) { 2634 proximityChangedLocked(mProximityPendingValue == 1); 2635 mProximityPendingValue = -1; 2636 } 2637 if (mProximityPartialLock.isHeld()) { 2638 mProximityPartialLock.release(); 2639 } 2640 } 2641 } 2642 }; 2643 2644 private Runnable mAutoBrightnessTask = new Runnable() { 2645 public void run() { 2646 synchronized (mLocks) { 2647 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) { 2648 int value = (int)mLightSensorPendingValue; 2649 mLightSensorPendingDecrease = false; 2650 mLightSensorPendingIncrease = false; 2651 lightSensorChangedLocked(value, false); 2652 } 2653 } 2654 } 2655 }; 2656 2657 /** used to prevent lightsensor changes while turning on. */ 2658 private boolean mInitialAnimation = true; 2659 2660 private void dockStateChanged(int state) { 2661 synchronized (mLocks) { 2662 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED); 2663 if (mIsDocked) { 2664 // allow brightness to decrease when docked 2665 mHighestLightSensorValue = -1; 2666 } 2667 if ((mPowerState & SCREEN_ON_BIT) != 0) { 2668 // force lights recalculation 2669 int value = (int)mLightSensorValue; 2670 mLightSensorValue = -1; 2671 lightSensorChangedLocked(value, false); 2672 } 2673 } 2674 } 2675 2676 private void lightSensorChangedLocked(int value, boolean immediate) { 2677 if (DEBUG_LIGHT_SENSOR) { 2678 Slog.d(TAG, "lightSensorChangedLocked value=" + value + " immediate=" + immediate); 2679 } 2680 2681 // Don't do anything if the screen is off. 2682 if ((mPowerState & SCREEN_ON_BIT) == 0) { 2683 if (DEBUG_LIGHT_SENSOR) { 2684 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off"); 2685 } 2686 return; 2687 } 2688 2689 if (mLightSensorValue != value) { 2690 mLightSensorValue = value; 2691 if ((mPowerState & BATTERY_LOW_BIT) == 0) { 2692 // use maximum light sensor value seen since screen went on for LCD to avoid flicker 2693 // we only do this if we are undocked, since lighting should be stable when 2694 // stationary in a dock. 2695 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues); 2696 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues); 2697 int keyboardValue; 2698 if (mKeyboardVisible) { 2699 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues); 2700 } else { 2701 keyboardValue = 0; 2702 } 2703 mLightSensorScreenBrightness = lcdValue; 2704 mLightSensorButtonBrightness = buttonValue; 2705 mLightSensorKeyboardBrightness = keyboardValue; 2706 2707 if (DEBUG_LIGHT_SENSOR) { 2708 Slog.d(TAG, "lcdValue " + lcdValue); 2709 Slog.d(TAG, "buttonValue " + buttonValue); 2710 Slog.d(TAG, "keyboardValue " + keyboardValue); 2711 } 2712 2713 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) { 2714 if (!mSkippedScreenOn && !mInitialAnimation) { 2715 final int steps; 2716 if (immediate) { 2717 steps = IMMEDIATE_ANIM_STEPS; 2718 } else { 2719 synchronized (mScreenBrightnessAnimator) { 2720 if (mScreenBrightnessAnimator.currentValue <= lcdValue) { 2721 steps = AUTOBRIGHTNESS_ANIM_STEPS; 2722 } else { 2723 steps = AUTODIMNESS_ANIM_STEPS; 2724 } 2725 } 2726 } 2727 mScreenBrightnessAnimator.animateTo(lcdValue, value, 2728 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS); 2729 } 2730 } 2731 if (mButtonBrightnessOverride < 0) { 2732 mButtonLight.setBrightness(buttonValue); 2733 } 2734 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) { 2735 mKeyboardLight.setBrightness(keyboardValue); 2736 } 2737 } 2738 } 2739 } 2740 2741 /** 2742 * The user requested that we go to sleep (probably with the power button). 2743 * This overrides all wake locks that are held. 2744 */ 2745 public void goToSleep(long time) 2746 { 2747 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER); 2748 } 2749 2750 /** 2751 * The user requested that we go to sleep (probably with the power button). 2752 * This overrides all wake locks that are held. 2753 */ 2754 public void goToSleepWithReason(long time, int reason) 2755 { 2756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 2757 synchronized (mLocks) { 2758 goToSleepLocked(time, reason); 2759 } 2760 } 2761 2762 /** 2763 * Reboot the device immediately, passing 'reason' (may be null) 2764 * to the underlying __reboot system call. Should not return. 2765 */ 2766 public void reboot(String reason) 2767 { 2768 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 2769 2770 if (mHandler == null || !ActivityManagerNative.isSystemReady()) { 2771 throw new IllegalStateException("Too early to call reboot()"); 2772 } 2773 2774 final String finalReason = reason; 2775 Runnable runnable = new Runnable() { 2776 public void run() { 2777 synchronized (this) { 2778 ShutdownThread.reboot(mContext, finalReason, false); 2779 } 2780 2781 } 2782 }; 2783 // ShutdownThread must run on a looper capable of displaying the UI. 2784 mHandler.post(runnable); 2785 2786 // PowerManager.reboot() is documented not to return so just wait for the inevitable. 2787 synchronized (runnable) { 2788 while (true) { 2789 try { 2790 runnable.wait(); 2791 } catch (InterruptedException e) { 2792 } 2793 } 2794 } 2795 } 2796 2797 /** 2798 * Crash the runtime (causing a complete restart of the Android framework). 2799 * Requires REBOOT permission. Mostly for testing. Should not return. 2800 */ 2801 public void crash(final String message) 2802 { 2803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null); 2804 Thread t = new Thread("PowerManagerService.crash()") { 2805 public void run() { throw new RuntimeException(message); } 2806 }; 2807 try { 2808 t.start(); 2809 t.join(); 2810 } catch (InterruptedException e) { 2811 Log.wtf(TAG, e); 2812 } 2813 } 2814 2815 private void goToSleepLocked(long time, int reason) { 2816 if (DEBUG) { 2817 Exception ex = new Exception(); 2818 ex.fillInStackTrace(); 2819 Slog.d(TAG, "goToSleep mLastEventTime=" + mLastEventTime + " time=" + time 2820 + " reason=" + reason, ex); 2821 } 2822 2823 if (mLastEventTime <= time) { 2824 mLastEventTime = time; 2825 // cancel all of the wake locks 2826 mWakeLockState = SCREEN_OFF; 2827 int N = mLocks.size(); 2828 int numCleared = 0; 2829 boolean proxLock = false; 2830 for (int i=0; i<N; i++) { 2831 WakeLock wl = mLocks.get(i); 2832 if (isScreenLock(wl.flags)) { 2833 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) 2834 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) { 2835 proxLock = true; 2836 } else { 2837 mLocks.get(i).activated = false; 2838 numCleared++; 2839 } 2840 } 2841 } 2842 if (!proxLock) { 2843 mProxIgnoredBecauseScreenTurnedOff = true; 2844 if (DEBUG_PROXIMITY_SENSOR) { 2845 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff"); 2846 } 2847 } 2848 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared); 2849 mStillNeedSleepNotification = true; 2850 mUserState = SCREEN_OFF; 2851 setPowerState(SCREEN_OFF, false, reason); 2852 cancelTimerLocked(); 2853 } 2854 } 2855 2856 public long timeSinceScreenOn() { 2857 synchronized (mLocks) { 2858 if ((mPowerState & SCREEN_ON_BIT) != 0) { 2859 return 0; 2860 } 2861 return SystemClock.elapsedRealtime() - mScreenOffTime; 2862 } 2863 } 2864 2865 public void setKeyboardVisibility(boolean visible) { 2866 synchronized (mLocks) { 2867 if (DEBUG) { 2868 Slog.d(TAG, "setKeyboardVisibility: " + visible); 2869 } 2870 if (mKeyboardVisible != visible) { 2871 mKeyboardVisible = visible; 2872 // don't signal user activity if the screen is off; other code 2873 // will take care of turning on due to a true change to the lid 2874 // switch and synchronized with the lock screen. 2875 if ((mPowerState & SCREEN_ON_BIT) != 0) { 2876 if (mUseSoftwareAutoBrightness) { 2877 // force recompute of backlight values 2878 if (mLightSensorValue >= 0) { 2879 int value = (int)mLightSensorValue; 2880 mLightSensorValue = -1; 2881 lightSensorChangedLocked(value, false); 2882 } 2883 } 2884 userActivity(SystemClock.uptimeMillis(), false, PowerManager.USER_ACTIVITY_EVENT_BUTTON, true); 2885 } 2886 } 2887 } 2888 } 2889 2890 /** 2891 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything. 2892 * When disabling user activity we also reset user power state so the keyguard can reset its 2893 * short screen timeout when keyguard is unhidden. 2894 */ 2895 public void enableUserActivity(boolean enabled) { 2896 if (DEBUG) { 2897 Slog.d(TAG, "enableUserActivity " + enabled); 2898 } 2899 synchronized (mLocks) { 2900 mUserActivityAllowed = enabled; 2901 if (!enabled) { 2902 // cancel timeout and clear mUserState so the keyguard can set a short timeout 2903 setTimeoutLocked(SystemClock.uptimeMillis(), 0); 2904 } 2905 } 2906 } 2907 2908 private void setScreenBrightnessMode(int mode) { 2909 synchronized (mLocks) { 2910 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC); 2911 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) { 2912 mAutoBrightessEnabled = enabled; 2913 // This will get us a new value 2914 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn()); 2915 } 2916 } 2917 } 2918 2919 /** Sets the screen off timeouts: 2920 * mKeylightDelay 2921 * mDimDelay 2922 * mScreenOffDelay 2923 * */ 2924 private void setScreenOffTimeoutsLocked() { 2925 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) { 2926 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings 2927 mDimDelay = -1; 2928 mScreenOffDelay = 0; 2929 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) { 2930 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY; 2931 mDimDelay = -1; 2932 mScreenOffDelay = 0; 2933 } else { 2934 int totalDelay = mScreenOffTimeoutSetting; 2935 if (totalDelay > mMaximumScreenOffTimeout) { 2936 totalDelay = mMaximumScreenOffTimeout; 2937 } 2938 mKeylightDelay = LONG_KEYLIGHT_DELAY; 2939 if (totalDelay < 0) { 2940 // negative number means stay on as long as possible. 2941 mScreenOffDelay = mMaximumScreenOffTimeout; 2942 } else if (mKeylightDelay < totalDelay) { 2943 // subtract the time that the keylight delay. This will give us the 2944 // remainder of the time that we need to sleep to get the accurate 2945 // screen off timeout. 2946 mScreenOffDelay = totalDelay - mKeylightDelay; 2947 } else { 2948 mScreenOffDelay = 0; 2949 } 2950 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) { 2951 mDimDelay = mScreenOffDelay - LONG_DIM_TIME; 2952 mScreenOffDelay = LONG_DIM_TIME; 2953 } else { 2954 mDimDelay = -1; 2955 } 2956 } 2957 if (DEBUG) { 2958 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay 2959 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay 2960 + " mDimScreen=" + mDimScreen); 2961 } 2962 } 2963 2964 /** 2965 * Refreshes cached secure settings. Called once on startup, and 2966 * on subsequent changes to secure settings. 2967 */ 2968 private void updateSettingsValues() { 2969 mShortKeylightDelay = Settings.Secure.getInt( 2970 mContext.getContentResolver(), 2971 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS, 2972 SHORT_KEYLIGHT_DELAY_DEFAULT); 2973 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay); 2974 } 2975 2976 private class LockList extends ArrayList<WakeLock> 2977 { 2978 void addLock(WakeLock wl) 2979 { 2980 int index = getIndex(wl.binder); 2981 if (index < 0) { 2982 this.add(wl); 2983 } 2984 } 2985 2986 WakeLock removeLock(IBinder binder) 2987 { 2988 int index = getIndex(binder); 2989 if (index >= 0) { 2990 return this.remove(index); 2991 } else { 2992 return null; 2993 } 2994 } 2995 2996 int getIndex(IBinder binder) 2997 { 2998 int N = this.size(); 2999 for (int i=0; i<N; i++) { 3000 if (this.get(i).binder == binder) { 3001 return i; 3002 } 3003 } 3004 return -1; 3005 } 3006 3007 int gatherState() 3008 { 3009 int result = 0; 3010 int N = this.size(); 3011 for (int i=0; i<N; i++) { 3012 WakeLock wl = this.get(i); 3013 if (wl.activated) { 3014 if (isScreenLock(wl.flags)) { 3015 result |= wl.minState; 3016 } 3017 } 3018 } 3019 return result; 3020 } 3021 3022 int reactivateScreenLocksLocked() 3023 { 3024 int result = 0; 3025 int N = this.size(); 3026 for (int i=0; i<N; i++) { 3027 WakeLock wl = this.get(i); 3028 if (isScreenLock(wl.flags)) { 3029 wl.activated = true; 3030 result |= wl.minState; 3031 } 3032 } 3033 if (DEBUG_PROXIMITY_SENSOR) { 3034 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff=" 3035 + mProxIgnoredBecauseScreenTurnedOff); 3036 } 3037 mProxIgnoredBecauseScreenTurnedOff = false; 3038 return result; 3039 } 3040 } 3041 3042 public void setPolicy(WindowManagerPolicy p) { 3043 synchronized (mLocks) { 3044 mPolicy = p; 3045 mLocks.notifyAll(); 3046 } 3047 } 3048 3049 WindowManagerPolicy getPolicyLocked() { 3050 while (mPolicy == null || !mDoneBooting) { 3051 try { 3052 mLocks.wait(); 3053 } catch (InterruptedException e) { 3054 // Ignore 3055 } 3056 } 3057 return mPolicy; 3058 } 3059 3060 public void systemReady() { 3061 mSensorManager = new SystemSensorManager(mHandlerThread.getLooper()); 3062 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); 3063 // don't bother with the light sensor if auto brightness is handled in hardware 3064 if (mUseSoftwareAutoBrightness) { 3065 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); 3066 } 3067 3068 // wait until sensors are enabled before turning on screen. 3069 // some devices will not activate the light sensor properly on boot 3070 // unless we do this. 3071 if (mUseSoftwareAutoBrightness) { 3072 // turn the screen on 3073 setPowerState(SCREEN_BRIGHT); 3074 } else { 3075 // turn everything on 3076 setPowerState(ALL_BRIGHT); 3077 } 3078 3079 synchronized (mLocks) { 3080 Slog.d(TAG, "system ready!"); 3081 mDoneBooting = true; 3082 3083 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled); 3084 3085 long identity = Binder.clearCallingIdentity(); 3086 try { 3087 mBatteryStats.noteScreenBrightness(getPreferredBrightness()); 3088 mBatteryStats.noteScreenOn(); 3089 } catch (RemoteException e) { 3090 // Nothing interesting to do. 3091 } finally { 3092 Binder.restoreCallingIdentity(identity); 3093 } 3094 } 3095 } 3096 3097 void bootCompleted() { 3098 Slog.d(TAG, "bootCompleted"); 3099 synchronized (mLocks) { 3100 mBootCompleted = true; 3101 userActivity(SystemClock.uptimeMillis(), false, PowerManager.USER_ACTIVITY_EVENT_BUTTON, true); 3102 updateWakeLockLocked(); 3103 mLocks.notifyAll(); 3104 } 3105 } 3106 3107 // for watchdog 3108 public void monitor() { 3109 synchronized (mLocks) { } 3110 } 3111 3112 public int getSupportedWakeLockFlags() { 3113 int result = PowerManager.PARTIAL_WAKE_LOCK 3114 | PowerManager.FULL_WAKE_LOCK 3115 | PowerManager.SCREEN_DIM_WAKE_LOCK; 3116 3117 if (mProximitySensor != null) { 3118 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK; 3119 } 3120 3121 return result; 3122 } 3123 3124 public void setBacklightBrightness(int brightness) { 3125 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 3126 // Don't let applications turn the screen all the way off 3127 synchronized (mLocks) { 3128 brightness = Math.max(brightness, mScreenBrightnessDim); 3129 mLcdLight.setBrightness(brightness); 3130 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0); 3131 mButtonLight.setBrightness(brightness); 3132 long identity = Binder.clearCallingIdentity(); 3133 try { 3134 mBatteryStats.noteScreenBrightness(brightness); 3135 } catch (RemoteException e) { 3136 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e); 3137 } finally { 3138 Binder.restoreCallingIdentity(identity); 3139 } 3140 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0); 3141 } 3142 } 3143 3144 public void setAutoBrightnessAdjustment(float adj) { 3145 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 3146 synchronized (mLocks) { 3147 mLightSensorAdjustSetting = adj; 3148 if (mSensorManager != null && mLightSensorEnabled) { 3149 // clear calling identity so sensor manager battery stats are accurate 3150 long identity = Binder.clearCallingIdentity(); 3151 try { 3152 // force recompute of backlight values 3153 if (mLightSensorValue >= 0) { 3154 int value = (int)mLightSensorValue; 3155 mLightSensorValue = -1; 3156 handleLightSensorValue(value, true); 3157 } 3158 } finally { 3159 Binder.restoreCallingIdentity(identity); 3160 } 3161 } 3162 } 3163 } 3164 3165 public void setAttentionLight(boolean on, int color) { 3166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null); 3167 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0); 3168 } 3169 3170 private void enableProximityLockLocked() { 3171 if (DEBUG_PROXIMITY_SENSOR) { 3172 Slog.d(TAG, "enableProximityLockLocked"); 3173 } 3174 if (!mProximitySensorEnabled) { 3175 // clear calling identity so sensor manager battery stats are accurate 3176 long identity = Binder.clearCallingIdentity(); 3177 try { 3178 mSensorManager.registerListener(mProximityListener, mProximitySensor, 3179 SensorManager.SENSOR_DELAY_NORMAL); 3180 mProximitySensorEnabled = true; 3181 } finally { 3182 Binder.restoreCallingIdentity(identity); 3183 } 3184 } 3185 } 3186 3187 private void disableProximityLockLocked() { 3188 if (DEBUG_PROXIMITY_SENSOR) { 3189 Slog.d(TAG, "disableProximityLockLocked"); 3190 } 3191 if (mProximitySensorEnabled) { 3192 // clear calling identity so sensor manager battery stats are accurate 3193 long identity = Binder.clearCallingIdentity(); 3194 try { 3195 mSensorManager.unregisterListener(mProximityListener); 3196 mHandler.removeCallbacks(mProximityTask); 3197 if (mProximityPartialLock.isHeld()) { 3198 mProximityPartialLock.release(); 3199 } 3200 mProximitySensorEnabled = false; 3201 } finally { 3202 Binder.restoreCallingIdentity(identity); 3203 } 3204 if (mProximitySensorActive) { 3205 mProximitySensorActive = false; 3206 if (DEBUG_PROXIMITY_SENSOR) { 3207 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff=" 3208 + mProxIgnoredBecauseScreenTurnedOff); 3209 } 3210 if (!mProxIgnoredBecauseScreenTurnedOff) { 3211 forceUserActivityLocked(); 3212 } 3213 } 3214 } 3215 } 3216 3217 private void proximityChangedLocked(boolean active) { 3218 if (DEBUG_PROXIMITY_SENSOR) { 3219 Slog.d(TAG, "proximityChangedLocked, active: " + active); 3220 } 3221 if (!mProximitySensorEnabled) { 3222 Slog.d(TAG, "Ignoring proximity change after sensor is disabled"); 3223 return; 3224 } 3225 if (active) { 3226 if (DEBUG_PROXIMITY_SENSOR) { 3227 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff=" 3228 + mProxIgnoredBecauseScreenTurnedOff); 3229 } 3230 if (!mProxIgnoredBecauseScreenTurnedOff) { 3231 goToSleepLocked(SystemClock.uptimeMillis(), 3232 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR); 3233 } 3234 mProximitySensorActive = true; 3235 } else { 3236 // proximity sensor negative events trigger as user activity. 3237 // temporarily set mUserActivityAllowed to true so this will work 3238 // even when the keyguard is on. 3239 mProximitySensorActive = false; 3240 if (DEBUG_PROXIMITY_SENSOR) { 3241 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff=" 3242 + mProxIgnoredBecauseScreenTurnedOff); 3243 } 3244 if (!mProxIgnoredBecauseScreenTurnedOff) { 3245 forceUserActivityLocked(); 3246 } 3247 3248 if (mProximityWakeLockCount == 0) { 3249 // disable sensor if we have no listeners left after proximity negative 3250 disableProximityLockLocked(); 3251 } 3252 } 3253 } 3254 3255 private void enableLightSensorLocked(boolean enable) { 3256 if (DEBUG_LIGHT_SENSOR) { 3257 Slog.d(TAG, "enableLightSensorLocked enable=" + enable 3258 + " mLightSensorEnabled=" + mLightSensorEnabled 3259 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled 3260 + " mWaitingForFirstLightSensor=" + mWaitingForFirstLightSensor); 3261 } 3262 if (!mAutoBrightessEnabled) { 3263 enable = false; 3264 } 3265 if (mSensorManager != null && mLightSensorEnabled != enable) { 3266 mLightSensorEnabled = enable; 3267 // clear calling identity so sensor manager battery stats are accurate 3268 long identity = Binder.clearCallingIdentity(); 3269 try { 3270 if (enable) { 3271 // reset our highest value when reenabling 3272 mHighestLightSensorValue = -1; 3273 // force recompute of backlight values 3274 final int value = (int)mLightSensorValue; 3275 if (value >= 0) { 3276 mLightSensorValue = -1; 3277 handleLightSensorValue(value, true); 3278 } 3279 mSensorManager.registerListener(mLightListener, mLightSensor, 3280 LIGHT_SENSOR_RATE); 3281 } else { 3282 mSensorManager.unregisterListener(mLightListener); 3283 mHandler.removeCallbacks(mAutoBrightnessTask); 3284 mLightSensorPendingDecrease = false; 3285 mLightSensorPendingIncrease = false; 3286 } 3287 } finally { 3288 Binder.restoreCallingIdentity(identity); 3289 } 3290 } 3291 } 3292 3293 SensorEventListener mProximityListener = new SensorEventListener() { 3294 public void onSensorChanged(SensorEvent event) { 3295 long milliseconds = SystemClock.elapsedRealtime(); 3296 synchronized (mLocks) { 3297 float distance = event.values[0]; 3298 long timeSinceLastEvent = milliseconds - mLastProximityEventTime; 3299 mLastProximityEventTime = milliseconds; 3300 mHandler.removeCallbacks(mProximityTask); 3301 boolean proximityTaskQueued = false; 3302 3303 // compare against getMaximumRange to support sensors that only return 0 or 1 3304 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD && 3305 distance < mProximitySensor.getMaximumRange()); 3306 3307 if (DEBUG_PROXIMITY_SENSOR) { 3308 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active); 3309 } 3310 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) { 3311 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing 3312 mProximityPendingValue = (active ? 1 : 0); 3313 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent); 3314 proximityTaskQueued = true; 3315 } else { 3316 // process the value immediately 3317 mProximityPendingValue = -1; 3318 proximityChangedLocked(active); 3319 } 3320 3321 // update mProximityPartialLock state 3322 boolean held = mProximityPartialLock.isHeld(); 3323 if (!held && proximityTaskQueued) { 3324 // hold wakelock until mProximityTask runs 3325 mProximityPartialLock.acquire(); 3326 } else if (held && !proximityTaskQueued) { 3327 mProximityPartialLock.release(); 3328 } 3329 } 3330 } 3331 3332 public void onAccuracyChanged(Sensor sensor, int accuracy) { 3333 // ignore 3334 } 3335 }; 3336 3337 private void handleLightSensorValue(int value, boolean immediate) { 3338 long milliseconds = SystemClock.elapsedRealtime(); 3339 if (mLightSensorValue == -1 3340 || milliseconds < mLastScreenOnTime + mLightSensorWarmupTime 3341 || mWaitingForFirstLightSensor) { 3342 // process the value immediately if screen has just turned on 3343 mHandler.removeCallbacks(mAutoBrightnessTask); 3344 mLightSensorPendingDecrease = false; 3345 mLightSensorPendingIncrease = false; 3346 lightSensorChangedLocked(value, immediate); 3347 } else { 3348 if ((value > mLightSensorValue && mLightSensorPendingDecrease) || 3349 (value < mLightSensorValue && mLightSensorPendingIncrease) || 3350 (value == mLightSensorValue) || 3351 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) { 3352 // delay processing to debounce the sensor 3353 mHandler.removeCallbacks(mAutoBrightnessTask); 3354 mLightSensorPendingDecrease = (value < mLightSensorValue); 3355 mLightSensorPendingIncrease = (value > mLightSensorValue); 3356 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) { 3357 mLightSensorPendingValue = value; 3358 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY); 3359 } 3360 } else { 3361 mLightSensorPendingValue = value; 3362 } 3363 } 3364 } 3365 3366 SensorEventListener mLightListener = new SensorEventListener() { 3367 @Override 3368 public void onSensorChanged(SensorEvent event) { 3369 if (DEBUG_LIGHT_SENSOR) { 3370 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]); 3371 } 3372 synchronized (mLocks) { 3373 // ignore light sensor while screen is turning off 3374 if (isScreenTurningOffLocked()) { 3375 return; 3376 } 3377 handleLightSensorValue((int)event.values[0], mWaitingForFirstLightSensor); 3378 if (mWaitingForFirstLightSensor && !mPreparingForScreenOn) { 3379 if (DEBUG_LIGHT_ANIMATION) { 3380 Slog.d(TAG, "onSensorChanged: Clearing mWaitingForFirstLightSensor."); 3381 } 3382 mWaitingForFirstLightSensor = false; 3383 } 3384 } 3385 } 3386 3387 @Override 3388 public void onAccuracyChanged(Sensor sensor, int accuracy) { 3389 // ignore 3390 } 3391 }; 3392} 3393