blob: 7bbc32ffec2868eb2555eae501141b0e66e17a71 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070032import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070035import android.hardware.Sensor;
36import android.hardware.SensorEvent;
37import android.hardware.SensorEventListener;
38import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.BatteryStats;
40import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080041import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.IPowerManager;
46import android.os.LocalPowerManager;
47import android.os.Power;
48import android.os.PowerManager;
49import android.os.Process;
50import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080051import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.provider.Settings.SettingNotFoundException;
54import android.provider.Settings;
55import android.util.EventLog;
56import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080057import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.view.WindowManagerPolicy;
59import static android.provider.Settings.System.DIM_SCREEN;
60import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050061import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
64import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
65
66import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080067import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.PrintWriter;
69import java.util.ArrayList;
70import java.util.HashMap;
71import java.util.Observable;
72import java.util.Observer;
73
Mike Lockwoodbc706a02009-07-27 13:50:57 -070074class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040075 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
77 private static final String TAG = "PowerManagerService";
78 static final String PARTIAL_NAME = "PowerManagerService";
79
80 private static final boolean LOG_PARTIAL_WL = false;
81
82 // Indicates whether touch-down cycles should be logged as part of the
83 // LOG_POWER_SCREEN_STATE log events
84 private static final boolean LOG_TOUCH_DOWNS = true;
85
86 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
87 | PowerManager.SCREEN_DIM_WAKE_LOCK
88 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070089 | PowerManager.FULL_WAKE_LOCK
90 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
92 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080093 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
95 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
96 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
97 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
98
Mike Lockwoodd7786b42009-10-15 17:09:16 -070099 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500100 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101
Mike Lockwood20f87d72009-11-05 16:08:51 -0500102 // For debouncing the proximity sensor.
103 private static final int PROXIMITY_SENSOR_DELAY = 1000;
104
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400105 // trigger proximity if distance is less than 5 cm
106 private static final float PROXIMITY_THRESHOLD = 5.0f;
107
Doug Zongker43866e02010-01-07 12:09:54 -0800108 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
110
111 // flags for setPowerState
112 private static final int SCREEN_ON_BIT = 0x00000001;
113 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
114 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
115 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
116 private static final int BATTERY_LOW_BIT = 0x00000010;
117
118 // values for setPowerState
119
120 // SCREEN_OFF == everything off
121 private static final int SCREEN_OFF = 0x00000000;
122
123 // SCREEN_DIM == screen on, screen backlight dim
124 private static final int SCREEN_DIM = SCREEN_ON_BIT;
125
126 // SCREEN_BRIGHT == screen on, screen backlight bright
127 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
128
129 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
130 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
131
132 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
133 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
134
135 // used for noChangeLights in setPowerState()
136 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
137
138 static final boolean ANIMATE_SCREEN_LIGHTS = true;
139 static final boolean ANIMATE_BUTTON_LIGHTS = false;
140 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400143 // Slower animation for autobrightness changes
144 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 // These magic numbers are the initial state of the LEDs at boot. Ideally
147 // we should read them from the driver, but our current hardware returns 0
148 // for the initial value. Oops!
149 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
150 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
151 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 private final int MY_UID;
154
155 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500156 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500158 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
161 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500162 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
163 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
164 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mUserState;
166 private boolean mKeyboardVisible = false;
167 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500168 private int mProximityWakeLockCount = 0;
169 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700170 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500171 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
172 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800173 private int mScreenOffTimeoutSetting;
174 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 private int mKeylightDelay;
176 private int mDimDelay;
177 private int mScreenOffDelay;
178 private int mWakeLockState;
179 private long mLastEventTime = 0;
180 private long mScreenOffTime;
181 private volatile WindowManagerPolicy mPolicy;
182 private final LockList mLocks = new LockList();
183 private Intent mScreenOffIntent;
184 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500185 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500187 private LightsService.Light mLcdLight;
188 private LightsService.Light mButtonLight;
189 private LightsService.Light mKeyboardLight;
190 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private UnsynchronizedWakeLock mBroadcastWakeLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
193 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
194 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500195 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private HandlerThread mHandlerThread;
197 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500198 private final TimeoutTask mTimeoutTask = new TimeoutTask();
199 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700201 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700203 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700205 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700206 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private boolean mIsPowered = false;
208 private IActivityManager mActivityService;
209 private IBatteryStats mBatteryStats;
210 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700211 private SensorManager mSensorManager;
212 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400213 private Sensor mLightSensor;
214 private boolean mLightSensorEnabled;
215 private float mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500216 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700217 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500218 private int mLightSensorScreenBrightness = -1;
219 private int mLightSensorButtonBrightness = -1;
220 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500222 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private long mNextTimeout;
224 private volatile int mPokey = 0;
225 private volatile boolean mPokeAwakeOnSet = false;
226 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500227 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500228 // mLastScreenOnTime is the time the screen was last turned on
229 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private boolean mPreventScreenOn;
231 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500232 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400233 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700234 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700235 private int[] mAutoBrightnessLevels;
236 private int[] mLcdBacklightValues;
237 private int[] mButtonBacklightValues;
238 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500239 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 // Used when logging number and duration of touch-down cycles
242 private long mTotalTouchDownTime;
243 private long mLastTouchDown;
244 private int mTouchCycles;
245
246 // could be either static or controllable at runtime
247 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500248 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400249 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 /*
252 static PrintStream mLog;
253 static {
254 try {
255 mLog = new PrintStream("/data/power.log");
256 }
257 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800258 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 }
260 }
261 static class Log {
262 static void d(String tag, String s) {
263 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800264 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266 static void i(String tag, String s) {
267 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800268 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270 static void w(String tag, String s) {
271 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
274 static void e(String tag, String s) {
275 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800276 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278 }
279 */
280
281 /**
282 * This class works around a deadlock between the lock in PowerManager.WakeLock
283 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
284 * mToken object so it can be accessed from any thread, but it calls into here
285 * with its lock held. This class is essentially a reimplementation of
286 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
287 * only call it with our own locks held.
288 */
289 private class UnsynchronizedWakeLock {
290 int mFlags;
291 String mTag;
292 IBinder mToken;
293 int mCount = 0;
294 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500295 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296
297 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
298 mFlags = flags;
299 mTag = tag;
300 mToken = new Binder();
301 mRefCounted = refCounted;
302 }
303
304 public void acquire() {
305 if (!mRefCounted || mCount++ == 0) {
306 long ident = Binder.clearCallingIdentity();
307 try {
308 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
309 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500310 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 } finally {
312 Binder.restoreCallingIdentity(ident);
313 }
314 }
315 }
316
317 public void release() {
318 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500319 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322 if (mCount < 0) {
323 throw new RuntimeException("WakeLock under-locked " + mTag);
324 }
325 }
326
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500327 public boolean isHeld()
328 {
329 return mHeld;
330 }
331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public String toString() {
333 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500334 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336 }
337
338 private final class BatteryReceiver extends BroadcastReceiver {
339 @Override
340 public void onReceive(Context context, Intent intent) {
341 synchronized (mLocks) {
342 boolean wasPowered = mIsPowered;
343 mIsPowered = mBatteryService.isPowered();
344
345 if (mIsPowered != wasPowered) {
346 // update mStayOnWhilePluggedIn wake lock
347 updateWakeLockLocked();
348
349 // treat plugging and unplugging the devices as a user activity.
350 // users find it disconcerting when they unplug the device
351 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500352 // to avoid turning on the screen when unplugging, we only trigger
353 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 // temporarily set mUserActivityAllowed to true so this will work
355 // even when the keyguard is on.
356 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500357 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
358 forceUserActivityLocked();
359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361 }
362 }
363 }
364 }
365
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500366 private final class BootCompletedReceiver extends BroadcastReceiver {
367 @Override
368 public void onReceive(Context context, Intent intent) {
369 bootCompleted();
370 }
371 }
372
Mike Lockwoodb2865412010-02-02 22:40:33 -0500373 private final class DockReceiver extends BroadcastReceiver {
374 @Override
375 public void onReceive(Context context, Intent intent) {
376 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
377 Intent.EXTRA_DOCK_STATE_UNDOCKED);
378 dockStateChanged(state);
379 }
380 }
381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 /**
383 * Set the setting that determines whether the device stays on when plugged in.
384 * The argument is a bit string, with each bit specifying a power source that,
385 * when the device is connected to that source, causes the device to stay on.
386 * See {@link android.os.BatteryManager} for the list of power sources that
387 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
388 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
389 * @param val an {@code int} containing the bits that specify which power sources
390 * should cause the device to stay on.
391 */
392 public void setStayOnSetting(int val) {
393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
394 Settings.System.putInt(mContext.getContentResolver(),
395 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
396 }
397
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800398 public void setMaximumScreenOffTimeount(int timeMs) {
399 mContext.enforceCallingOrSelfPermission(
400 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
401 synchronized (mLocks) {
402 mMaximumScreenOffTimeout = timeMs;
403 // recalculate everything
404 setScreenOffTimeoutsLocked();
405 }
406 }
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 private class SettingsObserver implements Observer {
409 private int getInt(String name) {
410 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
411 }
412
413 public void update(Observable o, Object arg) {
414 synchronized (mLocks) {
415 // STAY_ON_WHILE_PLUGGED_IN
416 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
417 updateWakeLockLocked();
418
419 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800420 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421
422 // DIM_SCREEN
423 //mDimScreen = getInt(DIM_SCREEN) != 0;
424
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700425 // SCREEN_BRIGHTNESS_MODE
426 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 // recalculate everything
429 setScreenOffTimeoutsLocked();
430 }
431 }
432 }
433
434 PowerManagerService()
435 {
436 // Hack to get our uid... should have a func for this.
437 long token = Binder.clearCallingIdentity();
438 MY_UID = Binder.getCallingUid();
439 Binder.restoreCallingIdentity(token);
440
441 // XXX remove this when the kernel doesn't timeout wake locks
442 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
443
444 // assume nothing is on yet
445 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 // Add ourself to the Watchdog monitors.
448 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
451 private ContentQueryMap mSettings;
452
Mike Lockwood3a322132009-11-24 00:30:52 -0500453 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700454 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500455 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 mContext = context;
457 mActivityService = activity;
458 mBatteryStats = BatteryStatsService.getService();
459 mBatteryService = battery;
460
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500461 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
462 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
463 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
464 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 mHandlerThread = new HandlerThread("PowerManagerService") {
467 @Override
468 protected void onLooperPrepared() {
469 super.onLooperPrepared();
470 initInThread();
471 }
472 };
473 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 synchronized (mHandlerThread) {
476 while (!mInitComplete) {
477 try {
478 mHandlerThread.wait();
479 } catch (InterruptedException e) {
480 // Ignore
481 }
482 }
483 }
484 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 void initInThread() {
487 mHandler = new Handler();
488
489 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700490 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
492 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
493 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
494 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
495 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
496 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500497 mProximityPartialLock = new UnsynchronizedWakeLock(
498 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499
500 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
501 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
502 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
503 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
504
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700505 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400506
507 // read settings for auto-brightness
508 mUseSoftwareAutoBrightness = resources.getBoolean(
509 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400510 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700511 mAutoBrightnessLevels = resources.getIntArray(
512 com.android.internal.R.array.config_autoBrightnessLevels);
513 mLcdBacklightValues = resources.getIntArray(
514 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
515 mButtonBacklightValues = resources.getIntArray(
516 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
517 mKeyboardBacklightValues = resources.getIntArray(
518 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500519 mLightSensorWarmupTime = resources.getInteger(
520 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700521 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700522
523 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
525 "(" + Settings.System.NAME + "=?) or ("
526 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700527 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700529 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
530 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 null);
532 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
533 SettingsObserver settingsObserver = new SettingsObserver();
534 mSettings.addObserver(settingsObserver);
535
536 // pretend that the settings changed so we will get their initial state
537 settingsObserver.update(mSettings, null);
538
539 // register for the battery changed notifications
540 IntentFilter filter = new IntentFilter();
541 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
542 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500543 filter = new IntentFilter();
544 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
545 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500546 filter = new IntentFilter();
547 filter.addAction(Intent.ACTION_DOCK_EVENT);
548 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
Doug Zongker43866e02010-01-07 12:09:54 -0800550 // Listen for secure settings changes
551 mContext.getContentResolver().registerContentObserver(
552 Settings.Secure.CONTENT_URI, true,
553 new ContentObserver(new Handler()) {
554 public void onChange(boolean selfChange) {
555 updateSettingsValues();
556 }
557 });
558 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 synchronized (mHandlerThread) {
561 mInitComplete = true;
562 mHandlerThread.notifyAll();
563 }
564 }
565
566 private class WakeLock implements IBinder.DeathRecipient
567 {
568 WakeLock(int f, IBinder b, String t, int u) {
569 super();
570 flags = f;
571 binder = b;
572 tag = t;
573 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400574 pid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 if (u != MY_UID || (
576 !"KEEP_SCREEN_ON_FLAG".equals(tag)
577 && !"KeyInputQueue".equals(tag))) {
578 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
579 ? BatteryStats.WAKE_TYPE_PARTIAL
580 : BatteryStats.WAKE_TYPE_FULL;
581 } else {
582 monitorType = -1;
583 }
584 try {
585 b.linkToDeath(this, 0);
586 } catch (RemoteException e) {
587 binderDied();
588 }
589 }
590 public void binderDied() {
591 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500592 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
594 }
595 final int flags;
596 final IBinder binder;
597 final String tag;
598 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400599 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 final int monitorType;
601 boolean activated = true;
602 int minState;
603 }
604
605 private void updateWakeLockLocked() {
606 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
607 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
608 mStayOnWhilePluggedInScreenDimLock.acquire();
609 mStayOnWhilePluggedInPartialLock.acquire();
610 } else {
611 mStayOnWhilePluggedInScreenDimLock.release();
612 mStayOnWhilePluggedInPartialLock.release();
613 }
614 }
615
616 private boolean isScreenLock(int flags)
617 {
618 int n = flags & LOCK_MASK;
619 return n == PowerManager.FULL_WAKE_LOCK
620 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
621 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
622 }
623
624 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700626 if (uid != Process.myUid()) {
627 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 long ident = Binder.clearCallingIdentity();
630 try {
631 synchronized (mLocks) {
632 acquireWakeLockLocked(flags, lock, uid, tag);
633 }
634 } finally {
635 Binder.restoreCallingIdentity(ident);
636 }
637 }
638
639 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
640 int acquireUid = -1;
641 String acquireName = null;
642 int acquireType = -1;
643
644 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800645 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647
648 int index = mLocks.getIndex(lock);
649 WakeLock wl;
650 boolean newlock;
651 if (index < 0) {
652 wl = new WakeLock(flags, lock, tag, uid);
653 switch (wl.flags & LOCK_MASK)
654 {
655 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500656 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400657 wl.minState = SCREEN_BRIGHT;
658 } else {
659 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 break;
662 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
663 wl.minState = SCREEN_BRIGHT;
664 break;
665 case PowerManager.SCREEN_DIM_WAKE_LOCK:
666 wl.minState = SCREEN_DIM;
667 break;
668 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700669 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 break;
671 default:
672 // just log and bail. we're in the server, so don't
673 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 + " flags=" + flags);
676 return;
677 }
678 mLocks.addLock(wl);
679 newlock = true;
680 } else {
681 wl = mLocks.get(index);
682 newlock = false;
683 }
684 if (isScreenLock(flags)) {
685 // if this causes a wakeup, we reactivate all of the locks and
686 // set it to whatever they want. otherwise, we modulate that
687 // by the current state so we never turn it more on than
688 // it already is.
689 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700690 int oldWakeLockState = mWakeLockState;
691 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800693 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700694 + " mWakeLockState=0x"
695 + Integer.toHexString(mWakeLockState)
696 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 } else {
699 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800700 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 + " mLocks.gatherState()=0x"
702 + Integer.toHexString(mLocks.gatherState())
703 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
704 }
705 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
706 }
707 setPowerState(mWakeLockState | mUserState);
708 }
709 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
710 if (newlock) {
711 mPartialCount++;
712 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800713 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715 }
716 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700717 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500718 mProximityWakeLockCount++;
719 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700720 enableProximityLockLocked();
721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723 if (newlock) {
724 acquireUid = wl.uid;
725 acquireName = wl.tag;
726 acquireType = wl.monitorType;
727 }
728
729 if (acquireType >= 0) {
730 try {
731 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
732 } catch (RemoteException e) {
733 // Ignore
734 }
735 }
736 }
737
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500738 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700739 int uid = Binder.getCallingUid();
740 if (uid != Process.myUid()) {
741 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743
744 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500745 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747 }
748
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500749 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 int releaseUid;
751 String releaseName;
752 int releaseType;
753
754 WakeLock wl = mLocks.removeLock(lock);
755 if (wl == null) {
756 return;
757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800760 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
762 }
763
764 if (isScreenLock(wl.flags)) {
765 mWakeLockState = mLocks.gatherState();
766 // goes in the middle to reduce flicker
767 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
768 userActivity(SystemClock.uptimeMillis(), false);
769 }
770 setPowerState(mWakeLockState | mUserState);
771 }
772 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
773 mPartialCount--;
774 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800775 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 Power.releaseWakeLock(PARTIAL_NAME);
777 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700778 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500779 mProximityWakeLockCount--;
780 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500781 if (mProximitySensorActive &&
782 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500783 // wait for proximity sensor to go negative before disabling sensor
784 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800785 Slog.d(TAG, "waiting for proximity sensor to go negative");
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500786 }
787 } else {
788 disableProximityLockLocked();
789 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 // Unlink the lock from the binder.
793 wl.binder.unlinkToDeath(wl, 0);
794 releaseUid = wl.uid;
795 releaseName = wl.tag;
796 releaseType = wl.monitorType;
797
798 if (releaseType >= 0) {
799 long origId = Binder.clearCallingIdentity();
800 try {
801 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
802 } catch (RemoteException e) {
803 // Ignore
804 } finally {
805 Binder.restoreCallingIdentity(origId);
806 }
807 }
808 }
809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 private class PokeLock implements IBinder.DeathRecipient
811 {
812 PokeLock(int p, IBinder b, String t) {
813 super();
814 this.pokey = p;
815 this.binder = b;
816 this.tag = t;
817 try {
818 b.linkToDeath(this, 0);
819 } catch (RemoteException e) {
820 binderDied();
821 }
822 }
823 public void binderDied() {
824 setPokeLock(0, this.binder, this.tag);
825 }
826 int pokey;
827 IBinder binder;
828 String tag;
829 boolean awakeOnSet;
830 }
831
832 public void setPokeLock(int pokey, IBinder token, String tag) {
833 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
834 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800835 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 return;
837 }
838
839 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
840 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
841 + " and POKE_LOCK_MEDIUM_TIMEOUT");
842 }
843
844 synchronized (mLocks) {
845 if (pokey != 0) {
846 PokeLock p = mPokeLocks.get(token);
847 int oldPokey = 0;
848 if (p != null) {
849 oldPokey = p.pokey;
850 p.pokey = pokey;
851 } else {
852 p = new PokeLock(pokey, token, tag);
853 mPokeLocks.put(token, p);
854 }
855 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
856 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
857 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
858 p.awakeOnSet = true;
859 }
860 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700861 PokeLock rLock = mPokeLocks.remove(token);
862 if (rLock != null) {
863 token.unlinkToDeath(rLock, 0);
864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 }
866
867 int oldPokey = mPokey;
868 int cumulative = 0;
869 boolean oldAwakeOnSet = mPokeAwakeOnSet;
870 boolean awakeOnSet = false;
871 for (PokeLock p: mPokeLocks.values()) {
872 cumulative |= p.pokey;
873 if (p.awakeOnSet) {
874 awakeOnSet = true;
875 }
876 }
877 mPokey = cumulative;
878 mPokeAwakeOnSet = awakeOnSet;
879
880 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
881 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 if (oldCumulativeTimeout != newCumulativeTimeout) {
884 setScreenOffTimeoutsLocked();
885 // reset the countdown timer, but use the existing nextState so it doesn't
886 // change anything
887 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
888 }
889 }
890 }
891
892 private static String lockType(int type)
893 {
894 switch (type)
895 {
896 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700897 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700899 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700901 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700903 return "PARTIAL_WAKE_LOCK ";
904 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
905 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 default:
David Brown251faa62009-08-02 22:04:36 -0700907 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909 }
910
911 private static String dumpPowerState(int state) {
912 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
913 ? "KEYBOARD_BRIGHT_BIT " : "")
914 + (((state & SCREEN_BRIGHT_BIT) != 0)
915 ? "SCREEN_BRIGHT_BIT " : "")
916 + (((state & SCREEN_ON_BIT) != 0)
917 ? "SCREEN_ON_BIT " : "")
918 + (((state & BATTERY_LOW_BIT) != 0)
919 ? "BATTERY_LOW_BIT " : "");
920 }
921
922 @Override
923 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
924 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
925 != PackageManager.PERMISSION_GRANTED) {
926 pw.println("Permission Denial: can't dump PowerManager from from pid="
927 + Binder.getCallingPid()
928 + ", uid=" + Binder.getCallingUid());
929 return;
930 }
931
932 long now = SystemClock.uptimeMillis();
933
Mike Lockwoodca44df82010-02-25 13:48:49 -0500934 synchronized (mLocks) {
935 pw.println("Power Manager State:");
936 pw.println(" mIsPowered=" + mIsPowered
937 + " mPowerState=" + mPowerState
938 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
939 + " ms");
940 pw.println(" mPartialCount=" + mPartialCount);
941 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
942 pw.println(" mUserState=" + dumpPowerState(mUserState));
943 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
944 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
945 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
946 + " " + ((mNextTimeout-now)/1000) + "s from now");
947 pw.println(" mDimScreen=" + mDimScreen
948 + " mStayOnConditions=" + mStayOnConditions);
949 pw.println(" mScreenOffReason=" + mScreenOffReason
950 + " mUserState=" + mUserState);
951 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
952 + ',' + mBroadcastQueue[2] + "}");
953 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
954 + ',' + mBroadcastWhy[2] + "}");
955 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
956 pw.println(" mKeyboardVisible=" + mKeyboardVisible
957 + " mUserActivityAllowed=" + mUserActivityAllowed);
958 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
959 + " mScreenOffDelay=" + mScreenOffDelay);
960 pw.println(" mPreventScreenOn=" + mPreventScreenOn
961 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
962 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
963 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
964 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
965 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
966 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
967 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
968 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
969 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
970 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
971 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
972 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
973 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
974 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
975 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
976 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
977 pw.println(" mLightSensorValue=" + mLightSensorValue
978 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
979 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
980 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
981 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
982 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
983 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
984 mScreenBrightness.dump(pw, " mScreenBrightness: ");
985 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
986 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800987
Mike Lockwoodca44df82010-02-25 13:48:49 -0500988 int N = mLocks.size();
989 pw.println();
990 pw.println("mLocks.size=" + N + ":");
991 for (int i=0; i<N; i++) {
992 WakeLock wl = mLocks.get(i);
993 String type = lockType(wl.flags & LOCK_MASK);
994 String acquireCausesWakeup = "";
995 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
996 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
997 }
998 String activated = "";
999 if (wl.activated) {
1000 activated = " activated";
1001 }
1002 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001003 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1004 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001006
1007 pw.println();
1008 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1009 for (PokeLock p: mPokeLocks.values()) {
1010 pw.println(" poke lock '" + p.tag + "':"
1011 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1012 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1013 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1014 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1015 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1016 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1017 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1018 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001020
Mike Lockwoodca44df82010-02-25 13:48:49 -05001021 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
1024
Joe Onorato7999bff2010-07-24 11:50:05 -04001025 private void setTimeoutLocked(long now, int nextState) {
1026 setTimeoutLocked(now, -1, nextState);
1027 }
1028
1029 // If they gave a timeoutOverride it is the number of seconds
1030 // to screen-off. Figure out where in the countdown cycle we
1031 // should jump to.
1032 private void setTimeoutLocked(long now, long timeoutOverride, int nextState) {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001033 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001034 synchronized (mLocks) {
1035 mHandler.removeCallbacks(mTimeoutTask);
1036 mTimeoutTask.nextState = nextState;
1037 long when = 0;
1038 if (timeoutOverride <= 0) {
1039 switch (nextState)
1040 {
1041 case SCREEN_BRIGHT:
1042 when = now + mKeylightDelay;
1043 break;
1044 case SCREEN_DIM:
1045 if (mDimDelay >= 0) {
1046 when = now + mDimDelay;
Andreas Huberd04ed082010-07-27 16:49:10 -07001047 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001048 } else {
1049 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1050 }
1051 case SCREEN_OFF:
1052 synchronized (mLocks) {
1053 when = now + mScreenOffDelay;
1054 }
1055 break;
Andreas Huberd04ed082010-07-27 16:49:10 -07001056 default:
1057 when = now;
1058 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001060 } else {
1061 override: {
1062 if (timeoutOverride <= mScreenOffDelay) {
1063 when = now + timeoutOverride;
1064 nextState = SCREEN_OFF;
1065 break override;
1066 }
1067 timeoutOverride -= mScreenOffDelay;
1068
1069 if (mDimDelay >= 0) {
1070 if (timeoutOverride <= mDimDelay) {
1071 when = now + timeoutOverride;
1072 nextState = SCREEN_DIM;
1073 break override;
1074 }
1075 timeoutOverride -= mDimDelay;
1076 }
1077
1078 when = now + timeoutOverride;
1079 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001081 }
1082 if (mSpew) {
1083 Slog.d(TAG, "setTimeoutLocked now=" + now
1084 + " timeoutOverride=" + timeoutOverride
1085 + " nextState=" + nextState + " when=" + when);
1086 }
1087 mHandler.postAtTime(mTimeoutTask, when);
1088 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
1091 }
1092
1093 private void cancelTimerLocked()
1094 {
1095 mHandler.removeCallbacks(mTimeoutTask);
1096 mTimeoutTask.nextState = -1;
1097 }
1098
1099 private class TimeoutTask implements Runnable
1100 {
1101 int nextState; // access should be synchronized on mLocks
1102 public void run()
1103 {
1104 synchronized (mLocks) {
1105 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001106 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108
1109 if (nextState == -1) {
1110 return;
1111 }
1112
1113 mUserState = this.nextState;
1114 setPowerState(this.nextState | mWakeLockState);
1115
1116 long now = SystemClock.uptimeMillis();
1117
1118 switch (this.nextState)
1119 {
1120 case SCREEN_BRIGHT:
1121 if (mDimDelay >= 0) {
1122 setTimeoutLocked(now, SCREEN_DIM);
1123 break;
1124 }
1125 case SCREEN_DIM:
1126 setTimeoutLocked(now, SCREEN_OFF);
1127 break;
1128 }
1129 }
1130 }
1131 }
1132
1133 private void sendNotificationLocked(boolean on, int why)
1134 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001135 if (!on) {
1136 mStillNeedSleepNotification = false;
1137 }
1138
Joe Onorato128e7292009-03-24 18:41:31 -07001139 // Add to the queue.
1140 int index = 0;
1141 while (mBroadcastQueue[index] != -1) {
1142 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
Joe Onorato128e7292009-03-24 18:41:31 -07001144 mBroadcastQueue[index] = on ? 1 : 0;
1145 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146
Joe Onorato128e7292009-03-24 18:41:31 -07001147 // If we added it position 2, then there is a pair that can be stripped.
1148 // If we added it position 1 and we're turning the screen off, we can strip
1149 // the pair and do nothing, because the screen is already off, and therefore
1150 // keyguard has already been enabled.
1151 // However, if we added it at position 1 and we're turning it on, then position
1152 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1153 // on, so have to run the queue then.
1154 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001155 // While we're collapsing them, if it's going off, and the new reason
1156 // is more significant than the first, then use the new one.
1157 if (!on && mBroadcastWhy[0] > why) {
1158 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001159 }
1160 mBroadcastQueue[0] = on ? 1 : 0;
1161 mBroadcastQueue[1] = -1;
1162 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001163 mBroadcastWakeLock.release();
1164 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001165 index = 0;
1166 }
1167 if (index == 1 && !on) {
1168 mBroadcastQueue[0] = -1;
1169 mBroadcastQueue[1] = -1;
1170 index = -1;
1171 // The wake lock was being held, but we're not actually going to do any
1172 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001175 }
1176
1177 // Now send the message.
1178 if (index >= 0) {
1179 // Acquire the broadcast wake lock before changing the power
1180 // state. It will be release after the broadcast is sent.
1181 // We always increment the ref count for each notification in the queue
1182 // and always decrement when that notification is handled.
1183 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001185 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187 }
1188
1189 private Runnable mNotificationTask = new Runnable()
1190 {
1191 public void run()
1192 {
Joe Onorato128e7292009-03-24 18:41:31 -07001193 while (true) {
1194 int value;
1195 int why;
1196 WindowManagerPolicy policy;
1197 synchronized (mLocks) {
1198 value = mBroadcastQueue[0];
1199 why = mBroadcastWhy[0];
1200 for (int i=0; i<2; i++) {
1201 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1202 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1203 }
1204 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
Joe Onorato128e7292009-03-24 18:41:31 -07001206 if (value == 1) {
1207 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
Joe Onorato128e7292009-03-24 18:41:31 -07001209 policy.screenTurnedOn();
1210 try {
1211 ActivityManagerNative.getDefault().wakingUp();
1212 } catch (RemoteException e) {
1213 // ignore it
1214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215
Joe Onorato128e7292009-03-24 18:41:31 -07001216 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001217 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001218 }
1219 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1220 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1221 mScreenOnBroadcastDone, mHandler, 0, null, null);
1222 } else {
1223 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001224 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001225 mBroadcastWakeLock.mCount);
1226 mBroadcastWakeLock.release();
1227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
1229 }
Joe Onorato128e7292009-03-24 18:41:31 -07001230 else if (value == 0) {
1231 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232
Joe Onorato128e7292009-03-24 18:41:31 -07001233 policy.screenTurnedOff(why);
1234 try {
1235 ActivityManagerNative.getDefault().goingToSleep();
1236 } catch (RemoteException e) {
1237 // ignore it.
1238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239
Joe Onorato128e7292009-03-24 18:41:31 -07001240 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1241 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1242 mScreenOffBroadcastDone, mHandler, 0, null, null);
1243 } else {
1244 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001245 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001246 mBroadcastWakeLock.mCount);
1247 mBroadcastWakeLock.release();
1248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 }
1250 }
Joe Onorato128e7292009-03-24 18:41:31 -07001251 else {
1252 // If we're in this case, then this handler is running for a previous
1253 // paired transaction. mBroadcastWakeLock will already have been released.
1254 break;
1255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257 }
1258 };
1259
1260 long mScreenOnStart;
1261 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1262 public void onReceive(Context context, Intent intent) {
1263 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001264 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1266 mBroadcastWakeLock.release();
1267 }
1268 }
1269 };
1270
1271 long mScreenOffStart;
1272 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1273 public void onReceive(Context context, Intent intent) {
1274 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001275 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1277 mBroadcastWakeLock.release();
1278 }
1279 }
1280 };
1281
1282 void logPointerUpEvent() {
1283 if (LOG_TOUCH_DOWNS) {
1284 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1285 mLastTouchDown = 0;
1286 }
1287 }
1288
1289 void logPointerDownEvent() {
1290 if (LOG_TOUCH_DOWNS) {
1291 // If we are not already timing a down/up sequence
1292 if (mLastTouchDown == 0) {
1293 mLastTouchDown = SystemClock.elapsedRealtime();
1294 mTouchCycles++;
1295 }
1296 }
1297 }
1298
1299 /**
1300 * Prevents the screen from turning on even if it *should* turn on due
1301 * to a subsequent full wake lock being acquired.
1302 * <p>
1303 * This is a temporary hack that allows an activity to "cover up" any
1304 * display glitches that happen during the activity's startup
1305 * sequence. (Specifically, this API was added to work around a
1306 * cosmetic bug in the "incoming call" sequence, where the lock screen
1307 * would flicker briefly before the incoming call UI became visible.)
1308 * TODO: There ought to be a more elegant way of doing this,
1309 * probably by having the PowerManager and ActivityManager
1310 * work together to let apps specify that the screen on/off
1311 * state should be synchronized with the Activity lifecycle.
1312 * <p>
1313 * Note that calling preventScreenOn(true) will NOT turn the screen
1314 * off if it's currently on. (This API only affects *future*
1315 * acquisitions of full wake locks.)
1316 * But calling preventScreenOn(false) WILL turn the screen on if
1317 * it's currently off because of a prior preventScreenOn(true) call.
1318 * <p>
1319 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1320 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1321 * call doesn't occur within 5 seconds, we'll turn the screen back on
1322 * ourselves (and log a warning about it); this prevents a buggy app
1323 * from disabling the screen forever.)
1324 * <p>
1325 * TODO: this feature should really be controlled by a new type of poke
1326 * lock (rather than an IPowerManager call).
1327 */
1328 public void preventScreenOn(boolean prevent) {
1329 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1330
1331 synchronized (mLocks) {
1332 if (prevent) {
1333 // First of all, grab a partial wake lock to
1334 // make sure the CPU stays on during the entire
1335 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1336 mPreventScreenOnPartialLock.acquire();
1337
1338 // Post a forceReenableScreen() call (for 5 seconds in the
1339 // future) to make sure the matching preventScreenOn(false) call
1340 // has happened by then.
1341 mHandler.removeCallbacks(mForceReenableScreenTask);
1342 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1343
1344 // Finally, set the flag that prevents the screen from turning on.
1345 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001346 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 mPreventScreenOn = true;
1348 } else {
1349 // (Re)enable the screen.
1350 mPreventScreenOn = false;
1351
1352 // We're "undoing" a the prior preventScreenOn(true) call, so we
1353 // no longer need the 5-second safeguard.
1354 mHandler.removeCallbacks(mForceReenableScreenTask);
1355
1356 // Forcibly turn on the screen if it's supposed to be on. (This
1357 // handles the case where the screen is currently off because of
1358 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001359 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001361 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1363 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001364 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001366 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368 }
1369
1370 // Release the partial wake lock that we held during the
1371 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1372 mPreventScreenOnPartialLock.release();
1373 }
1374 }
1375 }
1376
1377 public void setScreenBrightnessOverride(int brightness) {
1378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1379
Mike Lockwoodf527c712010-06-10 14:12:33 -04001380 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 synchronized (mLocks) {
1382 if (mScreenBrightnessOverride != brightness) {
1383 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001384 if (isScreenOn()) {
1385 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388 }
1389 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001390
1391 public void setButtonBrightnessOverride(int brightness) {
1392 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1393
Mike Lockwoodf527c712010-06-10 14:12:33 -04001394 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001395 synchronized (mLocks) {
1396 if (mButtonBrightnessOverride != brightness) {
1397 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001398 if (isScreenOn()) {
1399 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1400 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001401 }
1402 }
1403 }
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 /**
1406 * Sanity-check that gets called 5 seconds after any call to
1407 * preventScreenOn(true). This ensures that the original call
1408 * is followed promptly by a call to preventScreenOn(false).
1409 */
1410 private void forceReenableScreen() {
1411 // We shouldn't get here at all if mPreventScreenOn is false, since
1412 // we should have already removed any existing
1413 // mForceReenableScreenTask messages...
1414 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001415 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 return;
1417 }
1418
1419 // Uh oh. It's been 5 seconds since a call to
1420 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1421 // This means the app that called preventScreenOn(true) is either
1422 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1423 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1424 // crashed before doing so.)
1425
1426 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001427 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 + "Forcing the screen back on...");
1429 preventScreenOn(false);
1430 }
1431
1432 private Runnable mForceReenableScreenTask = new Runnable() {
1433 public void run() {
1434 forceReenableScreen();
1435 }
1436 };
1437
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001438 private int setScreenStateLocked(boolean on) {
1439 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001440 if (err == 0) {
1441 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1442 if (mUseSoftwareAutoBrightness) {
1443 enableLightSensor(on);
1444 if (!on) {
1445 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001446 mButtonLight.turnOff();
1447 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001448 // clear current value so we will update based on the new conditions
1449 // when the sensor is reenabled.
1450 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001451 // reset our highest light sensor value when the screen turns off
1452 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001453 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001454 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001455 }
1456 return err;
1457 }
1458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 private void setPowerState(int state)
1460 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001461 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463
Mike Lockwood435eb642009-12-03 08:40:18 -05001464 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 {
1466 synchronized (mLocks) {
1467 int err;
1468
1469 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001470 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001472 + " noChangeLights=" + noChangeLights
1473 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475
1476 if (noChangeLights) {
1477 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1478 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001479 if (mProximitySensorActive) {
1480 // don't turn on the screen when the proximity sensor lock is held
1481 newState = (newState & ~SCREEN_BRIGHT);
1482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483
1484 if (batteryIsLow()) {
1485 newState |= BATTERY_LOW_BIT;
1486 } else {
1487 newState &= ~BATTERY_LOW_BIT;
1488 }
1489 if (newState == mPowerState) {
1490 return;
1491 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001492
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001493 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 newState |= ALL_BRIGHT;
1495 }
1496
1497 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1498 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1499
Mike Lockwood51b844962009-11-16 21:51:18 -05001500 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001501 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001503 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001509 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001511 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1513 }
1514
1515 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001516 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1518 }
1519
1520 if (oldScreenOn != newScreenOn) {
1521 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001522 // When the user presses the power button, we need to always send out the
1523 // notification that it's going to sleep so the keyguard goes on. But
1524 // we can't do that until the screen fades out, so we don't show the keyguard
1525 // too early.
1526 if (mStillNeedSleepNotification) {
1527 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1528 }
1529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 // Turn on the screen UNLESS there was a prior
1531 // preventScreenOn(true) request. (Note that the lifetime
1532 // of a single preventScreenOn() request is limited to 5
1533 // seconds to prevent a buggy app from disabling the
1534 // screen forever; see forceReenableScreen().)
1535 boolean reallyTurnScreenOn = true;
1536 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001537 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 + mPreventScreenOn);
1539 }
1540
1541 if (mPreventScreenOn) {
1542 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001543 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 reallyTurnScreenOn = false;
1546 }
1547 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001548 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 long identity = Binder.clearCallingIdentity();
1550 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001551 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 mBatteryStats.noteScreenOn();
1553 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 } finally {
1556 Binder.restoreCallingIdentity(identity);
1557 }
1558 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001559 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 // But continue as if we really did turn the screen on...
1561 err = 0;
1562 }
1563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 mLastTouchDown = 0;
1565 mTotalTouchDownTime = 0;
1566 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001567 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 mTotalTouchDownTime, mTouchCycles);
1569 if (err == 0) {
1570 mPowerState |= SCREEN_ON_BIT;
1571 sendNotificationLocked(true, -1);
1572 }
1573 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001574 // cancel light sensor task
1575 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 mScreenOffTime = SystemClock.elapsedRealtime();
1577 long identity = Binder.clearCallingIdentity();
1578 try {
1579 mBatteryStats.noteScreenOff();
1580 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001581 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 } finally {
1583 Binder.restoreCallingIdentity(identity);
1584 }
1585 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001586 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001588 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 err = 0;
1591 mLastTouchDown = 0;
1592 }
1593 }
1594 }
1595 }
1596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001597
Mike Lockwood435eb642009-12-03 08:40:18 -05001598 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001600 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001602 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001604 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001606 mScreenOffReason = reason;
1607 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 return err;
1610 }
1611
1612 private boolean batteryIsLow() {
1613 return (!mIsPowered &&
1614 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1615 }
1616
The Android Open Source Project10592532009-03-18 17:39:46 -07001617 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001618 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001619 newState = applyButtonState(newState);
1620 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001621 final int realDifference = (newState ^ oldState);
1622 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001624 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 int offMask = 0;
1628 int dimMask = 0;
1629 int onMask = 0;
1630
1631 int preferredBrightness = getPreferredBrightness();
1632 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1635 if (ANIMATE_KEYBOARD_LIGHTS) {
1636 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1637 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001638 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001639 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001641 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001642 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1643 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 startAnimation = true;
1646 } else {
1647 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001648 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001650 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652 }
1653 }
1654
1655 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1656 if (ANIMATE_BUTTON_LIGHTS) {
1657 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1658 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001659 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001660 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001662 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001663 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1664 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 startAnimation = true;
1667 } else {
1668 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001669 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001671 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
1674 }
1675
1676 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1677 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001678 int nominalCurrentValue = -1;
1679 // If there was an actual difference in the light state, then
1680 // figure out the "ideal" current value based on the previous
1681 // state. Otherwise, this is a change due to the brightness
1682 // override, so we want to animate from whatever the current
1683 // value is.
1684 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1685 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1686 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1687 nominalCurrentValue = preferredBrightness;
1688 break;
1689 case SCREEN_ON_BIT:
1690 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1691 break;
1692 case 0:
1693 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1694 break;
1695 case SCREEN_BRIGHT_BIT:
1696 default:
1697 // not possible
1698 nominalCurrentValue = (int)mScreenBrightness.curValue;
1699 break;
1700 }
Joe Onorato128e7292009-03-24 18:41:31 -07001701 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001702 int brightness = preferredBrightness;
1703 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1705 // dim or turn off backlight, depending on if the screen is on
1706 // the scale is because the brightness ramp isn't linear and this biases
1707 // it so the later parts take longer.
1708 final float scale = 1.5f;
1709 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1710 if (ratio > 1.0f) ratio = 1.0f;
1711 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1713 // was bright
1714 steps = ANIM_STEPS;
1715 } else {
1716 // was dim
1717 steps = (int)(ANIM_STEPS*ratio*scale);
1718 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001719 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 if ((oldState & SCREEN_ON_BIT) != 0) {
1722 // was bright
1723 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1724 } else {
1725 // was dim
1726 steps = (int)(ANIM_STEPS*ratio);
1727 }
1728 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1729 // If the "stay on while plugged in" option is
1730 // turned on, then the screen will often not
1731 // automatically turn off while plugged in. To
1732 // still have a sense of when it is inactive, we
1733 // will then count going dim as turning off.
1734 mScreenOffTime = SystemClock.elapsedRealtime();
1735 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001736 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001739 long identity = Binder.clearCallingIdentity();
1740 try {
1741 mBatteryStats.noteScreenBrightness(brightness);
1742 } catch (RemoteException e) {
1743 // Nothing interesting to do.
1744 } finally {
1745 Binder.restoreCallingIdentity(identity);
1746 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001747 if (mScreenBrightness.setTargetLocked(brightness,
1748 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1749 startAnimation = true;
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 } else {
1752 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1753 // dim or turn off backlight, depending on if the screen is on
1754 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001755 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001757 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 }
1759 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001760 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762 }
1763 }
1764
1765 if (startAnimation) {
1766 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001767 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 mHandler.removeCallbacks(mLightAnimator);
1770 mHandler.post(mLightAnimator);
1771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001774 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001775 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
1777 if (dimMask != 0) {
1778 int brightness = Power.BRIGHTNESS_DIM;
1779 if ((newState & BATTERY_LOW_BIT) != 0 &&
1780 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1781 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1782 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001783 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001784 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 }
1786 if (onMask != 0) {
1787 int brightness = getPreferredBrightness();
1788 if ((newState & BATTERY_LOW_BIT) != 0 &&
1789 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1790 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1791 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001792 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001793 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796
The Android Open Source Project10592532009-03-18 17:39:46 -07001797 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001798 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001799 ? LightsService.BRIGHTNESS_MODE_SENSOR
1800 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001801 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001802 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001803 }
1804 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001805 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001806 }
1807 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001808 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
1811
1812 class BrightnessState {
1813 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 boolean initialized;
1816 int targetValue;
1817 float curValue;
1818 float delta;
1819 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 BrightnessState(int m) {
1822 mask = m;
1823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 public void dump(PrintWriter pw, String prefix) {
1826 pw.println(prefix + "animating=" + animating
1827 + " targetValue=" + targetValue
1828 + " curValue=" + curValue
1829 + " delta=" + delta);
1830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001831
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001832 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001833 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 if (!initialized) {
1835 initialized = true;
1836 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001837 } else if (targetValue == target) {
1838 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001841 delta = (targetValue -
1842 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1843 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001845 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001846 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001847 + " target=" + targetValue + " delta=" + delta
1848 + " nominalCurrentValue=" + nominalCurrentValue
1849 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001852 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 boolean stepLocked() {
1856 if (!animating) return false;
1857 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001858 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 + " target=" + targetValue + " delta=" + delta);
1860 }
1861 curValue += delta;
1862 int curIntValue = (int)curValue;
1863 boolean more = true;
1864 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001865 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 more = false;
1867 } else if (delta > 0) {
1868 if (curIntValue >= targetValue) {
1869 curValue = curIntValue = targetValue;
1870 more = false;
1871 }
1872 } else {
1873 if (curIntValue <= targetValue) {
1874 curValue = curIntValue = targetValue;
1875 more = false;
1876 }
1877 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001878 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001879 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 animating = more;
1881 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001882 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001883 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885 }
1886 return more;
1887 }
1888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 private class LightAnimator implements Runnable {
1891 public void run() {
1892 synchronized (mLocks) {
1893 long now = SystemClock.uptimeMillis();
1894 boolean more = mScreenBrightness.stepLocked();
1895 if (mKeyboardBrightness.stepLocked()) {
1896 more = true;
1897 }
1898 if (mButtonBrightness.stepLocked()) {
1899 more = true;
1900 }
1901 if (more) {
1902 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1903 }
1904 }
1905 }
1906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 private int getPreferredBrightness() {
1909 try {
1910 if (mScreenBrightnessOverride >= 0) {
1911 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001912 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001913 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001914 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
1916 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1917 SCREEN_BRIGHTNESS);
1918 // Don't let applications turn the screen all the way off
1919 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1920 } catch (SettingNotFoundException snfe) {
1921 return Power.BRIGHTNESS_ON;
1922 }
1923 }
1924
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001925 private int applyButtonState(int state) {
1926 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001927 if ((state & BATTERY_LOW_BIT) != 0) {
1928 // do not override brightness if the battery is low
1929 return state;
1930 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001931 if (mButtonBrightnessOverride >= 0) {
1932 brightness = mButtonBrightnessOverride;
1933 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1934 brightness = mLightSensorButtonBrightness;
1935 }
1936 if (brightness > 0) {
1937 return state | BUTTON_BRIGHT_BIT;
1938 } else if (brightness == 0) {
1939 return state & ~BUTTON_BRIGHT_BIT;
1940 } else {
1941 return state;
1942 }
1943 }
1944
1945 private int applyKeyboardState(int state) {
1946 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04001947 if ((state & BATTERY_LOW_BIT) != 0) {
1948 // do not override brightness if the battery is low
1949 return state;
1950 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001951 if (!mKeyboardVisible) {
1952 brightness = 0;
1953 } else if (mButtonBrightnessOverride >= 0) {
1954 brightness = mButtonBrightnessOverride;
1955 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1956 brightness = mLightSensorKeyboardBrightness;
1957 }
1958 if (brightness > 0) {
1959 return state | KEYBOARD_BRIGHT_BIT;
1960 } else if (brightness == 0) {
1961 return state & ~KEYBOARD_BRIGHT_BIT;
1962 } else {
1963 return state;
1964 }
1965 }
1966
Charles Mendis322591c2009-10-29 11:06:59 -07001967 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 synchronized (mLocks) {
1969 return (mPowerState & SCREEN_ON_BIT) != 0;
1970 }
1971 }
1972
Charles Mendis322591c2009-10-29 11:06:59 -07001973 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 synchronized (mLocks) {
1975 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1976 }
1977 }
1978
Mike Lockwood497087e32009-11-08 18:33:03 -05001979 private boolean isScreenTurningOffLocked() {
1980 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1981 }
1982
Mike Lockwood200b30b2009-09-20 00:23:59 -04001983 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001984 if (isScreenTurningOffLocked()) {
1985 // cancel animation so userActivity will succeed
1986 mScreenBrightness.animating = false;
1987 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001988 boolean savedActivityAllowed = mUserActivityAllowed;
1989 mUserActivityAllowed = true;
1990 userActivity(SystemClock.uptimeMillis(), false);
1991 mUserActivityAllowed = savedActivityAllowed;
1992 }
1993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04001996 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
1998
1999 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002000 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002
2003 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002004 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006
2007 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002008 userActivity(time, -1, noChangeLights, eventType, force);
2009 }
2010
2011 /*
2012 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2013 * on with user activity. Don't use this function.
2014 */
2015 public void clearUserActivityTimeout(long now, long timeout) {
2016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2017 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2018 userActivity(now, timeout, false, OTHER_EVENT, false);
2019 }
2020
2021 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2022 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2024
2025 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002026 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002028 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030 return;
2031 }
2032
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002033 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2034 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2035 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2036 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002037 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002038 }
2039 return;
2040 }
2041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (false) {
2043 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002044 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002046 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 }
2049
2050 synchronized (mLocks) {
2051 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002052 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 + " mUserActivityAllowed=" + mUserActivityAllowed
2054 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002055 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2056 + " mProximitySensorActive=" + mProximitySensorActive
2057 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
Mike Lockwood05067122009-10-27 23:07:25 -04002059 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002060 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002061 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002062 return;
2063 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002064 // Disable proximity sensor if if user presses power key while we are in the
2065 // "waiting for proximity sensor to go negative" state.
2066 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2067 mProximitySensorActive = false;
2068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (mLastEventTime <= time || force) {
2070 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002071 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002072 // Only turn on button backlights if a button was pressed
2073 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002074 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2076 } else {
2077 // don't clear button/keyboard backlights when the screen is touched.
2078 mUserState |= SCREEN_BRIGHT;
2079 }
2080
Dianne Hackborn617f8772009-03-31 15:04:46 -07002081 int uid = Binder.getCallingUid();
2082 long ident = Binder.clearCallingIdentity();
2083 try {
2084 mBatteryStats.noteUserActivity(uid, eventType);
2085 } catch (RemoteException e) {
2086 // Ignore
2087 } finally {
2088 Binder.restoreCallingIdentity(ident);
2089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002090
Michael Chane96440f2009-05-06 10:27:36 -07002091 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002092 setPowerState(mUserState | mWakeLockState, noChangeLights,
2093 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002094 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096 }
2097 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002098
2099 if (mPolicy != null) {
2100 mPolicy.userActivity();
2101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002104 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2105 try {
2106 int i;
2107 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2108 if (sensorValue < mAutoBrightnessLevels[i]) {
2109 break;
2110 }
2111 }
2112 return values[i];
2113 } catch (Exception e) {
2114 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002115 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002116 return 255;
2117 }
2118 }
2119
Mike Lockwood20f87d72009-11-05 16:08:51 -05002120 private Runnable mProximityTask = new Runnable() {
2121 public void run() {
2122 synchronized (mLocks) {
2123 if (mProximityPendingValue != -1) {
2124 proximityChangedLocked(mProximityPendingValue == 1);
2125 mProximityPendingValue = -1;
2126 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002127 if (mProximityPartialLock.isHeld()) {
2128 mProximityPartialLock.release();
2129 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002130 }
2131 }
2132 };
2133
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002134 private Runnable mAutoBrightnessTask = new Runnable() {
2135 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002136 synchronized (mLocks) {
2137 int value = (int)mLightSensorPendingValue;
2138 if (value >= 0) {
2139 mLightSensorPendingValue = -1;
2140 lightSensorChangedLocked(value);
2141 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002142 }
2143 }
2144 };
2145
Mike Lockwoodb2865412010-02-02 22:40:33 -05002146 private void dockStateChanged(int state) {
2147 synchronized (mLocks) {
2148 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2149 if (mIsDocked) {
2150 mHighestLightSensorValue = -1;
2151 }
2152 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2153 // force lights recalculation
2154 int value = (int)mLightSensorValue;
2155 mLightSensorValue = -1;
2156 lightSensorChangedLocked(value);
2157 }
2158 }
2159 }
2160
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002161 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002162 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002163 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002164 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002165
Mike Lockwoodb2865412010-02-02 22:40:33 -05002166 // do not allow light sensor value to decrease
2167 if (mHighestLightSensorValue < value) {
2168 mHighestLightSensorValue = value;
2169 }
2170
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002171 if (mLightSensorValue != value) {
2172 mLightSensorValue = value;
2173 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002174 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2175 // we only do this if we are undocked, since lighting should be stable when
2176 // stationary in a dock.
2177 int lcdValue = getAutoBrightnessValue(
2178 (mIsDocked ? value : mHighestLightSensorValue),
2179 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002180 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002181 int keyboardValue;
2182 if (mKeyboardVisible) {
2183 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2184 } else {
2185 keyboardValue = 0;
2186 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002187 mLightSensorScreenBrightness = lcdValue;
2188 mLightSensorButtonBrightness = buttonValue;
2189 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002190
2191 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 Slog.d(TAG, "lcdValue " + lcdValue);
2193 Slog.d(TAG, "buttonValue " + buttonValue);
2194 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002195 }
2196
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002197 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002198 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002199 if (ANIMATE_SCREEN_LIGHTS) {
2200 if (mScreenBrightness.setTargetLocked(lcdValue,
2201 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2202 (int)mScreenBrightness.curValue)) {
2203 startAnimation = true;
2204 }
2205 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002206 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002207 ? LightsService.BRIGHTNESS_MODE_SENSOR
2208 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002209 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002210 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002211 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002212 if (mButtonBrightnessOverride < 0) {
2213 if (ANIMATE_BUTTON_LIGHTS) {
2214 if (mButtonBrightness.setTargetLocked(buttonValue,
2215 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2216 (int)mButtonBrightness.curValue)) {
2217 startAnimation = true;
2218 }
2219 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002220 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002221 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002222 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002223 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2224 if (ANIMATE_KEYBOARD_LIGHTS) {
2225 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2226 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2227 (int)mKeyboardBrightness.curValue)) {
2228 startAnimation = true;
2229 }
2230 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002231 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002232 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002233 }
2234 if (startAnimation) {
2235 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002236 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002237 }
2238 mHandler.removeCallbacks(mLightAnimator);
2239 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002240 }
2241 }
2242 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002243 }
2244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 /**
2246 * The user requested that we go to sleep (probably with the power button).
2247 * This overrides all wake locks that are held.
2248 */
2249 public void goToSleep(long time)
2250 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002251 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2252 }
2253
2254 /**
2255 * The user requested that we go to sleep (probably with the power button).
2256 * This overrides all wake locks that are held.
2257 */
2258 public void goToSleepWithReason(long time, int reason)
2259 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2261 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002262 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002267 * Reboot the device immediately, passing 'reason' (may be null)
2268 * to the underlying __reboot system call. Should not return.
2269 */
2270 public void reboot(String reason)
2271 {
2272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002273
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002274 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2275 throw new IllegalStateException("Too early to call reboot()");
2276 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002277
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002278 final String finalReason = reason;
2279 Runnable runnable = new Runnable() {
2280 public void run() {
2281 synchronized (this) {
2282 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002283 }
2284
San Mehat1e512792010-01-07 10:40:29 -08002285 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002286 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002287 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002288 mHandler.post(runnable);
2289
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002290 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002291 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002292 while (true) {
2293 try {
2294 runnable.wait();
2295 } catch (InterruptedException e) {
2296 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002297 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002298 }
2299 }
2300
Dan Egnor60d87622009-12-16 16:32:58 -08002301 /**
2302 * Crash the runtime (causing a complete restart of the Android framework).
2303 * Requires REBOOT permission. Mostly for testing. Should not return.
2304 */
2305 public void crash(final String message)
2306 {
2307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2308 Thread t = new Thread("PowerManagerService.crash()") {
2309 public void run() { throw new RuntimeException(message); }
2310 };
2311 try {
2312 t.start();
2313 t.join();
2314 } catch (InterruptedException e) {
2315 Log.wtf(TAG, e);
2316 }
2317 }
2318
Mike Lockwood435eb642009-12-03 08:40:18 -05002319 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320
2321 if (mLastEventTime <= time) {
2322 mLastEventTime = time;
2323 // cancel all of the wake locks
2324 mWakeLockState = SCREEN_OFF;
2325 int N = mLocks.size();
2326 int numCleared = 0;
2327 for (int i=0; i<N; i++) {
2328 WakeLock wl = mLocks.get(i);
2329 if (isScreenLock(wl.flags)) {
2330 mLocks.get(i).activated = false;
2331 numCleared++;
2332 }
2333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002334 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002335 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002337 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 cancelTimerLocked();
2339 }
2340 }
2341
2342 public long timeSinceScreenOn() {
2343 synchronized (mLocks) {
2344 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2345 return 0;
2346 }
2347 return SystemClock.elapsedRealtime() - mScreenOffTime;
2348 }
2349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002352 synchronized (mLocks) {
2353 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002354 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002355 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002356 if (mKeyboardVisible != visible) {
2357 mKeyboardVisible = visible;
2358 // don't signal user activity if the screen is off; other code
2359 // will take care of turning on due to a true change to the lid
2360 // switch and synchronized with the lock screen.
2361 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002362 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002363 // force recompute of backlight values
2364 if (mLightSensorValue >= 0) {
2365 int value = (int)mLightSensorValue;
2366 mLightSensorValue = -1;
2367 lightSensorChangedLocked(value);
2368 }
2369 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002370 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2371 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002372 }
2373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 }
2375
2376 /**
2377 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002378 * When disabling user activity we also reset user power state so the keyguard can reset its
2379 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 */
2381 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002382 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002383 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 synchronized (mLocks) {
2386 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002387 if (!enabled) {
2388 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2389 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392 }
2393
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002394 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002395 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002396 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002397 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002398 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002399 // force recompute of backlight values
2400 if (mLightSensorValue >= 0) {
2401 int value = (int)mLightSensorValue;
2402 mLightSensorValue = -1;
2403 lightSensorChangedLocked(value);
2404 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002405 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002406 }
2407 }
2408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 /** Sets the screen off timeouts:
2410 * mKeylightDelay
2411 * mDimDelay
2412 * mScreenOffDelay
2413 * */
2414 private void setScreenOffTimeoutsLocked() {
2415 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002416 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 mDimDelay = -1;
2418 mScreenOffDelay = 0;
2419 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2420 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2421 mDimDelay = -1;
2422 mScreenOffDelay = 0;
2423 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002424 int totalDelay = mScreenOffTimeoutSetting;
2425 if (totalDelay > mMaximumScreenOffTimeout) {
2426 totalDelay = mMaximumScreenOffTimeout;
2427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2429 if (totalDelay < 0) {
2430 mScreenOffDelay = Integer.MAX_VALUE;
2431 } else if (mKeylightDelay < totalDelay) {
2432 // subtract the time that the keylight delay. This will give us the
2433 // remainder of the time that we need to sleep to get the accurate
2434 // screen off timeout.
2435 mScreenOffDelay = totalDelay - mKeylightDelay;
2436 } else {
2437 mScreenOffDelay = 0;
2438 }
2439 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2440 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2441 mScreenOffDelay = LONG_DIM_TIME;
2442 } else {
2443 mDimDelay = -1;
2444 }
2445 }
2446 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002447 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2449 + " mDimScreen=" + mDimScreen);
2450 }
2451 }
2452
2453 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002454 * Refreshes cached secure settings. Called once on startup, and
2455 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 */
Doug Zongker43866e02010-01-07 12:09:54 -08002457 private void updateSettingsValues() {
2458 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002460 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002462 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
2465 private class LockList extends ArrayList<WakeLock>
2466 {
2467 void addLock(WakeLock wl)
2468 {
2469 int index = getIndex(wl.binder);
2470 if (index < 0) {
2471 this.add(wl);
2472 }
2473 }
2474
2475 WakeLock removeLock(IBinder binder)
2476 {
2477 int index = getIndex(binder);
2478 if (index >= 0) {
2479 return this.remove(index);
2480 } else {
2481 return null;
2482 }
2483 }
2484
2485 int getIndex(IBinder binder)
2486 {
2487 int N = this.size();
2488 for (int i=0; i<N; i++) {
2489 if (this.get(i).binder == binder) {
2490 return i;
2491 }
2492 }
2493 return -1;
2494 }
2495
2496 int gatherState()
2497 {
2498 int result = 0;
2499 int N = this.size();
2500 for (int i=0; i<N; i++) {
2501 WakeLock wl = this.get(i);
2502 if (wl.activated) {
2503 if (isScreenLock(wl.flags)) {
2504 result |= wl.minState;
2505 }
2506 }
2507 }
2508 return result;
2509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002510
Michael Chane96440f2009-05-06 10:27:36 -07002511 int reactivateScreenLocksLocked()
2512 {
2513 int result = 0;
2514 int N = this.size();
2515 for (int i=0; i<N; i++) {
2516 WakeLock wl = this.get(i);
2517 if (isScreenLock(wl.flags)) {
2518 wl.activated = true;
2519 result |= wl.minState;
2520 }
2521 }
2522 return result;
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525
2526 void setPolicy(WindowManagerPolicy p) {
2527 synchronized (mLocks) {
2528 mPolicy = p;
2529 mLocks.notifyAll();
2530 }
2531 }
2532
2533 WindowManagerPolicy getPolicyLocked() {
2534 while (mPolicy == null || !mDoneBooting) {
2535 try {
2536 mLocks.wait();
2537 } catch (InterruptedException e) {
2538 // Ignore
2539 }
2540 }
2541 return mPolicy;
2542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002545 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2546 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2547 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002548 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002549 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002550 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002551 }
2552
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002553 // wait until sensors are enabled before turning on screen.
2554 // some devices will not activate the light sensor properly on boot
2555 // unless we do this.
2556 if (mUseSoftwareAutoBrightness) {
2557 // turn the screen on
2558 setPowerState(SCREEN_BRIGHT);
2559 } else {
2560 // turn everything on
2561 setPowerState(ALL_BRIGHT);
2562 }
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002565 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002567
Dianne Hackborn617f8772009-03-31 15:04:46 -07002568 long identity = Binder.clearCallingIdentity();
2569 try {
2570 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2571 mBatteryStats.noteScreenOn();
2572 } catch (RemoteException e) {
2573 // Nothing interesting to do.
2574 } finally {
2575 Binder.restoreCallingIdentity(identity);
2576 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002577 }
2578 }
2579
2580 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002581 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002582 synchronized (mLocks) {
2583 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2585 updateWakeLockLocked();
2586 mLocks.notifyAll();
2587 }
2588 }
2589
2590 public void monitor() {
2591 synchronized (mLocks) { }
2592 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002593
2594 public int getSupportedWakeLockFlags() {
2595 int result = PowerManager.PARTIAL_WAKE_LOCK
2596 | PowerManager.FULL_WAKE_LOCK
2597 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2598
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002599 if (mProximitySensor != null) {
2600 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2601 }
2602
2603 return result;
2604 }
2605
Mike Lockwood237a2992009-09-15 14:42:16 -04002606 public void setBacklightBrightness(int brightness) {
2607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2608 // Don't let applications turn the screen all the way off
2609 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002610 mLcdLight.setBrightness(brightness);
2611 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2612 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002613 long identity = Binder.clearCallingIdentity();
2614 try {
2615 mBatteryStats.noteScreenBrightness(brightness);
2616 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002617 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002618 } finally {
2619 Binder.restoreCallingIdentity(identity);
2620 }
2621
2622 // update our animation state
2623 if (ANIMATE_SCREEN_LIGHTS) {
2624 mScreenBrightness.curValue = brightness;
2625 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002626 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002627 }
2628 if (ANIMATE_KEYBOARD_LIGHTS) {
2629 mKeyboardBrightness.curValue = brightness;
2630 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002631 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002632 }
2633 if (ANIMATE_BUTTON_LIGHTS) {
2634 mButtonBrightness.curValue = brightness;
2635 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002636 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002637 }
2638 }
2639
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002640 public void setAttentionLight(boolean on, int color) {
2641 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002642 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002643 }
2644
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002645 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002646 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002647 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002648 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002649 if (!mProximitySensorEnabled) {
2650 // clear calling identity so sensor manager battery stats are accurate
2651 long identity = Binder.clearCallingIdentity();
2652 try {
2653 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2654 SensorManager.SENSOR_DELAY_NORMAL);
2655 mProximitySensorEnabled = true;
2656 } finally {
2657 Binder.restoreCallingIdentity(identity);
2658 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002659 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002660 }
2661
2662 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002663 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002664 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002665 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002666 if (mProximitySensorEnabled) {
2667 // clear calling identity so sensor manager battery stats are accurate
2668 long identity = Binder.clearCallingIdentity();
2669 try {
2670 mSensorManager.unregisterListener(mProximityListener);
2671 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002672 if (mProximityPartialLock.isHeld()) {
2673 mProximityPartialLock.release();
2674 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002675 mProximitySensorEnabled = false;
2676 } finally {
2677 Binder.restoreCallingIdentity(identity);
2678 }
2679 if (mProximitySensorActive) {
2680 mProximitySensorActive = false;
2681 forceUserActivityLocked();
2682 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002683 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002684 }
2685
Mike Lockwood20f87d72009-11-05 16:08:51 -05002686 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002687 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002688 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002689 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002690 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002691 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002692 return;
2693 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002694 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002695 goToSleepLocked(SystemClock.uptimeMillis(),
2696 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002697 mProximitySensorActive = true;
2698 } else {
2699 // proximity sensor negative events trigger as user activity.
2700 // temporarily set mUserActivityAllowed to true so this will work
2701 // even when the keyguard is on.
2702 mProximitySensorActive = false;
2703 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002704
2705 if (mProximityWakeLockCount == 0) {
2706 // disable sensor if we have no listeners left after proximity negative
2707 disableProximityLockLocked();
2708 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002709 }
2710 }
2711
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002712 private void enableLightSensor(boolean enable) {
2713 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002714 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002715 }
2716 if (mSensorManager != null && mLightSensorEnabled != enable) {
2717 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002718 // clear calling identity so sensor manager battery stats are accurate
2719 long identity = Binder.clearCallingIdentity();
2720 try {
2721 if (enable) {
2722 mSensorManager.registerListener(mLightListener, mLightSensor,
2723 SensorManager.SENSOR_DELAY_NORMAL);
2724 } else {
2725 mSensorManager.unregisterListener(mLightListener);
2726 mHandler.removeCallbacks(mAutoBrightnessTask);
2727 }
2728 } finally {
2729 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002730 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002731 }
2732 }
2733
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002734 SensorEventListener mProximityListener = new SensorEventListener() {
2735 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002736 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002737 synchronized (mLocks) {
2738 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002739 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2740 mLastProximityEventTime = milliseconds;
2741 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002742 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002743
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002744 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002745 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2746 distance < mProximitySensor.getMaximumRange());
2747
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002748 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002749 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002750 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002751 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2752 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2753 mProximityPendingValue = (active ? 1 : 0);
2754 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002755 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002756 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002757 // process the value immediately
2758 mProximityPendingValue = -1;
2759 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002760 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002761
2762 // update mProximityPartialLock state
2763 boolean held = mProximityPartialLock.isHeld();
2764 if (!held && proximityTaskQueued) {
2765 // hold wakelock until mProximityTask runs
2766 mProximityPartialLock.acquire();
2767 } else if (held && !proximityTaskQueued) {
2768 mProximityPartialLock.release();
2769 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002770 }
2771 }
2772
2773 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2774 // ignore
2775 }
2776 };
2777
2778 SensorEventListener mLightListener = new SensorEventListener() {
2779 public void onSensorChanged(SensorEvent event) {
2780 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002781 // ignore light sensor while screen is turning off
2782 if (isScreenTurningOffLocked()) {
2783 return;
2784 }
2785
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002786 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002787 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002788 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002789 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002790 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002791 mHandler.removeCallbacks(mAutoBrightnessTask);
2792 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002793 if (mLightSensorValue == -1 ||
2794 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2795 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002796 lightSensorChangedLocked(value);
2797 } else {
2798 // delay processing to debounce the sensor
2799 mLightSensorPendingValue = value;
2800 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2801 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002802 } else {
2803 mLightSensorPendingValue = -1;
2804 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002805 }
2806 }
2807
2808 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2809 // ignore
2810 }
2811 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812}