blob: f106fc360f09e5d4316573303a5f6d891aa15876 [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;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070034import android.hardware.Sensor;
35import android.hardware.SensorEvent;
36import android.hardware.SensorEventListener;
37import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.BatteryStats;
39import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080040import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Handler;
42import android.os.HandlerThread;
43import android.os.IBinder;
Doug Zongker43866e02010-01-07 12:09:54 -080044import android.os.IMountService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import 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;
57import android.view.WindowManagerPolicy;
58import static android.provider.Settings.System.DIM_SCREEN;
59import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050060import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070061import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
63import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
64
65import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080066import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.io.PrintWriter;
68import java.util.ArrayList;
69import java.util.HashMap;
70import java.util.Observable;
71import java.util.Observer;
72
Mike Lockwoodbc706a02009-07-27 13:50:57 -070073class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040074 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76 private static final String TAG = "PowerManagerService";
77 static final String PARTIAL_NAME = "PowerManagerService";
78
79 private static final boolean LOG_PARTIAL_WL = false;
80
81 // Indicates whether touch-down cycles should be logged as part of the
82 // LOG_POWER_SCREEN_STATE log events
83 private static final boolean LOG_TOUCH_DOWNS = true;
84
85 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
86 | PowerManager.SCREEN_DIM_WAKE_LOCK
87 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070088 | PowerManager.FULL_WAKE_LOCK
89 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
91 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080092 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
94 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
95 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
96 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
97
Mike Lockwoodd7786b42009-10-15 17:09:16 -070098 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -050099 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700100
Mike Lockwood20f87d72009-11-05 16:08:51 -0500101 // For debouncing the proximity sensor.
102 private static final int PROXIMITY_SENSOR_DELAY = 1000;
103
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400104 // trigger proximity if distance is less than 5 cm
105 private static final float PROXIMITY_THRESHOLD = 5.0f;
106
Doug Zongker43866e02010-01-07 12:09:54 -0800107 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
109
110 // flags for setPowerState
111 private static final int SCREEN_ON_BIT = 0x00000001;
112 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
113 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
114 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
115 private static final int BATTERY_LOW_BIT = 0x00000010;
116
117 // values for setPowerState
118
119 // SCREEN_OFF == everything off
120 private static final int SCREEN_OFF = 0x00000000;
121
122 // SCREEN_DIM == screen on, screen backlight dim
123 private static final int SCREEN_DIM = SCREEN_ON_BIT;
124
125 // SCREEN_BRIGHT == screen on, screen backlight bright
126 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
127
128 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
129 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
130
131 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
132 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
133
134 // used for noChangeLights in setPowerState()
135 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
136
137 static final boolean ANIMATE_SCREEN_LIGHTS = true;
138 static final boolean ANIMATE_BUTTON_LIGHTS = false;
139 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400142 // Slower animation for autobrightness changes
143 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 // These magic numbers are the initial state of the LEDs at boot. Ideally
146 // we should read them from the driver, but our current hardware returns 0
147 // for the initial value. Oops!
148 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
149 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
150 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private final int MY_UID;
153
154 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500155 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700157 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
158 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mPartialCount = 0;
160 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500161 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
162 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
163 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mUserState;
165 private boolean mKeyboardVisible = false;
166 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500167 private int mProximityWakeLockCount = 0;
168 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700169 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500170 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
171 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800172 private int mScreenOffTimeoutSetting;
173 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 private int mKeylightDelay;
175 private int mDimDelay;
176 private int mScreenOffDelay;
177 private int mWakeLockState;
178 private long mLastEventTime = 0;
179 private long mScreenOffTime;
180 private volatile WindowManagerPolicy mPolicy;
181 private final LockList mLocks = new LockList();
182 private Intent mScreenOffIntent;
183 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500184 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500186 private LightsService.Light mLcdLight;
187 private LightsService.Light mButtonLight;
188 private LightsService.Light mKeyboardLight;
189 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private UnsynchronizedWakeLock mBroadcastWakeLock;
191 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
193 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500194 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private HandlerThread mHandlerThread;
196 private Handler mHandler;
197 private TimeoutTask mTimeoutTask = new TimeoutTask();
198 private LightAnimator mLightAnimator = new LightAnimator();
199 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700200 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700202 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700204 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700205 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private boolean mIsPowered = false;
207 private IActivityManager mActivityService;
208 private IBatteryStats mBatteryStats;
209 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700210 private SensorManager mSensorManager;
211 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400212 private Sensor mLightSensor;
213 private boolean mLightSensorEnabled;
214 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700215 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500216 private int mLightSensorScreenBrightness = -1;
217 private int mLightSensorButtonBrightness = -1;
218 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private boolean mDimScreen = true;
220 private long mNextTimeout;
221 private volatile int mPokey = 0;
222 private volatile boolean mPokeAwakeOnSet = false;
223 private volatile boolean mInitComplete = false;
224 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500225 // mLastScreenOnTime is the time the screen was last turned on
226 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private boolean mPreventScreenOn;
228 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500229 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400230 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700231 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700232 private int[] mAutoBrightnessLevels;
233 private int[] mLcdBacklightValues;
234 private int[] mButtonBacklightValues;
235 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500236 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
238 // Used when logging number and duration of touch-down cycles
239 private long mTotalTouchDownTime;
240 private long mLastTouchDown;
241 private int mTouchCycles;
242
243 // could be either static or controllable at runtime
244 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500245 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400246 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 /*
249 static PrintStream mLog;
250 static {
251 try {
252 mLog = new PrintStream("/data/power.log");
253 }
254 catch (FileNotFoundException e) {
255 android.util.Log.e(TAG, "Life is hard", e);
256 }
257 }
258 static class Log {
259 static void d(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.d(tag, s);
262 }
263 static void i(String tag, String s) {
264 mLog.println(s);
265 android.util.Log.i(tag, s);
266 }
267 static void w(String tag, String s) {
268 mLog.println(s);
269 android.util.Log.w(tag, s);
270 }
271 static void e(String tag, String s) {
272 mLog.println(s);
273 android.util.Log.e(tag, s);
274 }
275 }
276 */
277
278 /**
279 * This class works around a deadlock between the lock in PowerManager.WakeLock
280 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
281 * mToken object so it can be accessed from any thread, but it calls into here
282 * with its lock held. This class is essentially a reimplementation of
283 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
284 * only call it with our own locks held.
285 */
286 private class UnsynchronizedWakeLock {
287 int mFlags;
288 String mTag;
289 IBinder mToken;
290 int mCount = 0;
291 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500292 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293
294 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
295 mFlags = flags;
296 mTag = tag;
297 mToken = new Binder();
298 mRefCounted = refCounted;
299 }
300
301 public void acquire() {
302 if (!mRefCounted || mCount++ == 0) {
303 long ident = Binder.clearCallingIdentity();
304 try {
305 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
306 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500307 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 } finally {
309 Binder.restoreCallingIdentity(ident);
310 }
311 }
312 }
313
314 public void release() {
315 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500316 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500317 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319 if (mCount < 0) {
320 throw new RuntimeException("WakeLock under-locked " + mTag);
321 }
322 }
323
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500324 public boolean isHeld()
325 {
326 return mHeld;
327 }
328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 public String toString() {
330 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500331 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333 }
334
335 private final class BatteryReceiver extends BroadcastReceiver {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 synchronized (mLocks) {
339 boolean wasPowered = mIsPowered;
340 mIsPowered = mBatteryService.isPowered();
341
342 if (mIsPowered != wasPowered) {
343 // update mStayOnWhilePluggedIn wake lock
344 updateWakeLockLocked();
345
346 // treat plugging and unplugging the devices as a user activity.
347 // users find it disconcerting when they unplug the device
348 // and it shuts off right away.
349 // temporarily set mUserActivityAllowed to true so this will work
350 // even when the keyguard is on.
351 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400352 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354 }
355 }
356 }
357 }
358
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500359 private final class BootCompletedReceiver extends BroadcastReceiver {
360 @Override
361 public void onReceive(Context context, Intent intent) {
362 bootCompleted();
363 }
364 }
365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 /**
367 * Set the setting that determines whether the device stays on when plugged in.
368 * The argument is a bit string, with each bit specifying a power source that,
369 * when the device is connected to that source, causes the device to stay on.
370 * See {@link android.os.BatteryManager} for the list of power sources that
371 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
372 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
373 * @param val an {@code int} containing the bits that specify which power sources
374 * should cause the device to stay on.
375 */
376 public void setStayOnSetting(int val) {
377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
378 Settings.System.putInt(mContext.getContentResolver(),
379 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
380 }
381
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800382 public void setMaximumScreenOffTimeount(int timeMs) {
383 mContext.enforceCallingOrSelfPermission(
384 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
385 synchronized (mLocks) {
386 mMaximumScreenOffTimeout = timeMs;
387 // recalculate everything
388 setScreenOffTimeoutsLocked();
389 }
390 }
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 private class SettingsObserver implements Observer {
393 private int getInt(String name) {
394 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
395 }
396
397 public void update(Observable o, Object arg) {
398 synchronized (mLocks) {
399 // STAY_ON_WHILE_PLUGGED_IN
400 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
401 updateWakeLockLocked();
402
403 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800404 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405
406 // DIM_SCREEN
407 //mDimScreen = getInt(DIM_SCREEN) != 0;
408
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700409 // SCREEN_BRIGHTNESS_MODE
410 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 // recalculate everything
413 setScreenOffTimeoutsLocked();
414 }
415 }
416 }
417
418 PowerManagerService()
419 {
420 // Hack to get our uid... should have a func for this.
421 long token = Binder.clearCallingIdentity();
422 MY_UID = Binder.getCallingUid();
423 Binder.restoreCallingIdentity(token);
424
425 // XXX remove this when the kernel doesn't timeout wake locks
426 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
427
428 // assume nothing is on yet
429 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 // Add ourself to the Watchdog monitors.
432 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 }
434
435 private ContentQueryMap mSettings;
436
Mike Lockwood3a322132009-11-24 00:30:52 -0500437 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700438 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500439 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mContext = context;
441 mActivityService = activity;
442 mBatteryStats = BatteryStatsService.getService();
443 mBatteryService = battery;
444
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500445 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
446 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
447 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
448 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 mHandlerThread = new HandlerThread("PowerManagerService") {
451 @Override
452 protected void onLooperPrepared() {
453 super.onLooperPrepared();
454 initInThread();
455 }
456 };
457 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 synchronized (mHandlerThread) {
460 while (!mInitComplete) {
461 try {
462 mHandlerThread.wait();
463 } catch (InterruptedException e) {
464 // Ignore
465 }
466 }
467 }
468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 void initInThread() {
471 mHandler = new Handler();
472
473 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700474 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
476 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
477 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
478 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
479 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
480 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500481 mProximityPartialLock = new UnsynchronizedWakeLock(
482 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483
484 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
485 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
486 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
487 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
488
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700489 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400490
491 // read settings for auto-brightness
492 mUseSoftwareAutoBrightness = resources.getBoolean(
493 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400494 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700495 mAutoBrightnessLevels = resources.getIntArray(
496 com.android.internal.R.array.config_autoBrightnessLevels);
497 mLcdBacklightValues = resources.getIntArray(
498 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
499 mButtonBacklightValues = resources.getIntArray(
500 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
501 mKeyboardBacklightValues = resources.getIntArray(
502 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500503 mLightSensorWarmupTime = resources.getInteger(
504 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700505 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700506
507 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
509 "(" + Settings.System.NAME + "=?) or ("
510 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700511 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700513 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
514 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 null);
516 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
517 SettingsObserver settingsObserver = new SettingsObserver();
518 mSettings.addObserver(settingsObserver);
519
520 // pretend that the settings changed so we will get their initial state
521 settingsObserver.update(mSettings, null);
522
523 // register for the battery changed notifications
524 IntentFilter filter = new IntentFilter();
525 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
526 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500527 filter = new IntentFilter();
528 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
529 mContext.registerReceiver(new BootCompletedReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
Doug Zongker43866e02010-01-07 12:09:54 -0800531 // Listen for secure settings changes
532 mContext.getContentResolver().registerContentObserver(
533 Settings.Secure.CONTENT_URI, true,
534 new ContentObserver(new Handler()) {
535 public void onChange(boolean selfChange) {
536 updateSettingsValues();
537 }
538 });
539 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
Mike Lockwood4984e732009-11-01 08:16:33 -0500541 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400542 // turn the screen on
543 setPowerState(SCREEN_BRIGHT);
544 } else {
545 // turn everything on
546 setPowerState(ALL_BRIGHT);
547 }
Dan Murphy951764b2009-08-27 14:59:03 -0500548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 synchronized (mHandlerThread) {
550 mInitComplete = true;
551 mHandlerThread.notifyAll();
552 }
553 }
554
555 private class WakeLock implements IBinder.DeathRecipient
556 {
557 WakeLock(int f, IBinder b, String t, int u) {
558 super();
559 flags = f;
560 binder = b;
561 tag = t;
562 uid = u == MY_UID ? Process.SYSTEM_UID : u;
563 if (u != MY_UID || (
564 !"KEEP_SCREEN_ON_FLAG".equals(tag)
565 && !"KeyInputQueue".equals(tag))) {
566 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
567 ? BatteryStats.WAKE_TYPE_PARTIAL
568 : BatteryStats.WAKE_TYPE_FULL;
569 } else {
570 monitorType = -1;
571 }
572 try {
573 b.linkToDeath(this, 0);
574 } catch (RemoteException e) {
575 binderDied();
576 }
577 }
578 public void binderDied() {
579 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500580 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 }
582 }
583 final int flags;
584 final IBinder binder;
585 final String tag;
586 final int uid;
587 final int monitorType;
588 boolean activated = true;
589 int minState;
590 }
591
592 private void updateWakeLockLocked() {
593 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
594 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
595 mStayOnWhilePluggedInScreenDimLock.acquire();
596 mStayOnWhilePluggedInPartialLock.acquire();
597 } else {
598 mStayOnWhilePluggedInScreenDimLock.release();
599 mStayOnWhilePluggedInPartialLock.release();
600 }
601 }
602
603 private boolean isScreenLock(int flags)
604 {
605 int n = flags & LOCK_MASK;
606 return n == PowerManager.FULL_WAKE_LOCK
607 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
608 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
609 }
610
611 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700613 if (uid != Process.myUid()) {
614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 long ident = Binder.clearCallingIdentity();
617 try {
618 synchronized (mLocks) {
619 acquireWakeLockLocked(flags, lock, uid, tag);
620 }
621 } finally {
622 Binder.restoreCallingIdentity(ident);
623 }
624 }
625
626 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
627 int acquireUid = -1;
628 String acquireName = null;
629 int acquireType = -1;
630
631 if (mSpew) {
632 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
633 }
634
635 int index = mLocks.getIndex(lock);
636 WakeLock wl;
637 boolean newlock;
638 if (index < 0) {
639 wl = new WakeLock(flags, lock, tag, uid);
640 switch (wl.flags & LOCK_MASK)
641 {
642 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500643 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400644 wl.minState = SCREEN_BRIGHT;
645 } else {
646 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 break;
649 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
650 wl.minState = SCREEN_BRIGHT;
651 break;
652 case PowerManager.SCREEN_DIM_WAKE_LOCK:
653 wl.minState = SCREEN_DIM;
654 break;
655 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700656 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 break;
658 default:
659 // just log and bail. we're in the server, so don't
660 // throw an exception.
661 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
662 + " flags=" + flags);
663 return;
664 }
665 mLocks.addLock(wl);
666 newlock = true;
667 } else {
668 wl = mLocks.get(index);
669 newlock = false;
670 }
671 if (isScreenLock(flags)) {
672 // if this causes a wakeup, we reactivate all of the locks and
673 // set it to whatever they want. otherwise, we modulate that
674 // by the current state so we never turn it more on than
675 // it already is.
676 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700677 int oldWakeLockState = mWakeLockState;
678 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 if (mSpew) {
680 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700681 + " mWakeLockState=0x"
682 + Integer.toHexString(mWakeLockState)
683 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 } else {
686 if (mSpew) {
687 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
688 + " mLocks.gatherState()=0x"
689 + Integer.toHexString(mLocks.gatherState())
690 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
691 }
692 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
693 }
694 setPowerState(mWakeLockState | mUserState);
695 }
696 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
697 if (newlock) {
698 mPartialCount++;
699 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800700 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
702 }
703 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700704 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500705 mProximityWakeLockCount++;
706 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700707 enableProximityLockLocked();
708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710 if (newlock) {
711 acquireUid = wl.uid;
712 acquireName = wl.tag;
713 acquireType = wl.monitorType;
714 }
715
716 if (acquireType >= 0) {
717 try {
718 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
719 } catch (RemoteException e) {
720 // Ignore
721 }
722 }
723 }
724
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500725 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700726 int uid = Binder.getCallingUid();
727 if (uid != Process.myUid()) {
728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730
731 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500732 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734 }
735
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500736 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 int releaseUid;
738 String releaseName;
739 int releaseType;
740
741 WakeLock wl = mLocks.removeLock(lock);
742 if (wl == null) {
743 return;
744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 if (mSpew) {
747 Log.d(TAG, "releaseWakeLock flags=0x"
748 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
749 }
750
751 if (isScreenLock(wl.flags)) {
752 mWakeLockState = mLocks.gatherState();
753 // goes in the middle to reduce flicker
754 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
755 userActivity(SystemClock.uptimeMillis(), false);
756 }
757 setPowerState(mWakeLockState | mUserState);
758 }
759 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
760 mPartialCount--;
761 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800762 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 Power.releaseWakeLock(PARTIAL_NAME);
764 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700765 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500766 mProximityWakeLockCount--;
767 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500768 if (mProximitySensorActive &&
769 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500770 // wait for proximity sensor to go negative before disabling sensor
771 if (mDebugProximitySensor) {
772 Log.d(TAG, "waiting for proximity sensor to go negative");
773 }
774 } else {
775 disableProximityLockLocked();
776 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
779 // Unlink the lock from the binder.
780 wl.binder.unlinkToDeath(wl, 0);
781 releaseUid = wl.uid;
782 releaseName = wl.tag;
783 releaseType = wl.monitorType;
784
785 if (releaseType >= 0) {
786 long origId = Binder.clearCallingIdentity();
787 try {
788 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
789 } catch (RemoteException e) {
790 // Ignore
791 } finally {
792 Binder.restoreCallingIdentity(origId);
793 }
794 }
795 }
796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 private class PokeLock implements IBinder.DeathRecipient
798 {
799 PokeLock(int p, IBinder b, String t) {
800 super();
801 this.pokey = p;
802 this.binder = b;
803 this.tag = t;
804 try {
805 b.linkToDeath(this, 0);
806 } catch (RemoteException e) {
807 binderDied();
808 }
809 }
810 public void binderDied() {
811 setPokeLock(0, this.binder, this.tag);
812 }
813 int pokey;
814 IBinder binder;
815 String tag;
816 boolean awakeOnSet;
817 }
818
819 public void setPokeLock(int pokey, IBinder token, String tag) {
820 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
821 if (token == null) {
822 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
823 return;
824 }
825
826 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
827 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
828 + " and POKE_LOCK_MEDIUM_TIMEOUT");
829 }
830
831 synchronized (mLocks) {
832 if (pokey != 0) {
833 PokeLock p = mPokeLocks.get(token);
834 int oldPokey = 0;
835 if (p != null) {
836 oldPokey = p.pokey;
837 p.pokey = pokey;
838 } else {
839 p = new PokeLock(pokey, token, tag);
840 mPokeLocks.put(token, p);
841 }
842 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
843 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
844 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
845 p.awakeOnSet = true;
846 }
847 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700848 PokeLock rLock = mPokeLocks.remove(token);
849 if (rLock != null) {
850 token.unlinkToDeath(rLock, 0);
851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853
854 int oldPokey = mPokey;
855 int cumulative = 0;
856 boolean oldAwakeOnSet = mPokeAwakeOnSet;
857 boolean awakeOnSet = false;
858 for (PokeLock p: mPokeLocks.values()) {
859 cumulative |= p.pokey;
860 if (p.awakeOnSet) {
861 awakeOnSet = true;
862 }
863 }
864 mPokey = cumulative;
865 mPokeAwakeOnSet = awakeOnSet;
866
867 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
868 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 if (oldCumulativeTimeout != newCumulativeTimeout) {
871 setScreenOffTimeoutsLocked();
872 // reset the countdown timer, but use the existing nextState so it doesn't
873 // change anything
874 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
875 }
876 }
877 }
878
879 private static String lockType(int type)
880 {
881 switch (type)
882 {
883 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700884 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700886 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700888 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700890 return "PARTIAL_WAKE_LOCK ";
891 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
892 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 default:
David Brown251faa62009-08-02 22:04:36 -0700894 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896 }
897
898 private static String dumpPowerState(int state) {
899 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
900 ? "KEYBOARD_BRIGHT_BIT " : "")
901 + (((state & SCREEN_BRIGHT_BIT) != 0)
902 ? "SCREEN_BRIGHT_BIT " : "")
903 + (((state & SCREEN_ON_BIT) != 0)
904 ? "SCREEN_ON_BIT " : "")
905 + (((state & BATTERY_LOW_BIT) != 0)
906 ? "BATTERY_LOW_BIT " : "");
907 }
908
909 @Override
910 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
911 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
912 != PackageManager.PERMISSION_GRANTED) {
913 pw.println("Permission Denial: can't dump PowerManager from from pid="
914 + Binder.getCallingPid()
915 + ", uid=" + Binder.getCallingUid());
916 return;
917 }
918
919 long now = SystemClock.uptimeMillis();
920
921 pw.println("Power Manager State:");
922 pw.println(" mIsPowered=" + mIsPowered
923 + " mPowerState=" + mPowerState
924 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
925 + " ms");
926 pw.println(" mPartialCount=" + mPartialCount);
927 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
928 pw.println(" mUserState=" + dumpPowerState(mUserState));
929 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
930 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
931 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
932 + " " + ((mNextTimeout-now)/1000) + "s from now");
933 pw.println(" mDimScreen=" + mDimScreen
934 + " mStayOnConditions=" + mStayOnConditions);
Mike Lockwood435eb642009-12-03 08:40:18 -0500935 pw.println(" mScreenOffReason=" + mScreenOffReason
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700937 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
938 + ',' + mBroadcastQueue[2] + "}");
939 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
940 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
942 pw.println(" mKeyboardVisible=" + mKeyboardVisible
943 + " mUserActivityAllowed=" + mUserActivityAllowed);
944 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
945 + " mScreenOffDelay=" + mScreenOffDelay);
946 pw.println(" mPreventScreenOn=" + mPreventScreenOn
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500947 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
948 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800949 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
950 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500951 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
953 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
954 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
955 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500956 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500957 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
958 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700959 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500960 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
961 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700962 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500963 pw.println(" mLightSensorValue=" + mLightSensorValue
964 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
965 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
966 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
967 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400968 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700969 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 mScreenBrightness.dump(pw, " mScreenBrightness: ");
971 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
972 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 int N = mLocks.size();
975 pw.println();
976 pw.println("mLocks.size=" + N + ":");
977 for (int i=0; i<N; i++) {
978 WakeLock wl = mLocks.get(i);
979 String type = lockType(wl.flags & LOCK_MASK);
980 String acquireCausesWakeup = "";
981 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
982 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
983 }
984 String activated = "";
985 if (wl.activated) {
986 activated = " activated";
987 }
988 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
989 + activated + " (minState=" + wl.minState + ")");
990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 pw.println();
993 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
994 for (PokeLock p: mPokeLocks.values()) {
995 pw.println(" poke lock '" + p.tag + "':"
996 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
997 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700998 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
999 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1001 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1002 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1003 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
1004 }
1005
1006 pw.println();
1007 }
1008
1009 private void setTimeoutLocked(long now, int nextState)
1010 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001011 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 mHandler.removeCallbacks(mTimeoutTask);
1013 mTimeoutTask.nextState = nextState;
1014 long when = now;
1015 switch (nextState)
1016 {
1017 case SCREEN_BRIGHT:
1018 when += mKeylightDelay;
1019 break;
1020 case SCREEN_DIM:
1021 if (mDimDelay >= 0) {
1022 when += mDimDelay;
1023 break;
1024 } else {
1025 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1026 }
1027 case SCREEN_OFF:
1028 synchronized (mLocks) {
1029 when += mScreenOffDelay;
1030 }
1031 break;
1032 }
1033 if (mSpew) {
1034 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1035 + " when=" + when);
1036 }
1037 mHandler.postAtTime(mTimeoutTask, when);
1038 mNextTimeout = when; // for debugging
1039 }
1040 }
1041
1042 private void cancelTimerLocked()
1043 {
1044 mHandler.removeCallbacks(mTimeoutTask);
1045 mTimeoutTask.nextState = -1;
1046 }
1047
1048 private class TimeoutTask implements Runnable
1049 {
1050 int nextState; // access should be synchronized on mLocks
1051 public void run()
1052 {
1053 synchronized (mLocks) {
1054 if (mSpew) {
1055 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1056 }
1057
1058 if (nextState == -1) {
1059 return;
1060 }
1061
1062 mUserState = this.nextState;
1063 setPowerState(this.nextState | mWakeLockState);
1064
1065 long now = SystemClock.uptimeMillis();
1066
1067 switch (this.nextState)
1068 {
1069 case SCREEN_BRIGHT:
1070 if (mDimDelay >= 0) {
1071 setTimeoutLocked(now, SCREEN_DIM);
1072 break;
1073 }
1074 case SCREEN_DIM:
1075 setTimeoutLocked(now, SCREEN_OFF);
1076 break;
1077 }
1078 }
1079 }
1080 }
1081
1082 private void sendNotificationLocked(boolean on, int why)
1083 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001084 if (!on) {
1085 mStillNeedSleepNotification = false;
1086 }
1087
Joe Onorato128e7292009-03-24 18:41:31 -07001088 // Add to the queue.
1089 int index = 0;
1090 while (mBroadcastQueue[index] != -1) {
1091 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
Joe Onorato128e7292009-03-24 18:41:31 -07001093 mBroadcastQueue[index] = on ? 1 : 0;
1094 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095
Joe Onorato128e7292009-03-24 18:41:31 -07001096 // If we added it position 2, then there is a pair that can be stripped.
1097 // If we added it position 1 and we're turning the screen off, we can strip
1098 // the pair and do nothing, because the screen is already off, and therefore
1099 // keyguard has already been enabled.
1100 // However, if we added it at position 1 and we're turning it on, then position
1101 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1102 // on, so have to run the queue then.
1103 if (index == 2) {
1104 // Also, while we're collapsing them, if it's going to be an "off," and one
1105 // is off because of user, then use that, regardless of whether it's the first
1106 // or second one.
1107 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1108 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1109 }
1110 mBroadcastQueue[0] = on ? 1 : 0;
1111 mBroadcastQueue[1] = -1;
1112 mBroadcastQueue[2] = -1;
1113 index = 0;
1114 }
1115 if (index == 1 && !on) {
1116 mBroadcastQueue[0] = -1;
1117 mBroadcastQueue[1] = -1;
1118 index = -1;
1119 // The wake lock was being held, but we're not actually going to do any
1120 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001121 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001123 }
1124
1125 // Now send the message.
1126 if (index >= 0) {
1127 // Acquire the broadcast wake lock before changing the power
1128 // state. It will be release after the broadcast is sent.
1129 // We always increment the ref count for each notification in the queue
1130 // and always decrement when that notification is handled.
1131 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001132 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001133 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 }
1136
1137 private Runnable mNotificationTask = new Runnable()
1138 {
1139 public void run()
1140 {
Joe Onorato128e7292009-03-24 18:41:31 -07001141 while (true) {
1142 int value;
1143 int why;
1144 WindowManagerPolicy policy;
1145 synchronized (mLocks) {
1146 value = mBroadcastQueue[0];
1147 why = mBroadcastWhy[0];
1148 for (int i=0; i<2; i++) {
1149 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1150 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1151 }
1152 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
Joe Onorato128e7292009-03-24 18:41:31 -07001154 if (value == 1) {
1155 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001156
Joe Onorato128e7292009-03-24 18:41:31 -07001157 policy.screenTurnedOn();
1158 try {
1159 ActivityManagerNative.getDefault().wakingUp();
1160 } catch (RemoteException e) {
1161 // ignore it
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163
Joe Onorato128e7292009-03-24 18:41:31 -07001164 if (mSpew) {
1165 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1166 }
1167 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1168 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1169 mScreenOnBroadcastDone, mHandler, 0, null, null);
1170 } else {
1171 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001172 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001173 mBroadcastWakeLock.mCount);
1174 mBroadcastWakeLock.release();
1175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177 }
Joe Onorato128e7292009-03-24 18:41:31 -07001178 else if (value == 0) {
1179 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001180
Joe Onorato128e7292009-03-24 18:41:31 -07001181 policy.screenTurnedOff(why);
1182 try {
1183 ActivityManagerNative.getDefault().goingToSleep();
1184 } catch (RemoteException e) {
1185 // ignore it.
1186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187
Joe Onorato128e7292009-03-24 18:41:31 -07001188 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1189 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1190 mScreenOffBroadcastDone, mHandler, 0, null, null);
1191 } else {
1192 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001194 mBroadcastWakeLock.mCount);
1195 mBroadcastWakeLock.release();
1196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198 }
Joe Onorato128e7292009-03-24 18:41:31 -07001199 else {
1200 // If we're in this case, then this handler is running for a previous
1201 // paired transaction. mBroadcastWakeLock will already have been released.
1202 break;
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205 }
1206 };
1207
1208 long mScreenOnStart;
1209 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1210 public void onReceive(Context context, Intent intent) {
1211 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1214 mBroadcastWakeLock.release();
1215 }
1216 }
1217 };
1218
1219 long mScreenOffStart;
1220 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1221 public void onReceive(Context context, Intent intent) {
1222 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001223 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1225 mBroadcastWakeLock.release();
1226 }
1227 }
1228 };
1229
1230 void logPointerUpEvent() {
1231 if (LOG_TOUCH_DOWNS) {
1232 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1233 mLastTouchDown = 0;
1234 }
1235 }
1236
1237 void logPointerDownEvent() {
1238 if (LOG_TOUCH_DOWNS) {
1239 // If we are not already timing a down/up sequence
1240 if (mLastTouchDown == 0) {
1241 mLastTouchDown = SystemClock.elapsedRealtime();
1242 mTouchCycles++;
1243 }
1244 }
1245 }
1246
1247 /**
1248 * Prevents the screen from turning on even if it *should* turn on due
1249 * to a subsequent full wake lock being acquired.
1250 * <p>
1251 * This is a temporary hack that allows an activity to "cover up" any
1252 * display glitches that happen during the activity's startup
1253 * sequence. (Specifically, this API was added to work around a
1254 * cosmetic bug in the "incoming call" sequence, where the lock screen
1255 * would flicker briefly before the incoming call UI became visible.)
1256 * TODO: There ought to be a more elegant way of doing this,
1257 * probably by having the PowerManager and ActivityManager
1258 * work together to let apps specify that the screen on/off
1259 * state should be synchronized with the Activity lifecycle.
1260 * <p>
1261 * Note that calling preventScreenOn(true) will NOT turn the screen
1262 * off if it's currently on. (This API only affects *future*
1263 * acquisitions of full wake locks.)
1264 * But calling preventScreenOn(false) WILL turn the screen on if
1265 * it's currently off because of a prior preventScreenOn(true) call.
1266 * <p>
1267 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1268 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1269 * call doesn't occur within 5 seconds, we'll turn the screen back on
1270 * ourselves (and log a warning about it); this prevents a buggy app
1271 * from disabling the screen forever.)
1272 * <p>
1273 * TODO: this feature should really be controlled by a new type of poke
1274 * lock (rather than an IPowerManager call).
1275 */
1276 public void preventScreenOn(boolean prevent) {
1277 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1278
1279 synchronized (mLocks) {
1280 if (prevent) {
1281 // First of all, grab a partial wake lock to
1282 // make sure the CPU stays on during the entire
1283 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1284 mPreventScreenOnPartialLock.acquire();
1285
1286 // Post a forceReenableScreen() call (for 5 seconds in the
1287 // future) to make sure the matching preventScreenOn(false) call
1288 // has happened by then.
1289 mHandler.removeCallbacks(mForceReenableScreenTask);
1290 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1291
1292 // Finally, set the flag that prevents the screen from turning on.
1293 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001294 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 mPreventScreenOn = true;
1296 } else {
1297 // (Re)enable the screen.
1298 mPreventScreenOn = false;
1299
1300 // We're "undoing" a the prior preventScreenOn(true) call, so we
1301 // no longer need the 5-second safeguard.
1302 mHandler.removeCallbacks(mForceReenableScreenTask);
1303
1304 // Forcibly turn on the screen if it's supposed to be on. (This
1305 // handles the case where the screen is currently off because of
1306 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001307 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (mSpew) {
1309 Log.d(TAG,
1310 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1311 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001312 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001314 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 }
1317
1318 // Release the partial wake lock that we held during the
1319 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1320 mPreventScreenOnPartialLock.release();
1321 }
1322 }
1323 }
1324
1325 public void setScreenBrightnessOverride(int brightness) {
1326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1327
1328 synchronized (mLocks) {
1329 if (mScreenBrightnessOverride != brightness) {
1330 mScreenBrightnessOverride = brightness;
1331 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1332 }
1333 }
1334 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001335
1336 public void setButtonBrightnessOverride(int brightness) {
1337 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1338
1339 synchronized (mLocks) {
1340 if (mButtonBrightnessOverride != brightness) {
1341 mButtonBrightnessOverride = brightness;
1342 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1343 }
1344 }
1345 }
1346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 /**
1348 * Sanity-check that gets called 5 seconds after any call to
1349 * preventScreenOn(true). This ensures that the original call
1350 * is followed promptly by a call to preventScreenOn(false).
1351 */
1352 private void forceReenableScreen() {
1353 // We shouldn't get here at all if mPreventScreenOn is false, since
1354 // we should have already removed any existing
1355 // mForceReenableScreenTask messages...
1356 if (!mPreventScreenOn) {
1357 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1358 return;
1359 }
1360
1361 // Uh oh. It's been 5 seconds since a call to
1362 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1363 // This means the app that called preventScreenOn(true) is either
1364 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1365 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1366 // crashed before doing so.)
1367
1368 // Log a warning, and forcibly turn the screen back on.
1369 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1370 + "Forcing the screen back on...");
1371 preventScreenOn(false);
1372 }
1373
1374 private Runnable mForceReenableScreenTask = new Runnable() {
1375 public void run() {
1376 forceReenableScreen();
1377 }
1378 };
1379
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001380 private int setScreenStateLocked(boolean on) {
1381 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001382 if (err == 0) {
1383 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1384 if (mUseSoftwareAutoBrightness) {
1385 enableLightSensor(on);
1386 if (!on) {
1387 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001388 mButtonLight.turnOff();
1389 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001390 // clear current value so we will update based on the new conditions
1391 // when the sensor is reenabled.
1392 mLightSensorValue = -1;
1393 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001394 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001395 }
1396 return err;
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 private void setPowerState(int state)
1400 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001401 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403
Mike Lockwood435eb642009-12-03 08:40:18 -05001404 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 {
1406 synchronized (mLocks) {
1407 int err;
1408
1409 if (mSpew) {
1410 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1411 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001412 + " noChangeLights=" + noChangeLights
1413 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
1416 if (noChangeLights) {
1417 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1418 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001419 if (mProximitySensorActive) {
1420 // don't turn on the screen when the proximity sensor lock is held
1421 newState = (newState & ~SCREEN_BRIGHT);
1422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
1424 if (batteryIsLow()) {
1425 newState |= BATTERY_LOW_BIT;
1426 } else {
1427 newState &= ~BATTERY_LOW_BIT;
1428 }
1429 if (newState == mPowerState) {
1430 return;
1431 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001432
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001433 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 newState |= ALL_BRIGHT;
1435 }
1436
1437 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1438 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1439
Mike Lockwood51b84492009-11-16 21:51:18 -05001440 if (mSpew) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1442 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1443 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1444 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1445 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1446 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1447 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1448 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1449 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1450 + " newScreenOn=" + newScreenOn);
1451 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1452 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1453 }
1454
1455 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001456 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1458 }
1459
1460 if (oldScreenOn != newScreenOn) {
1461 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001462 // When the user presses the power button, we need to always send out the
1463 // notification that it's going to sleep so the keyguard goes on. But
1464 // we can't do that until the screen fades out, so we don't show the keyguard
1465 // too early.
1466 if (mStillNeedSleepNotification) {
1467 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 // Turn on the screen UNLESS there was a prior
1471 // preventScreenOn(true) request. (Note that the lifetime
1472 // of a single preventScreenOn() request is limited to 5
1473 // seconds to prevent a buggy app from disabling the
1474 // screen forever; see forceReenableScreen().)
1475 boolean reallyTurnScreenOn = true;
1476 if (mSpew) {
1477 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1478 + mPreventScreenOn);
1479 }
1480
1481 if (mPreventScreenOn) {
1482 if (mSpew) {
1483 Log.d(TAG, "- PREVENTING screen from really turning on!");
1484 }
1485 reallyTurnScreenOn = false;
1486 }
1487 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001488 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 long identity = Binder.clearCallingIdentity();
1490 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001491 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 mBatteryStats.noteScreenOn();
1493 } catch (RemoteException e) {
1494 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1495 } finally {
1496 Binder.restoreCallingIdentity(identity);
1497 }
1498 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001499 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 // But continue as if we really did turn the screen on...
1501 err = 0;
1502 }
1503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 mLastTouchDown = 0;
1505 mTotalTouchDownTime = 0;
1506 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001507 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 mTotalTouchDownTime, mTouchCycles);
1509 if (err == 0) {
1510 mPowerState |= SCREEN_ON_BIT;
1511 sendNotificationLocked(true, -1);
1512 }
1513 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001514 // cancel light sensor task
1515 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 mScreenOffTime = SystemClock.elapsedRealtime();
1517 long identity = Binder.clearCallingIdentity();
1518 try {
1519 mBatteryStats.noteScreenOff();
1520 } catch (RemoteException e) {
1521 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1522 } finally {
1523 Binder.restoreCallingIdentity(identity);
1524 }
1525 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001526 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001528 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 err = 0;
1531 mLastTouchDown = 0;
1532 }
1533 }
1534 }
1535 }
1536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001537
Mike Lockwood435eb642009-12-03 08:40:18 -05001538 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001540 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001542 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001544 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001546 mScreenOffReason = reason;
1547 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 return err;
1550 }
1551
1552 private boolean batteryIsLow() {
1553 return (!mIsPowered &&
1554 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1555 }
1556
The Android Open Source Project10592532009-03-18 17:39:46 -07001557 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001558 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001559 newState = applyButtonState(newState);
1560 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001561 final int realDifference = (newState ^ oldState);
1562 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001564 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 int offMask = 0;
1568 int dimMask = 0;
1569 int onMask = 0;
1570
1571 int preferredBrightness = getPreferredBrightness();
1572 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1575 if (ANIMATE_KEYBOARD_LIGHTS) {
1576 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1577 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001578 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001579 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001581 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001582 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1583 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585 startAnimation = true;
1586 } else {
1587 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001588 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001590 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592 }
1593 }
1594
1595 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1596 if (ANIMATE_BUTTON_LIGHTS) {
1597 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1598 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001599 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001600 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001602 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001603 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1604 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606 startAnimation = true;
1607 } else {
1608 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001609 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001611 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
1613 }
1614 }
1615
1616 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1617 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001618 int nominalCurrentValue = -1;
1619 // If there was an actual difference in the light state, then
1620 // figure out the "ideal" current value based on the previous
1621 // state. Otherwise, this is a change due to the brightness
1622 // override, so we want to animate from whatever the current
1623 // value is.
1624 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1625 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1626 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1627 nominalCurrentValue = preferredBrightness;
1628 break;
1629 case SCREEN_ON_BIT:
1630 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1631 break;
1632 case 0:
1633 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1634 break;
1635 case SCREEN_BRIGHT_BIT:
1636 default:
1637 // not possible
1638 nominalCurrentValue = (int)mScreenBrightness.curValue;
1639 break;
1640 }
Joe Onorato128e7292009-03-24 18:41:31 -07001641 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001642 int brightness = preferredBrightness;
1643 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1645 // dim or turn off backlight, depending on if the screen is on
1646 // the scale is because the brightness ramp isn't linear and this biases
1647 // it so the later parts take longer.
1648 final float scale = 1.5f;
1649 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1650 if (ratio > 1.0f) ratio = 1.0f;
1651 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1653 // was bright
1654 steps = ANIM_STEPS;
1655 } else {
1656 // was dim
1657 steps = (int)(ANIM_STEPS*ratio*scale);
1658 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001659 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 if ((oldState & SCREEN_ON_BIT) != 0) {
1662 // was bright
1663 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1664 } else {
1665 // was dim
1666 steps = (int)(ANIM_STEPS*ratio);
1667 }
1668 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1669 // If the "stay on while plugged in" option is
1670 // turned on, then the screen will often not
1671 // automatically turn off while plugged in. To
1672 // still have a sense of when it is inactive, we
1673 // will then count going dim as turning off.
1674 mScreenOffTime = SystemClock.elapsedRealtime();
1675 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001676 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001679 long identity = Binder.clearCallingIdentity();
1680 try {
1681 mBatteryStats.noteScreenBrightness(brightness);
1682 } catch (RemoteException e) {
1683 // Nothing interesting to do.
1684 } finally {
1685 Binder.restoreCallingIdentity(identity);
1686 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001687 if (mScreenBrightness.setTargetLocked(brightness,
1688 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1689 startAnimation = true;
1690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 } else {
1692 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1693 // dim or turn off backlight, depending on if the screen is on
1694 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001695 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001697 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001700 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703 }
1704
1705 if (startAnimation) {
1706 if (mSpew) {
1707 Log.i(TAG, "Scheduling light animator!");
1708 }
1709 mHandler.removeCallbacks(mLightAnimator);
1710 mHandler.post(mLightAnimator);
1711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (offMask != 0) {
1714 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001715 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717 if (dimMask != 0) {
1718 int brightness = Power.BRIGHTNESS_DIM;
1719 if ((newState & BATTERY_LOW_BIT) != 0 &&
1720 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1721 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1722 }
1723 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001724 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726 if (onMask != 0) {
1727 int brightness = getPreferredBrightness();
1728 if ((newState & BATTERY_LOW_BIT) != 0 &&
1729 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1730 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1731 }
1732 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001733 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736
The Android Open Source Project10592532009-03-18 17:39:46 -07001737 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001738 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001739 ? LightsService.BRIGHTNESS_MODE_SENSOR
1740 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001741 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001742 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001743 }
1744 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001745 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001746 }
1747 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001748 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751
1752 class BrightnessState {
1753 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 boolean initialized;
1756 int targetValue;
1757 float curValue;
1758 float delta;
1759 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 BrightnessState(int m) {
1762 mask = m;
1763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 public void dump(PrintWriter pw, String prefix) {
1766 pw.println(prefix + "animating=" + animating
1767 + " targetValue=" + targetValue
1768 + " curValue=" + curValue
1769 + " delta=" + delta);
1770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001771
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001772 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001773 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 if (!initialized) {
1775 initialized = true;
1776 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001777 } else if (targetValue == target) {
1778 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 }
1780 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001781 delta = (targetValue -
1782 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1783 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001785 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001787 + " target=" + targetValue + " delta=" + delta
1788 + " nominalCurrentValue=" + nominalCurrentValue
1789 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001792 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 boolean stepLocked() {
1796 if (!animating) return false;
1797 if (false && mSpew) {
1798 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1799 + " target=" + targetValue + " delta=" + delta);
1800 }
1801 curValue += delta;
1802 int curIntValue = (int)curValue;
1803 boolean more = true;
1804 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001805 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 more = false;
1807 } else if (delta > 0) {
1808 if (curIntValue >= targetValue) {
1809 curValue = curIntValue = targetValue;
1810 more = false;
1811 }
1812 } else {
1813 if (curIntValue <= targetValue) {
1814 curValue = curIntValue = targetValue;
1815 more = false;
1816 }
1817 }
1818 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001819 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 animating = more;
1821 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001822 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001823 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826 return more;
1827 }
1828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 private class LightAnimator implements Runnable {
1831 public void run() {
1832 synchronized (mLocks) {
1833 long now = SystemClock.uptimeMillis();
1834 boolean more = mScreenBrightness.stepLocked();
1835 if (mKeyboardBrightness.stepLocked()) {
1836 more = true;
1837 }
1838 if (mButtonBrightness.stepLocked()) {
1839 more = true;
1840 }
1841 if (more) {
1842 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1843 }
1844 }
1845 }
1846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 private int getPreferredBrightness() {
1849 try {
1850 if (mScreenBrightnessOverride >= 0) {
1851 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001852 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001853 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001854 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1857 SCREEN_BRIGHTNESS);
1858 // Don't let applications turn the screen all the way off
1859 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1860 } catch (SettingNotFoundException snfe) {
1861 return Power.BRIGHTNESS_ON;
1862 }
1863 }
1864
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001865 private int applyButtonState(int state) {
1866 int brightness = -1;
1867 if (mButtonBrightnessOverride >= 0) {
1868 brightness = mButtonBrightnessOverride;
1869 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1870 brightness = mLightSensorButtonBrightness;
1871 }
1872 if (brightness > 0) {
1873 return state | BUTTON_BRIGHT_BIT;
1874 } else if (brightness == 0) {
1875 return state & ~BUTTON_BRIGHT_BIT;
1876 } else {
1877 return state;
1878 }
1879 }
1880
1881 private int applyKeyboardState(int state) {
1882 int brightness = -1;
1883 if (!mKeyboardVisible) {
1884 brightness = 0;
1885 } else if (mButtonBrightnessOverride >= 0) {
1886 brightness = mButtonBrightnessOverride;
1887 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1888 brightness = mLightSensorKeyboardBrightness;
1889 }
1890 if (brightness > 0) {
1891 return state | KEYBOARD_BRIGHT_BIT;
1892 } else if (brightness == 0) {
1893 return state & ~KEYBOARD_BRIGHT_BIT;
1894 } else {
1895 return state;
1896 }
1897 }
1898
Charles Mendis322591c2009-10-29 11:06:59 -07001899 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 synchronized (mLocks) {
1901 return (mPowerState & SCREEN_ON_BIT) != 0;
1902 }
1903 }
1904
Charles Mendis322591c2009-10-29 11:06:59 -07001905 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 synchronized (mLocks) {
1907 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1908 }
1909 }
1910
Mike Lockwood497087e32009-11-08 18:33:03 -05001911 private boolean isScreenTurningOffLocked() {
1912 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1913 }
1914
Mike Lockwood200b30b2009-09-20 00:23:59 -04001915 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001916 if (isScreenTurningOffLocked()) {
1917 // cancel animation so userActivity will succeed
1918 mScreenBrightness.animating = false;
1919 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001920 boolean savedActivityAllowed = mUserActivityAllowed;
1921 mUserActivityAllowed = true;
1922 userActivity(SystemClock.uptimeMillis(), false);
1923 mUserActivityAllowed = savedActivityAllowed;
1924 }
1925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1927 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1928 userActivity(time, noChangeLights, OTHER_EVENT, force);
1929 }
1930
1931 public void userActivity(long time, boolean noChangeLights) {
1932 userActivity(time, noChangeLights, OTHER_EVENT, false);
1933 }
1934
1935 public void userActivity(long time, boolean noChangeLights, int eventType) {
1936 userActivity(time, noChangeLights, eventType, false);
1937 }
1938
1939 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1940 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1941
1942 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001943 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001945 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 return;
1948 }
1949
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001950 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1951 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1952 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1953 if (false) {
1954 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1955 }
1956 return;
1957 }
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (false) {
1960 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1961 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1962 } else {
1963 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1964 }
1965 }
1966
1967 synchronized (mLocks) {
1968 if (mSpew) {
1969 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1970 + " mUserActivityAllowed=" + mUserActivityAllowed
1971 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001972 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1973 + " mProximitySensorActive=" + mProximitySensorActive
1974 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
Mike Lockwood05067122009-10-27 23:07:25 -04001976 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001977 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001978 Log.d(TAG, "ignoring user activity while turning off screen");
1979 return;
1980 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001981 // Disable proximity sensor if if user presses power key while we are in the
1982 // "waiting for proximity sensor to go negative" state.
1983 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1984 mProximitySensorActive = false;
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if (mLastEventTime <= time || force) {
1987 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001988 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001989 // Only turn on button backlights if a button was pressed
1990 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001991 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1993 } else {
1994 // don't clear button/keyboard backlights when the screen is touched.
1995 mUserState |= SCREEN_BRIGHT;
1996 }
1997
Dianne Hackborn617f8772009-03-31 15:04:46 -07001998 int uid = Binder.getCallingUid();
1999 long ident = Binder.clearCallingIdentity();
2000 try {
2001 mBatteryStats.noteUserActivity(uid, eventType);
2002 } catch (RemoteException e) {
2003 // Ignore
2004 } finally {
2005 Binder.restoreCallingIdentity(ident);
2006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002007
Michael Chane96440f2009-05-06 10:27:36 -07002008 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002009 setPowerState(mUserState | mWakeLockState, noChangeLights,
2010 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 setTimeoutLocked(time, SCREEN_BRIGHT);
2012 }
2013 }
2014 }
2015 }
2016
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002017 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2018 try {
2019 int i;
2020 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2021 if (sensorValue < mAutoBrightnessLevels[i]) {
2022 break;
2023 }
2024 }
2025 return values[i];
2026 } catch (Exception e) {
2027 // guard against null pointer or index out of bounds errors
2028 Log.e(TAG, "getAutoBrightnessValue", e);
2029 return 255;
2030 }
2031 }
2032
Mike Lockwood20f87d72009-11-05 16:08:51 -05002033 private Runnable mProximityTask = new Runnable() {
2034 public void run() {
2035 synchronized (mLocks) {
2036 if (mProximityPendingValue != -1) {
2037 proximityChangedLocked(mProximityPendingValue == 1);
2038 mProximityPendingValue = -1;
2039 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002040 if (mProximityPartialLock.isHeld()) {
2041 mProximityPartialLock.release();
2042 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002043 }
2044 }
2045 };
2046
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002047 private Runnable mAutoBrightnessTask = new Runnable() {
2048 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002049 synchronized (mLocks) {
2050 int value = (int)mLightSensorPendingValue;
2051 if (value >= 0) {
2052 mLightSensorPendingValue = -1;
2053 lightSensorChangedLocked(value);
2054 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002055 }
2056 }
2057 };
2058
2059 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002060 if (mDebugLightSensor) {
2061 Log.d(TAG, "lightSensorChangedLocked " + value);
2062 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002063
2064 if (mLightSensorValue != value) {
2065 mLightSensorValue = value;
2066 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
2067 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
2068 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002069 int keyboardValue;
2070 if (mKeyboardVisible) {
2071 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2072 } else {
2073 keyboardValue = 0;
2074 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002075 mLightSensorScreenBrightness = lcdValue;
2076 mLightSensorButtonBrightness = buttonValue;
2077 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002078
2079 if (mDebugLightSensor) {
2080 Log.d(TAG, "lcdValue " + lcdValue);
2081 Log.d(TAG, "buttonValue " + buttonValue);
2082 Log.d(TAG, "keyboardValue " + keyboardValue);
2083 }
2084
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002085 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002086 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002087 if (ANIMATE_SCREEN_LIGHTS) {
2088 if (mScreenBrightness.setTargetLocked(lcdValue,
2089 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2090 (int)mScreenBrightness.curValue)) {
2091 startAnimation = true;
2092 }
2093 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002094 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002095 ? LightsService.BRIGHTNESS_MODE_SENSOR
2096 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002097 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002098 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002099 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002100 if (mButtonBrightnessOverride < 0) {
2101 if (ANIMATE_BUTTON_LIGHTS) {
2102 if (mButtonBrightness.setTargetLocked(buttonValue,
2103 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2104 (int)mButtonBrightness.curValue)) {
2105 startAnimation = true;
2106 }
2107 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002108 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002109 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002110 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002111 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2112 if (ANIMATE_KEYBOARD_LIGHTS) {
2113 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2114 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2115 (int)mKeyboardBrightness.curValue)) {
2116 startAnimation = true;
2117 }
2118 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002119 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002120 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002121 }
2122 if (startAnimation) {
2123 if (mDebugLightSensor) {
2124 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2125 }
2126 mHandler.removeCallbacks(mLightAnimator);
2127 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002128 }
2129 }
2130 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002131 }
2132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 /**
2134 * The user requested that we go to sleep (probably with the power button).
2135 * This overrides all wake locks that are held.
2136 */
2137 public void goToSleep(long time)
2138 {
2139 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2140 synchronized (mLocks) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002141 goToSleepLocked(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002146 * Reboot the device immediately, passing 'reason' (may be null)
2147 * to the underlying __reboot system call. Should not return.
2148 */
2149 public void reboot(String reason)
2150 {
2151 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002152
San Mehat1e512792010-01-07 10:40:29 -08002153 /*
2154 * Manually shutdown the MountService to ensure media is
2155 * put into a safe state.
2156 */
2157 IMountService mSvc = IMountService.Stub.asInterface(
2158 ServiceManager.getService("mount"));
2159
2160 if (mSvc != null) {
2161 try {
2162 mSvc.shutdown();
2163 } catch (Exception e) {
2164 Log.e(TAG, "MountService shutdown failed", e);
2165 }
2166 } else {
2167 Log.w(TAG, "MountService unavailable for shutdown");
2168 }
San Mehat14e69af2010-01-06 14:58:18 -08002169
Doug Zongker50a21f42009-11-19 12:49:53 -08002170 try {
2171 Power.reboot(reason);
2172 } catch (IOException e) {
2173 Log.e(TAG, "reboot failed", e);
2174 }
2175 }
2176
Dan Egnor60d87622009-12-16 16:32:58 -08002177 /**
2178 * Crash the runtime (causing a complete restart of the Android framework).
2179 * Requires REBOOT permission. Mostly for testing. Should not return.
2180 */
2181 public void crash(final String message)
2182 {
2183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2184 Thread t = new Thread("PowerManagerService.crash()") {
2185 public void run() { throw new RuntimeException(message); }
2186 };
2187 try {
2188 t.start();
2189 t.join();
2190 } catch (InterruptedException e) {
2191 Log.wtf(TAG, e);
2192 }
2193 }
2194
Mike Lockwood435eb642009-12-03 08:40:18 -05002195 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196
2197 if (mLastEventTime <= time) {
2198 mLastEventTime = time;
2199 // cancel all of the wake locks
2200 mWakeLockState = SCREEN_OFF;
2201 int N = mLocks.size();
2202 int numCleared = 0;
2203 for (int i=0; i<N; i++) {
2204 WakeLock wl = mLocks.get(i);
2205 if (isScreenLock(wl.flags)) {
2206 mLocks.get(i).activated = false;
2207 numCleared++;
2208 }
2209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002210 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002211 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002213 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 cancelTimerLocked();
2215 }
2216 }
2217
2218 public long timeSinceScreenOn() {
2219 synchronized (mLocks) {
2220 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2221 return 0;
2222 }
2223 return SystemClock.elapsedRealtime() - mScreenOffTime;
2224 }
2225 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002228 synchronized (mLocks) {
2229 if (mSpew) {
2230 Log.d(TAG, "setKeyboardVisibility: " + visible);
2231 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002232 if (mKeyboardVisible != visible) {
2233 mKeyboardVisible = visible;
2234 // don't signal user activity if the screen is off; other code
2235 // will take care of turning on due to a true change to the lid
2236 // switch and synchronized with the lock screen.
2237 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002238 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002239 // force recompute of backlight values
2240 if (mLightSensorValue >= 0) {
2241 int value = (int)mLightSensorValue;
2242 mLightSensorValue = -1;
2243 lightSensorChangedLocked(value);
2244 }
2245 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002246 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2247 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002248 }
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251
2252 /**
2253 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002254 * When disabling user activity we also reset user power state so the keyguard can reset its
2255 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 */
2257 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002258 if (mSpew) {
2259 Log.d(TAG, "enableUserActivity " + enabled);
2260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 synchronized (mLocks) {
2262 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002263 if (!enabled) {
2264 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2265 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 }
2268 }
2269
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002270 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002271 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002272 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002273 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002274 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002275 // force recompute of backlight values
2276 if (mLightSensorValue >= 0) {
2277 int value = (int)mLightSensorValue;
2278 mLightSensorValue = -1;
2279 lightSensorChangedLocked(value);
2280 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002281 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002282 }
2283 }
2284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 /** Sets the screen off timeouts:
2286 * mKeylightDelay
2287 * mDimDelay
2288 * mScreenOffDelay
2289 * */
2290 private void setScreenOffTimeoutsLocked() {
2291 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002292 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 mDimDelay = -1;
2294 mScreenOffDelay = 0;
2295 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2296 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2297 mDimDelay = -1;
2298 mScreenOffDelay = 0;
2299 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002300 int totalDelay = mScreenOffTimeoutSetting;
2301 if (totalDelay > mMaximumScreenOffTimeout) {
2302 totalDelay = mMaximumScreenOffTimeout;
2303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2305 if (totalDelay < 0) {
2306 mScreenOffDelay = Integer.MAX_VALUE;
2307 } else if (mKeylightDelay < totalDelay) {
2308 // subtract the time that the keylight delay. This will give us the
2309 // remainder of the time that we need to sleep to get the accurate
2310 // screen off timeout.
2311 mScreenOffDelay = totalDelay - mKeylightDelay;
2312 } else {
2313 mScreenOffDelay = 0;
2314 }
2315 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2316 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2317 mScreenOffDelay = LONG_DIM_TIME;
2318 } else {
2319 mDimDelay = -1;
2320 }
2321 }
2322 if (mSpew) {
2323 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2324 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2325 + " mDimScreen=" + mDimScreen);
2326 }
2327 }
2328
2329 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002330 * Refreshes cached secure settings. Called once on startup, and
2331 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 */
Doug Zongker43866e02010-01-07 12:09:54 -08002333 private void updateSettingsValues() {
2334 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002336 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 SHORT_KEYLIGHT_DELAY_DEFAULT);
Doug Zongker43866e02010-01-07 12:09:54 -08002338 // Log.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340
2341 private class LockList extends ArrayList<WakeLock>
2342 {
2343 void addLock(WakeLock wl)
2344 {
2345 int index = getIndex(wl.binder);
2346 if (index < 0) {
2347 this.add(wl);
2348 }
2349 }
2350
2351 WakeLock removeLock(IBinder binder)
2352 {
2353 int index = getIndex(binder);
2354 if (index >= 0) {
2355 return this.remove(index);
2356 } else {
2357 return null;
2358 }
2359 }
2360
2361 int getIndex(IBinder binder)
2362 {
2363 int N = this.size();
2364 for (int i=0; i<N; i++) {
2365 if (this.get(i).binder == binder) {
2366 return i;
2367 }
2368 }
2369 return -1;
2370 }
2371
2372 int gatherState()
2373 {
2374 int result = 0;
2375 int N = this.size();
2376 for (int i=0; i<N; i++) {
2377 WakeLock wl = this.get(i);
2378 if (wl.activated) {
2379 if (isScreenLock(wl.flags)) {
2380 result |= wl.minState;
2381 }
2382 }
2383 }
2384 return result;
2385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002386
Michael Chane96440f2009-05-06 10:27:36 -07002387 int reactivateScreenLocksLocked()
2388 {
2389 int result = 0;
2390 int N = this.size();
2391 for (int i=0; i<N; i++) {
2392 WakeLock wl = this.get(i);
2393 if (isScreenLock(wl.flags)) {
2394 wl.activated = true;
2395 result |= wl.minState;
2396 }
2397 }
2398 return result;
2399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
2401
2402 void setPolicy(WindowManagerPolicy p) {
2403 synchronized (mLocks) {
2404 mPolicy = p;
2405 mLocks.notifyAll();
2406 }
2407 }
2408
2409 WindowManagerPolicy getPolicyLocked() {
2410 while (mPolicy == null || !mDoneBooting) {
2411 try {
2412 mLocks.wait();
2413 } catch (InterruptedException e) {
2414 // Ignore
2415 }
2416 }
2417 return mPolicy;
2418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002421 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2422 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2423 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002424 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002425 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002426 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002427 }
2428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 synchronized (mLocks) {
2430 Log.d(TAG, "system ready!");
2431 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002432 long identity = Binder.clearCallingIdentity();
2433 try {
2434 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2435 mBatteryStats.noteScreenOn();
2436 } catch (RemoteException e) {
2437 // Nothing interesting to do.
2438 } finally {
2439 Binder.restoreCallingIdentity(identity);
2440 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002441 }
2442 }
2443
2444 void bootCompleted() {
2445 Log.d(TAG, "bootCompleted");
2446 synchronized (mLocks) {
2447 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2449 updateWakeLockLocked();
2450 mLocks.notifyAll();
2451 }
2452 }
2453
2454 public void monitor() {
2455 synchronized (mLocks) { }
2456 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002457
2458 public int getSupportedWakeLockFlags() {
2459 int result = PowerManager.PARTIAL_WAKE_LOCK
2460 | PowerManager.FULL_WAKE_LOCK
2461 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2462
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002463 if (mProximitySensor != null) {
2464 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2465 }
2466
2467 return result;
2468 }
2469
Mike Lockwood237a2992009-09-15 14:42:16 -04002470 public void setBacklightBrightness(int brightness) {
2471 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2472 // Don't let applications turn the screen all the way off
2473 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002474 mLcdLight.setBrightness(brightness);
2475 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2476 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002477 long identity = Binder.clearCallingIdentity();
2478 try {
2479 mBatteryStats.noteScreenBrightness(brightness);
2480 } catch (RemoteException e) {
2481 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2482 } finally {
2483 Binder.restoreCallingIdentity(identity);
2484 }
2485
2486 // update our animation state
2487 if (ANIMATE_SCREEN_LIGHTS) {
2488 mScreenBrightness.curValue = brightness;
2489 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002490 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002491 }
2492 if (ANIMATE_KEYBOARD_LIGHTS) {
2493 mKeyboardBrightness.curValue = brightness;
2494 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002495 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002496 }
2497 if (ANIMATE_BUTTON_LIGHTS) {
2498 mButtonBrightness.curValue = brightness;
2499 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002500 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002501 }
2502 }
2503
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002504 public void setAttentionLight(boolean on, int color) {
2505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002506 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002507 }
2508
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002509 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002510 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002511 Log.d(TAG, "enableProximityLockLocked");
2512 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002513 if (!mProximitySensorEnabled) {
2514 // clear calling identity so sensor manager battery stats are accurate
2515 long identity = Binder.clearCallingIdentity();
2516 try {
2517 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2518 SensorManager.SENSOR_DELAY_NORMAL);
2519 mProximitySensorEnabled = true;
2520 } finally {
2521 Binder.restoreCallingIdentity(identity);
2522 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002523 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002524 }
2525
2526 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002527 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002528 Log.d(TAG, "disableProximityLockLocked");
2529 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002530 if (mProximitySensorEnabled) {
2531 // clear calling identity so sensor manager battery stats are accurate
2532 long identity = Binder.clearCallingIdentity();
2533 try {
2534 mSensorManager.unregisterListener(mProximityListener);
2535 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002536 if (mProximityPartialLock.isHeld()) {
2537 mProximityPartialLock.release();
2538 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002539 mProximitySensorEnabled = false;
2540 } finally {
2541 Binder.restoreCallingIdentity(identity);
2542 }
2543 if (mProximitySensorActive) {
2544 mProximitySensorActive = false;
2545 forceUserActivityLocked();
2546 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002547 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002548 }
2549
Mike Lockwood20f87d72009-11-05 16:08:51 -05002550 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002551 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002552 Log.d(TAG, "proximityChangedLocked, active: " + active);
2553 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002554 if (!mProximitySensorEnabled) {
2555 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002556 return;
2557 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002558 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002559 goToSleepLocked(SystemClock.uptimeMillis(),
2560 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002561 mProximitySensorActive = true;
2562 } else {
2563 // proximity sensor negative events trigger as user activity.
2564 // temporarily set mUserActivityAllowed to true so this will work
2565 // even when the keyguard is on.
2566 mProximitySensorActive = false;
2567 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002568
2569 if (mProximityWakeLockCount == 0) {
2570 // disable sensor if we have no listeners left after proximity negative
2571 disableProximityLockLocked();
2572 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002573 }
2574 }
2575
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002576 private void enableLightSensor(boolean enable) {
2577 if (mDebugLightSensor) {
2578 Log.d(TAG, "enableLightSensor " + enable);
2579 }
2580 if (mSensorManager != null && mLightSensorEnabled != enable) {
2581 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002582 // clear calling identity so sensor manager battery stats are accurate
2583 long identity = Binder.clearCallingIdentity();
2584 try {
2585 if (enable) {
2586 mSensorManager.registerListener(mLightListener, mLightSensor,
2587 SensorManager.SENSOR_DELAY_NORMAL);
2588 } else {
2589 mSensorManager.unregisterListener(mLightListener);
2590 mHandler.removeCallbacks(mAutoBrightnessTask);
2591 }
2592 } finally {
2593 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002594 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002595 }
2596 }
2597
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002598 SensorEventListener mProximityListener = new SensorEventListener() {
2599 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002600 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002601 synchronized (mLocks) {
2602 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002603 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2604 mLastProximityEventTime = milliseconds;
2605 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002606 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002607
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002608 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002609 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2610 distance < mProximitySensor.getMaximumRange());
2611
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002612 if (mDebugProximitySensor) {
2613 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2614 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002615 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2616 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2617 mProximityPendingValue = (active ? 1 : 0);
2618 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002619 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002620 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002621 // process the value immediately
2622 mProximityPendingValue = -1;
2623 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002624 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002625
2626 // update mProximityPartialLock state
2627 boolean held = mProximityPartialLock.isHeld();
2628 if (!held && proximityTaskQueued) {
2629 // hold wakelock until mProximityTask runs
2630 mProximityPartialLock.acquire();
2631 } else if (held && !proximityTaskQueued) {
2632 mProximityPartialLock.release();
2633 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002634 }
2635 }
2636
2637 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2638 // ignore
2639 }
2640 };
2641
2642 SensorEventListener mLightListener = new SensorEventListener() {
2643 public void onSensorChanged(SensorEvent event) {
2644 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002645 // ignore light sensor while screen is turning off
2646 if (isScreenTurningOffLocked()) {
2647 return;
2648 }
2649
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002650 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002651 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002652 if (mDebugLightSensor) {
2653 Log.d(TAG, "onSensorChanged: light value: " + value);
2654 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002655 mHandler.removeCallbacks(mAutoBrightnessTask);
2656 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002657 if (mLightSensorValue == -1 ||
2658 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2659 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002660 lightSensorChangedLocked(value);
2661 } else {
2662 // delay processing to debounce the sensor
2663 mLightSensorPendingValue = value;
2664 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2665 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002666 } else {
2667 mLightSensorPendingValue = -1;
2668 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002669 }
2670 }
2671
2672 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2673 // ignore
2674 }
2675 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676}