blob: 611a86e3576ae48b5498c5adcc1c9db3ba91d67b [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070033import android.hardware.Sensor;
34import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
36import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.BatteryStats;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.HandlerThread;
41import android.os.IBinder;
42import android.os.IPowerManager;
43import android.os.LocalPowerManager;
44import android.os.Power;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.provider.Settings.SettingNotFoundException;
50import android.provider.Settings;
51import android.util.EventLog;
52import android.util.Log;
53import android.view.WindowManagerPolicy;
54import static android.provider.Settings.System.DIM_SCREEN;
55import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050056import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070057import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
59import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
64import java.util.HashMap;
65import java.util.Observable;
66import java.util.Observer;
67
Mike Lockwoodbc706a02009-07-27 13:50:57 -070068class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040069 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
71 private static final String TAG = "PowerManagerService";
72 static final String PARTIAL_NAME = "PowerManagerService";
73
74 private static final boolean LOG_PARTIAL_WL = false;
75
76 // Indicates whether touch-down cycles should be logged as part of the
77 // LOG_POWER_SCREEN_STATE log events
78 private static final boolean LOG_TOUCH_DOWNS = true;
79
80 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
81 | PowerManager.SCREEN_DIM_WAKE_LOCK
82 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070083 | PowerManager.FULL_WAKE_LOCK
84 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 // time since last state: time since last event:
87 // The short keylight delay comes from Gservices; this is the default.
88 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
89 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
90 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
91 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
92
Mike Lockwoodd7786b42009-10-15 17:09:16 -070093 // How long to wait to debounce light sensor changes.
94 private static final int LIGHT_SENSOR_DELAY = 1000;
95
Mike Lockwood20f87d72009-11-05 16:08:51 -050096 // For debouncing the proximity sensor.
97 private static final int PROXIMITY_SENSOR_DELAY = 1000;
98
Mike Lockwoodd20ea362009-09-15 00:13:38 -040099 // trigger proximity if distance is less than 5 cm
100 private static final float PROXIMITY_THRESHOLD = 5.0f;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 // Cached Gservices settings; see updateGservicesValues()
103 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
104
105 // flags for setPowerState
106 private static final int SCREEN_ON_BIT = 0x00000001;
107 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
108 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
109 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
110 private static final int BATTERY_LOW_BIT = 0x00000010;
111
112 // values for setPowerState
113
114 // SCREEN_OFF == everything off
115 private static final int SCREEN_OFF = 0x00000000;
116
117 // SCREEN_DIM == screen on, screen backlight dim
118 private static final int SCREEN_DIM = SCREEN_ON_BIT;
119
120 // SCREEN_BRIGHT == screen on, screen backlight bright
121 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
122
123 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
124 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
125
126 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
127 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
128
129 // used for noChangeLights in setPowerState()
130 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
131
132 static final boolean ANIMATE_SCREEN_LIGHTS = true;
133 static final boolean ANIMATE_BUTTON_LIGHTS = false;
134 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
135
136 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400137 // Slower animation for autobrightness changes
138 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
140 // These magic numbers are the initial state of the LEDs at boot. Ideally
141 // we should read them from the driver, but our current hardware returns 0
142 // for the initial value. Oops!
143 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
144 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
145 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
146
147 static final int LOG_POWER_SLEEP_REQUESTED = 2724;
148 static final int LOG_POWER_SCREEN_BROADCAST_SEND = 2725;
149 static final int LOG_POWER_SCREEN_BROADCAST_DONE = 2726;
150 static final int LOG_POWER_SCREEN_BROADCAST_STOP = 2727;
151 static final int LOG_POWER_SCREEN_STATE = 2728;
152 static final int LOG_POWER_PARTIAL_WAKE_STATE = 2729;
153
154 private final int MY_UID;
155
156 private boolean mDoneBooting = false;
157 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700158 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
159 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mPartialCount = 0;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700161 private int mProximityCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mPowerState;
163 private boolean mOffBecauseOfUser;
164 private int mUserState;
165 private boolean mKeyboardVisible = false;
166 private boolean mUserActivityAllowed = true;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700167 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500168 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
169 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 private int mTotalDelaySetting;
171 private int mKeylightDelay;
172 private int mDimDelay;
173 private int mScreenOffDelay;
174 private int mWakeLockState;
175 private long mLastEventTime = 0;
176 private long mScreenOffTime;
177 private volatile WindowManagerPolicy mPolicy;
178 private final LockList mLocks = new LockList();
179 private Intent mScreenOffIntent;
180 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private Context mContext;
183 private UnsynchronizedWakeLock mBroadcastWakeLock;
184 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
185 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
186 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
187 private HandlerThread mHandlerThread;
188 private Handler mHandler;
189 private TimeoutTask mTimeoutTask = new TimeoutTask();
190 private LightAnimator mLightAnimator = new LightAnimator();
191 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700192 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700194 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700196 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700197 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private boolean mIsPowered = false;
199 private IActivityManager mActivityService;
200 private IBatteryStats mBatteryStats;
201 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700202 private SensorManager mSensorManager;
203 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400204 private Sensor mLightSensor;
205 private boolean mLightSensorEnabled;
206 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700207 private float mLightSensorPendingValue = -1;
208 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private boolean mDimScreen = true;
210 private long mNextTimeout;
211 private volatile int mPokey = 0;
212 private volatile boolean mPokeAwakeOnSet = false;
213 private volatile boolean mInitComplete = false;
214 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
215 private long mScreenOnTime;
216 private long mScreenOnStartTime;
217 private boolean mPreventScreenOn;
218 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400219 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700220 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700221 private int[] mAutoBrightnessLevels;
222 private int[] mLcdBacklightValues;
223 private int[] mButtonBacklightValues;
224 private int[] mKeyboardBacklightValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225
226 // Used when logging number and duration of touch-down cycles
227 private long mTotalTouchDownTime;
228 private long mLastTouchDown;
229 private int mTouchCycles;
230
231 // could be either static or controllable at runtime
232 private static final boolean mSpew = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400233 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
235 /*
236 static PrintStream mLog;
237 static {
238 try {
239 mLog = new PrintStream("/data/power.log");
240 }
241 catch (FileNotFoundException e) {
242 android.util.Log.e(TAG, "Life is hard", e);
243 }
244 }
245 static class Log {
246 static void d(String tag, String s) {
247 mLog.println(s);
248 android.util.Log.d(tag, s);
249 }
250 static void i(String tag, String s) {
251 mLog.println(s);
252 android.util.Log.i(tag, s);
253 }
254 static void w(String tag, String s) {
255 mLog.println(s);
256 android.util.Log.w(tag, s);
257 }
258 static void e(String tag, String s) {
259 mLog.println(s);
260 android.util.Log.e(tag, s);
261 }
262 }
263 */
264
265 /**
266 * This class works around a deadlock between the lock in PowerManager.WakeLock
267 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
268 * mToken object so it can be accessed from any thread, but it calls into here
269 * with its lock held. This class is essentially a reimplementation of
270 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
271 * only call it with our own locks held.
272 */
273 private class UnsynchronizedWakeLock {
274 int mFlags;
275 String mTag;
276 IBinder mToken;
277 int mCount = 0;
278 boolean mRefCounted;
279
280 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
281 mFlags = flags;
282 mTag = tag;
283 mToken = new Binder();
284 mRefCounted = refCounted;
285 }
286
287 public void acquire() {
288 if (!mRefCounted || mCount++ == 0) {
289 long ident = Binder.clearCallingIdentity();
290 try {
291 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
292 MY_UID, mTag);
293 } finally {
294 Binder.restoreCallingIdentity(ident);
295 }
296 }
297 }
298
299 public void release() {
300 if (!mRefCounted || --mCount == 0) {
301 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
302 }
303 if (mCount < 0) {
304 throw new RuntimeException("WakeLock under-locked " + mTag);
305 }
306 }
307
308 public String toString() {
309 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
310 + " mCount=" + mCount + ")";
311 }
312 }
313
314 private final class BatteryReceiver extends BroadcastReceiver {
315 @Override
316 public void onReceive(Context context, Intent intent) {
317 synchronized (mLocks) {
318 boolean wasPowered = mIsPowered;
319 mIsPowered = mBatteryService.isPowered();
320
321 if (mIsPowered != wasPowered) {
322 // update mStayOnWhilePluggedIn wake lock
323 updateWakeLockLocked();
324
325 // treat plugging and unplugging the devices as a user activity.
326 // users find it disconcerting when they unplug the device
327 // and it shuts off right away.
328 // temporarily set mUserActivityAllowed to true so this will work
329 // even when the keyguard is on.
330 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400331 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333 }
334 }
335 }
336 }
337
338 /**
339 * Set the setting that determines whether the device stays on when plugged in.
340 * The argument is a bit string, with each bit specifying a power source that,
341 * when the device is connected to that source, causes the device to stay on.
342 * See {@link android.os.BatteryManager} for the list of power sources that
343 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
344 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
345 * @param val an {@code int} containing the bits that specify which power sources
346 * should cause the device to stay on.
347 */
348 public void setStayOnSetting(int val) {
349 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
350 Settings.System.putInt(mContext.getContentResolver(),
351 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
352 }
353
354 private class SettingsObserver implements Observer {
355 private int getInt(String name) {
356 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
357 }
358
359 public void update(Observable o, Object arg) {
360 synchronized (mLocks) {
361 // STAY_ON_WHILE_PLUGGED_IN
362 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
363 updateWakeLockLocked();
364
365 // SCREEN_OFF_TIMEOUT
366 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
367
368 // DIM_SCREEN
369 //mDimScreen = getInt(DIM_SCREEN) != 0;
370
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700371 // SCREEN_BRIGHTNESS_MODE
372 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 // recalculate everything
375 setScreenOffTimeoutsLocked();
376 }
377 }
378 }
379
380 PowerManagerService()
381 {
382 // Hack to get our uid... should have a func for this.
383 long token = Binder.clearCallingIdentity();
384 MY_UID = Binder.getCallingUid();
385 Binder.restoreCallingIdentity(token);
386
387 // XXX remove this when the kernel doesn't timeout wake locks
388 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
389
390 // assume nothing is on yet
391 mUserState = mPowerState = 0;
392
393 // Add ourself to the Watchdog monitors.
394 Watchdog.getInstance().addMonitor(this);
395 mScreenOnStartTime = SystemClock.elapsedRealtime();
396 }
397
398 private ContentQueryMap mSettings;
399
The Android Open Source Project10592532009-03-18 17:39:46 -0700400 void init(Context context, HardwareService hardware, IActivityManager activity,
401 BatteryService battery) {
402 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 mContext = context;
404 mActivityService = activity;
405 mBatteryStats = BatteryStatsService.getService();
406 mBatteryService = battery;
407
408 mHandlerThread = new HandlerThread("PowerManagerService") {
409 @Override
410 protected void onLooperPrepared() {
411 super.onLooperPrepared();
412 initInThread();
413 }
414 };
415 mHandlerThread.start();
416
417 synchronized (mHandlerThread) {
418 while (!mInitComplete) {
419 try {
420 mHandlerThread.wait();
421 } catch (InterruptedException e) {
422 // Ignore
423 }
424 }
425 }
426 }
427
428 void initInThread() {
429 mHandler = new Handler();
430
431 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700432 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
434 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
435 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
436 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
437 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
438 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
439
440 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
441 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
442 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
443 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
444
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700445 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400446
447 // read settings for auto-brightness
448 mUseSoftwareAutoBrightness = resources.getBoolean(
449 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400450 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700451 mAutoBrightnessLevels = resources.getIntArray(
452 com.android.internal.R.array.config_autoBrightnessLevels);
453 mLcdBacklightValues = resources.getIntArray(
454 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
455 mButtonBacklightValues = resources.getIntArray(
456 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
457 mKeyboardBacklightValues = resources.getIntArray(
458 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
459 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700460
461 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
463 "(" + Settings.System.NAME + "=?) or ("
464 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700465 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700467 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
468 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 null);
470 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
471 SettingsObserver settingsObserver = new SettingsObserver();
472 mSettings.addObserver(settingsObserver);
473
474 // pretend that the settings changed so we will get their initial state
475 settingsObserver.update(mSettings, null);
476
477 // register for the battery changed notifications
478 IntentFilter filter = new IntentFilter();
479 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
480 mContext.registerReceiver(new BatteryReceiver(), filter);
481
482 // Listen for Gservices changes
483 IntentFilter gservicesChangedFilter =
484 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
485 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
486 // And explicitly do the initial update of our cached settings
487 updateGservicesValues();
488
Mike Lockwood4984e732009-11-01 08:16:33 -0500489 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400490 // turn the screen on
491 setPowerState(SCREEN_BRIGHT);
492 } else {
493 // turn everything on
494 setPowerState(ALL_BRIGHT);
495 }
Dan Murphy951764b2009-08-27 14:59:03 -0500496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 synchronized (mHandlerThread) {
498 mInitComplete = true;
499 mHandlerThread.notifyAll();
500 }
501 }
502
503 private class WakeLock implements IBinder.DeathRecipient
504 {
505 WakeLock(int f, IBinder b, String t, int u) {
506 super();
507 flags = f;
508 binder = b;
509 tag = t;
510 uid = u == MY_UID ? Process.SYSTEM_UID : u;
511 if (u != MY_UID || (
512 !"KEEP_SCREEN_ON_FLAG".equals(tag)
513 && !"KeyInputQueue".equals(tag))) {
514 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
515 ? BatteryStats.WAKE_TYPE_PARTIAL
516 : BatteryStats.WAKE_TYPE_FULL;
517 } else {
518 monitorType = -1;
519 }
520 try {
521 b.linkToDeath(this, 0);
522 } catch (RemoteException e) {
523 binderDied();
524 }
525 }
526 public void binderDied() {
527 synchronized (mLocks) {
528 releaseWakeLockLocked(this.binder, true);
529 }
530 }
531 final int flags;
532 final IBinder binder;
533 final String tag;
534 final int uid;
535 final int monitorType;
536 boolean activated = true;
537 int minState;
538 }
539
540 private void updateWakeLockLocked() {
541 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
542 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
543 mStayOnWhilePluggedInScreenDimLock.acquire();
544 mStayOnWhilePluggedInPartialLock.acquire();
545 } else {
546 mStayOnWhilePluggedInScreenDimLock.release();
547 mStayOnWhilePluggedInPartialLock.release();
548 }
549 }
550
551 private boolean isScreenLock(int flags)
552 {
553 int n = flags & LOCK_MASK;
554 return n == PowerManager.FULL_WAKE_LOCK
555 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
556 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
557 }
558
559 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700561 if (uid != Process.myUid()) {
562 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 long ident = Binder.clearCallingIdentity();
565 try {
566 synchronized (mLocks) {
567 acquireWakeLockLocked(flags, lock, uid, tag);
568 }
569 } finally {
570 Binder.restoreCallingIdentity(ident);
571 }
572 }
573
574 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
575 int acquireUid = -1;
576 String acquireName = null;
577 int acquireType = -1;
578
579 if (mSpew) {
580 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
581 }
582
583 int index = mLocks.getIndex(lock);
584 WakeLock wl;
585 boolean newlock;
586 if (index < 0) {
587 wl = new WakeLock(flags, lock, tag, uid);
588 switch (wl.flags & LOCK_MASK)
589 {
590 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500591 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400592 wl.minState = SCREEN_BRIGHT;
593 } else {
594 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 break;
597 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
598 wl.minState = SCREEN_BRIGHT;
599 break;
600 case PowerManager.SCREEN_DIM_WAKE_LOCK:
601 wl.minState = SCREEN_DIM;
602 break;
603 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700604 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 break;
606 default:
607 // just log and bail. we're in the server, so don't
608 // throw an exception.
609 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
610 + " flags=" + flags);
611 return;
612 }
613 mLocks.addLock(wl);
614 newlock = true;
615 } else {
616 wl = mLocks.get(index);
617 newlock = false;
618 }
619 if (isScreenLock(flags)) {
620 // if this causes a wakeup, we reactivate all of the locks and
621 // set it to whatever they want. otherwise, we modulate that
622 // by the current state so we never turn it more on than
623 // it already is.
624 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700625 int oldWakeLockState = mWakeLockState;
626 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 if (mSpew) {
628 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700629 + " mWakeLockState=0x"
630 + Integer.toHexString(mWakeLockState)
631 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 } else {
634 if (mSpew) {
635 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
636 + " mLocks.gatherState()=0x"
637 + Integer.toHexString(mLocks.gatherState())
638 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
639 }
640 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
641 }
642 setPowerState(mWakeLockState | mUserState);
643 }
644 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
645 if (newlock) {
646 mPartialCount++;
647 if (mPartialCount == 1) {
648 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
649 }
650 }
651 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700652 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
653 mProximityCount++;
654 if (mProximityCount == 1) {
655 enableProximityLockLocked();
656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
658 if (newlock) {
659 acquireUid = wl.uid;
660 acquireName = wl.tag;
661 acquireType = wl.monitorType;
662 }
663
664 if (acquireType >= 0) {
665 try {
666 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
667 } catch (RemoteException e) {
668 // Ignore
669 }
670 }
671 }
672
673 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700674 int uid = Binder.getCallingUid();
675 if (uid != Process.myUid()) {
676 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678
679 synchronized (mLocks) {
680 releaseWakeLockLocked(lock, false);
681 }
682 }
683
684 private void releaseWakeLockLocked(IBinder lock, boolean death) {
685 int releaseUid;
686 String releaseName;
687 int releaseType;
688
689 WakeLock wl = mLocks.removeLock(lock);
690 if (wl == null) {
691 return;
692 }
693
694 if (mSpew) {
695 Log.d(TAG, "releaseWakeLock flags=0x"
696 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
697 }
698
699 if (isScreenLock(wl.flags)) {
700 mWakeLockState = mLocks.gatherState();
701 // goes in the middle to reduce flicker
702 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
703 userActivity(SystemClock.uptimeMillis(), false);
704 }
705 setPowerState(mWakeLockState | mUserState);
706 }
707 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
708 mPartialCount--;
709 if (mPartialCount == 0) {
710 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
711 Power.releaseWakeLock(PARTIAL_NAME);
712 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700713 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
714 mProximityCount--;
715 if (mProximityCount == 0) {
716 disableProximityLockLocked();
717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719 // Unlink the lock from the binder.
720 wl.binder.unlinkToDeath(wl, 0);
721 releaseUid = wl.uid;
722 releaseName = wl.tag;
723 releaseType = wl.monitorType;
724
725 if (releaseType >= 0) {
726 long origId = Binder.clearCallingIdentity();
727 try {
728 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
729 } catch (RemoteException e) {
730 // Ignore
731 } finally {
732 Binder.restoreCallingIdentity(origId);
733 }
734 }
735 }
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 private class PokeLock implements IBinder.DeathRecipient
738 {
739 PokeLock(int p, IBinder b, String t) {
740 super();
741 this.pokey = p;
742 this.binder = b;
743 this.tag = t;
744 try {
745 b.linkToDeath(this, 0);
746 } catch (RemoteException e) {
747 binderDied();
748 }
749 }
750 public void binderDied() {
751 setPokeLock(0, this.binder, this.tag);
752 }
753 int pokey;
754 IBinder binder;
755 String tag;
756 boolean awakeOnSet;
757 }
758
759 public void setPokeLock(int pokey, IBinder token, String tag) {
760 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
761 if (token == null) {
762 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
763 return;
764 }
765
766 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
767 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
768 + " and POKE_LOCK_MEDIUM_TIMEOUT");
769 }
770
771 synchronized (mLocks) {
772 if (pokey != 0) {
773 PokeLock p = mPokeLocks.get(token);
774 int oldPokey = 0;
775 if (p != null) {
776 oldPokey = p.pokey;
777 p.pokey = pokey;
778 } else {
779 p = new PokeLock(pokey, token, tag);
780 mPokeLocks.put(token, p);
781 }
782 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
783 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
784 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
785 p.awakeOnSet = true;
786 }
787 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700788 PokeLock rLock = mPokeLocks.remove(token);
789 if (rLock != null) {
790 token.unlinkToDeath(rLock, 0);
791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 }
793
794 int oldPokey = mPokey;
795 int cumulative = 0;
796 boolean oldAwakeOnSet = mPokeAwakeOnSet;
797 boolean awakeOnSet = false;
798 for (PokeLock p: mPokeLocks.values()) {
799 cumulative |= p.pokey;
800 if (p.awakeOnSet) {
801 awakeOnSet = true;
802 }
803 }
804 mPokey = cumulative;
805 mPokeAwakeOnSet = awakeOnSet;
806
807 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
808 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
809
810 if (oldCumulativeTimeout != newCumulativeTimeout) {
811 setScreenOffTimeoutsLocked();
812 // reset the countdown timer, but use the existing nextState so it doesn't
813 // change anything
814 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
815 }
816 }
817 }
818
819 private static String lockType(int type)
820 {
821 switch (type)
822 {
823 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700824 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700826 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700828 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700830 return "PARTIAL_WAKE_LOCK ";
831 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
832 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 default:
David Brown251faa62009-08-02 22:04:36 -0700834 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836 }
837
838 private static String dumpPowerState(int state) {
839 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
840 ? "KEYBOARD_BRIGHT_BIT " : "")
841 + (((state & SCREEN_BRIGHT_BIT) != 0)
842 ? "SCREEN_BRIGHT_BIT " : "")
843 + (((state & SCREEN_ON_BIT) != 0)
844 ? "SCREEN_ON_BIT " : "")
845 + (((state & BATTERY_LOW_BIT) != 0)
846 ? "BATTERY_LOW_BIT " : "");
847 }
848
849 @Override
850 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
851 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
852 != PackageManager.PERMISSION_GRANTED) {
853 pw.println("Permission Denial: can't dump PowerManager from from pid="
854 + Binder.getCallingPid()
855 + ", uid=" + Binder.getCallingUid());
856 return;
857 }
858
859 long now = SystemClock.uptimeMillis();
860
861 pw.println("Power Manager State:");
862 pw.println(" mIsPowered=" + mIsPowered
863 + " mPowerState=" + mPowerState
864 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
865 + " ms");
866 pw.println(" mPartialCount=" + mPartialCount);
867 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
868 pw.println(" mUserState=" + dumpPowerState(mUserState));
869 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
870 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
871 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
872 + " " + ((mNextTimeout-now)/1000) + "s from now");
873 pw.println(" mDimScreen=" + mDimScreen
874 + " mStayOnConditions=" + mStayOnConditions);
875 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
876 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700877 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
878 + ',' + mBroadcastQueue[2] + "}");
879 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
880 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
882 pw.println(" mKeyboardVisible=" + mKeyboardVisible
883 + " mUserActivityAllowed=" + mUserActivityAllowed);
884 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
885 + " mScreenOffDelay=" + mScreenOffDelay);
886 pw.println(" mPreventScreenOn=" + mPreventScreenOn
887 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
888 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
889 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
890 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
891 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
892 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700893 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500894 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
895 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700896 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
897 pw.println(" mLightSensorValue=" + mLightSensorValue);
898 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400899 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700900 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 mScreenBrightness.dump(pw, " mScreenBrightness: ");
902 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
903 mButtonBrightness.dump(pw, " mButtonBrightness: ");
904
905 int N = mLocks.size();
906 pw.println();
907 pw.println("mLocks.size=" + N + ":");
908 for (int i=0; i<N; i++) {
909 WakeLock wl = mLocks.get(i);
910 String type = lockType(wl.flags & LOCK_MASK);
911 String acquireCausesWakeup = "";
912 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
913 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
914 }
915 String activated = "";
916 if (wl.activated) {
917 activated = " activated";
918 }
919 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
920 + activated + " (minState=" + wl.minState + ")");
921 }
922
923 pw.println();
924 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
925 for (PokeLock p: mPokeLocks.values()) {
926 pw.println(" poke lock '" + p.tag + "':"
927 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
928 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700929 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
930 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
932 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
933 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
934 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
935 }
936
937 pw.println();
938 }
939
940 private void setTimeoutLocked(long now, int nextState)
941 {
942 if (mDoneBooting) {
943 mHandler.removeCallbacks(mTimeoutTask);
944 mTimeoutTask.nextState = nextState;
945 long when = now;
946 switch (nextState)
947 {
948 case SCREEN_BRIGHT:
949 when += mKeylightDelay;
950 break;
951 case SCREEN_DIM:
952 if (mDimDelay >= 0) {
953 when += mDimDelay;
954 break;
955 } else {
956 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
957 }
958 case SCREEN_OFF:
959 synchronized (mLocks) {
960 when += mScreenOffDelay;
961 }
962 break;
963 }
964 if (mSpew) {
965 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
966 + " when=" + when);
967 }
968 mHandler.postAtTime(mTimeoutTask, when);
969 mNextTimeout = when; // for debugging
970 }
971 }
972
973 private void cancelTimerLocked()
974 {
975 mHandler.removeCallbacks(mTimeoutTask);
976 mTimeoutTask.nextState = -1;
977 }
978
979 private class TimeoutTask implements Runnable
980 {
981 int nextState; // access should be synchronized on mLocks
982 public void run()
983 {
984 synchronized (mLocks) {
985 if (mSpew) {
986 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
987 }
988
989 if (nextState == -1) {
990 return;
991 }
992
993 mUserState = this.nextState;
994 setPowerState(this.nextState | mWakeLockState);
995
996 long now = SystemClock.uptimeMillis();
997
998 switch (this.nextState)
999 {
1000 case SCREEN_BRIGHT:
1001 if (mDimDelay >= 0) {
1002 setTimeoutLocked(now, SCREEN_DIM);
1003 break;
1004 }
1005 case SCREEN_DIM:
1006 setTimeoutLocked(now, SCREEN_OFF);
1007 break;
1008 }
1009 }
1010 }
1011 }
1012
1013 private void sendNotificationLocked(boolean on, int why)
1014 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001015 if (!on) {
1016 mStillNeedSleepNotification = false;
1017 }
1018
Joe Onorato128e7292009-03-24 18:41:31 -07001019 // Add to the queue.
1020 int index = 0;
1021 while (mBroadcastQueue[index] != -1) {
1022 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
Joe Onorato128e7292009-03-24 18:41:31 -07001024 mBroadcastQueue[index] = on ? 1 : 0;
1025 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026
Joe Onorato128e7292009-03-24 18:41:31 -07001027 // If we added it position 2, then there is a pair that can be stripped.
1028 // If we added it position 1 and we're turning the screen off, we can strip
1029 // the pair and do nothing, because the screen is already off, and therefore
1030 // keyguard has already been enabled.
1031 // However, if we added it at position 1 and we're turning it on, then position
1032 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1033 // on, so have to run the queue then.
1034 if (index == 2) {
1035 // Also, while we're collapsing them, if it's going to be an "off," and one
1036 // is off because of user, then use that, regardless of whether it's the first
1037 // or second one.
1038 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1039 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1040 }
1041 mBroadcastQueue[0] = on ? 1 : 0;
1042 mBroadcastQueue[1] = -1;
1043 mBroadcastQueue[2] = -1;
1044 index = 0;
1045 }
1046 if (index == 1 && !on) {
1047 mBroadcastQueue[0] = -1;
1048 mBroadcastQueue[1] = -1;
1049 index = -1;
1050 // The wake lock was being held, but we're not actually going to do any
1051 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1053 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001054 }
1055
1056 // Now send the message.
1057 if (index >= 0) {
1058 // Acquire the broadcast wake lock before changing the power
1059 // state. It will be release after the broadcast is sent.
1060 // We always increment the ref count for each notification in the queue
1061 // and always decrement when that notification is handled.
1062 mBroadcastWakeLock.acquire();
1063 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1064 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
1066 }
1067
1068 private Runnable mNotificationTask = new Runnable()
1069 {
1070 public void run()
1071 {
Joe Onorato128e7292009-03-24 18:41:31 -07001072 while (true) {
1073 int value;
1074 int why;
1075 WindowManagerPolicy policy;
1076 synchronized (mLocks) {
1077 value = mBroadcastQueue[0];
1078 why = mBroadcastWhy[0];
1079 for (int i=0; i<2; i++) {
1080 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1081 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1082 }
1083 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
Joe Onorato128e7292009-03-24 18:41:31 -07001085 if (value == 1) {
1086 mScreenOnStart = SystemClock.uptimeMillis();
1087
1088 policy.screenTurnedOn();
1089 try {
1090 ActivityManagerNative.getDefault().wakingUp();
1091 } catch (RemoteException e) {
1092 // ignore it
1093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094
Joe Onorato128e7292009-03-24 18:41:31 -07001095 if (mSpew) {
1096 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1097 }
1098 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1099 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1100 mScreenOnBroadcastDone, mHandler, 0, null, null);
1101 } else {
1102 synchronized (mLocks) {
1103 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1104 mBroadcastWakeLock.mCount);
1105 mBroadcastWakeLock.release();
1106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108 }
Joe Onorato128e7292009-03-24 18:41:31 -07001109 else if (value == 0) {
1110 mScreenOffStart = SystemClock.uptimeMillis();
1111
1112 policy.screenTurnedOff(why);
1113 try {
1114 ActivityManagerNative.getDefault().goingToSleep();
1115 } catch (RemoteException e) {
1116 // ignore it.
1117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118
Joe Onorato128e7292009-03-24 18:41:31 -07001119 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1120 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1121 mScreenOffBroadcastDone, mHandler, 0, null, null);
1122 } else {
1123 synchronized (mLocks) {
1124 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1125 mBroadcastWakeLock.mCount);
1126 mBroadcastWakeLock.release();
1127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
1129 }
Joe Onorato128e7292009-03-24 18:41:31 -07001130 else {
1131 // If we're in this case, then this handler is running for a previous
1132 // paired transaction. mBroadcastWakeLock will already have been released.
1133 break;
1134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136 }
1137 };
1138
1139 long mScreenOnStart;
1140 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1141 public void onReceive(Context context, Intent intent) {
1142 synchronized (mLocks) {
1143 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1144 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1145 mBroadcastWakeLock.release();
1146 }
1147 }
1148 };
1149
1150 long mScreenOffStart;
1151 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1152 public void onReceive(Context context, Intent intent) {
1153 synchronized (mLocks) {
1154 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1155 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1156 mBroadcastWakeLock.release();
1157 }
1158 }
1159 };
1160
1161 void logPointerUpEvent() {
1162 if (LOG_TOUCH_DOWNS) {
1163 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1164 mLastTouchDown = 0;
1165 }
1166 }
1167
1168 void logPointerDownEvent() {
1169 if (LOG_TOUCH_DOWNS) {
1170 // If we are not already timing a down/up sequence
1171 if (mLastTouchDown == 0) {
1172 mLastTouchDown = SystemClock.elapsedRealtime();
1173 mTouchCycles++;
1174 }
1175 }
1176 }
1177
1178 /**
1179 * Prevents the screen from turning on even if it *should* turn on due
1180 * to a subsequent full wake lock being acquired.
1181 * <p>
1182 * This is a temporary hack that allows an activity to "cover up" any
1183 * display glitches that happen during the activity's startup
1184 * sequence. (Specifically, this API was added to work around a
1185 * cosmetic bug in the "incoming call" sequence, where the lock screen
1186 * would flicker briefly before the incoming call UI became visible.)
1187 * TODO: There ought to be a more elegant way of doing this,
1188 * probably by having the PowerManager and ActivityManager
1189 * work together to let apps specify that the screen on/off
1190 * state should be synchronized with the Activity lifecycle.
1191 * <p>
1192 * Note that calling preventScreenOn(true) will NOT turn the screen
1193 * off if it's currently on. (This API only affects *future*
1194 * acquisitions of full wake locks.)
1195 * But calling preventScreenOn(false) WILL turn the screen on if
1196 * it's currently off because of a prior preventScreenOn(true) call.
1197 * <p>
1198 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1199 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1200 * call doesn't occur within 5 seconds, we'll turn the screen back on
1201 * ourselves (and log a warning about it); this prevents a buggy app
1202 * from disabling the screen forever.)
1203 * <p>
1204 * TODO: this feature should really be controlled by a new type of poke
1205 * lock (rather than an IPowerManager call).
1206 */
1207 public void preventScreenOn(boolean prevent) {
1208 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1209
1210 synchronized (mLocks) {
1211 if (prevent) {
1212 // First of all, grab a partial wake lock to
1213 // make sure the CPU stays on during the entire
1214 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1215 mPreventScreenOnPartialLock.acquire();
1216
1217 // Post a forceReenableScreen() call (for 5 seconds in the
1218 // future) to make sure the matching preventScreenOn(false) call
1219 // has happened by then.
1220 mHandler.removeCallbacks(mForceReenableScreenTask);
1221 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1222
1223 // Finally, set the flag that prevents the screen from turning on.
1224 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001225 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 mPreventScreenOn = true;
1227 } else {
1228 // (Re)enable the screen.
1229 mPreventScreenOn = false;
1230
1231 // We're "undoing" a the prior preventScreenOn(true) call, so we
1232 // no longer need the 5-second safeguard.
1233 mHandler.removeCallbacks(mForceReenableScreenTask);
1234
1235 // Forcibly turn on the screen if it's supposed to be on. (This
1236 // handles the case where the screen is currently off because of
1237 // a prior preventScreenOn(true) call.)
1238 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1239 if (mSpew) {
1240 Log.d(TAG,
1241 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1242 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001243 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001245 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247 }
1248
1249 // Release the partial wake lock that we held during the
1250 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1251 mPreventScreenOnPartialLock.release();
1252 }
1253 }
1254 }
1255
1256 public void setScreenBrightnessOverride(int brightness) {
1257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1258
1259 synchronized (mLocks) {
1260 if (mScreenBrightnessOverride != brightness) {
1261 mScreenBrightnessOverride = brightness;
1262 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1263 }
1264 }
1265 }
1266
1267 /**
1268 * Sanity-check that gets called 5 seconds after any call to
1269 * preventScreenOn(true). This ensures that the original call
1270 * is followed promptly by a call to preventScreenOn(false).
1271 */
1272 private void forceReenableScreen() {
1273 // We shouldn't get here at all if mPreventScreenOn is false, since
1274 // we should have already removed any existing
1275 // mForceReenableScreenTask messages...
1276 if (!mPreventScreenOn) {
1277 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1278 return;
1279 }
1280
1281 // Uh oh. It's been 5 seconds since a call to
1282 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1283 // This means the app that called preventScreenOn(true) is either
1284 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1285 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1286 // crashed before doing so.)
1287
1288 // Log a warning, and forcibly turn the screen back on.
1289 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1290 + "Forcing the screen back on...");
1291 preventScreenOn(false);
1292 }
1293
1294 private Runnable mForceReenableScreenTask = new Runnable() {
1295 public void run() {
1296 forceReenableScreen();
1297 }
1298 };
1299
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001300 private int setScreenStateLocked(boolean on) {
1301 int err = Power.setScreenState(on);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001302 if (err == 0 && mUseSoftwareAutoBrightness) {
Mike Lockwood4984e732009-11-01 08:16:33 -05001303 enableLightSensor(on);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001304 if (!on) {
1305 // make sure button and key backlights are off too
1306 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1307 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
Mike Lockwood6c97fca2009-10-20 08:10:00 -04001308 // clear current value so we will update based on the new conditions
1309 // when the sensor is reenabled.
1310 mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001311 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001312 }
1313 return err;
1314 }
1315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 private void setPowerState(int state)
1317 {
1318 setPowerState(state, false, false);
1319 }
1320
1321 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1322 {
1323 synchronized (mLocks) {
1324 int err;
1325
1326 if (mSpew) {
1327 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1328 + " newState=0x" + Integer.toHexString(newState)
1329 + " noChangeLights=" + noChangeLights);
1330 }
1331
1332 if (noChangeLights) {
1333 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1334 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001335 if (mProximitySensorActive) {
1336 // don't turn on the screen when the proximity sensor lock is held
1337 newState = (newState & ~SCREEN_BRIGHT);
1338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339
1340 if (batteryIsLow()) {
1341 newState |= BATTERY_LOW_BIT;
1342 } else {
1343 newState &= ~BATTERY_LOW_BIT;
1344 }
1345 if (newState == mPowerState) {
1346 return;
1347 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001348
Mike Lockwood4984e732009-11-01 08:16:33 -05001349 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 newState |= ALL_BRIGHT;
1351 }
1352
1353 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1354 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1355
1356 if (mSpew) {
1357 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1358 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1359 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1360 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1361 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1362 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1363 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1364 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1365 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1366 + " newScreenOn=" + newScreenOn);
1367 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1368 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1369 }
1370
1371 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001372 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1374 }
1375
1376 if (oldScreenOn != newScreenOn) {
1377 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001378 // When the user presses the power button, we need to always send out the
1379 // notification that it's going to sleep so the keyguard goes on. But
1380 // we can't do that until the screen fades out, so we don't show the keyguard
1381 // too early.
1382 if (mStillNeedSleepNotification) {
1383 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1384 }
1385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 // Turn on the screen UNLESS there was a prior
1387 // preventScreenOn(true) request. (Note that the lifetime
1388 // of a single preventScreenOn() request is limited to 5
1389 // seconds to prevent a buggy app from disabling the
1390 // screen forever; see forceReenableScreen().)
1391 boolean reallyTurnScreenOn = true;
1392 if (mSpew) {
1393 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1394 + mPreventScreenOn);
1395 }
1396
1397 if (mPreventScreenOn) {
1398 if (mSpew) {
1399 Log.d(TAG, "- PREVENTING screen from really turning on!");
1400 }
1401 reallyTurnScreenOn = false;
1402 }
1403 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001404 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 long identity = Binder.clearCallingIdentity();
1406 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001407 mBatteryStats.noteScreenBrightness(
1408 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 mBatteryStats.noteScreenOn();
1410 } catch (RemoteException e) {
1411 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1412 } finally {
1413 Binder.restoreCallingIdentity(identity);
1414 }
1415 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001416 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 // But continue as if we really did turn the screen on...
1418 err = 0;
1419 }
1420
1421 mScreenOnStartTime = SystemClock.elapsedRealtime();
1422 mLastTouchDown = 0;
1423 mTotalTouchDownTime = 0;
1424 mTouchCycles = 0;
1425 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1426 mTotalTouchDownTime, mTouchCycles);
1427 if (err == 0) {
1428 mPowerState |= SCREEN_ON_BIT;
1429 sendNotificationLocked(true, -1);
1430 }
1431 } else {
1432 mScreenOffTime = SystemClock.elapsedRealtime();
1433 long identity = Binder.clearCallingIdentity();
1434 try {
1435 mBatteryStats.noteScreenOff();
1436 } catch (RemoteException e) {
1437 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1438 } finally {
1439 Binder.restoreCallingIdentity(identity);
1440 }
1441 mPowerState &= ~SCREEN_ON_BIT;
1442 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001443 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 } else {
1445 mOffBecauseOfUser = becauseOfUser;
1446 err = 0;
1447 mLastTouchDown = 0;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
Joe Onorato128e7292009-03-24 18:41:31 -07001454 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 // I don't think we need to check the current state here because all of these
1456 // Power.setScreenState and sendNotificationLocked can both handle being
1457 // called multiple times in the same state. -joeo
1458 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1459 mTotalTouchDownTime, mTouchCycles);
1460 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001461 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if (mScreenOnStartTime != 0) {
1463 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1464 mScreenOnStartTime = 0;
1465 }
1466 if (err == 0) {
1467 int why = becauseOfUser
1468 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1469 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1470 sendNotificationLocked(false, why);
1471 }
1472 return err;
1473 }
1474
1475 private boolean batteryIsLow() {
1476 return (!mIsPowered &&
1477 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1478 }
1479
The Android Open Source Project10592532009-03-18 17:39:46 -07001480 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001481 final int oldState = mPowerState;
1482 final int realDifference = (newState ^ oldState);
1483 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001485 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487
1488 int offMask = 0;
1489 int dimMask = 0;
1490 int onMask = 0;
1491
1492 int preferredBrightness = getPreferredBrightness();
1493 boolean startAnimation = false;
1494
1495 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1496 if (ANIMATE_KEYBOARD_LIGHTS) {
1497 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1498 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001499 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1500 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 } else {
1502 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001503 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1504 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
1506 startAnimation = true;
1507 } else {
1508 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001511 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 }
1514 }
1515
1516 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1517 if (ANIMATE_BUTTON_LIGHTS) {
1518 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1519 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001520 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1521 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 } else {
1523 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001524 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1525 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 startAnimation = true;
1528 } else {
1529 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001530 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001532 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 }
1534 }
1535 }
1536
1537 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1538 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001539 int nominalCurrentValue = -1;
1540 // If there was an actual difference in the light state, then
1541 // figure out the "ideal" current value based on the previous
1542 // state. Otherwise, this is a change due to the brightness
1543 // override, so we want to animate from whatever the current
1544 // value is.
1545 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1546 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1547 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1548 nominalCurrentValue = preferredBrightness;
1549 break;
1550 case SCREEN_ON_BIT:
1551 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1552 break;
1553 case 0:
1554 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1555 break;
1556 case SCREEN_BRIGHT_BIT:
1557 default:
1558 // not possible
1559 nominalCurrentValue = (int)mScreenBrightness.curValue;
1560 break;
1561 }
Joe Onorato128e7292009-03-24 18:41:31 -07001562 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001563 int brightness = preferredBrightness;
1564 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1566 // dim or turn off backlight, depending on if the screen is on
1567 // the scale is because the brightness ramp isn't linear and this biases
1568 // it so the later parts take longer.
1569 final float scale = 1.5f;
1570 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1571 if (ratio > 1.0f) ratio = 1.0f;
1572 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1574 // was bright
1575 steps = ANIM_STEPS;
1576 } else {
1577 // was dim
1578 steps = (int)(ANIM_STEPS*ratio*scale);
1579 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001580 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if ((oldState & SCREEN_ON_BIT) != 0) {
1583 // was bright
1584 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1585 } else {
1586 // was dim
1587 steps = (int)(ANIM_STEPS*ratio);
1588 }
1589 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1590 // If the "stay on while plugged in" option is
1591 // turned on, then the screen will often not
1592 // automatically turn off while plugged in. To
1593 // still have a sense of when it is inactive, we
1594 // will then count going dim as turning off.
1595 mScreenOffTime = SystemClock.elapsedRealtime();
1596 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001597 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001600 long identity = Binder.clearCallingIdentity();
1601 try {
1602 mBatteryStats.noteScreenBrightness(brightness);
1603 } catch (RemoteException e) {
1604 // Nothing interesting to do.
1605 } finally {
1606 Binder.restoreCallingIdentity(identity);
1607 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001608 if (mScreenBrightness.setTargetLocked(brightness,
1609 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1610 startAnimation = true;
1611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 } else {
1613 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1614 // dim or turn off backlight, depending on if the screen is on
1615 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001616 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001618 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001621 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
1624 }
1625
1626 if (startAnimation) {
1627 if (mSpew) {
1628 Log.i(TAG, "Scheduling light animator!");
1629 }
1630 mHandler.removeCallbacks(mLightAnimator);
1631 mHandler.post(mLightAnimator);
1632 }
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if (offMask != 0) {
1635 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001636 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638 if (dimMask != 0) {
1639 int brightness = Power.BRIGHTNESS_DIM;
1640 if ((newState & BATTERY_LOW_BIT) != 0 &&
1641 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1642 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1643 }
1644 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001645 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 if (onMask != 0) {
1648 int brightness = getPreferredBrightness();
1649 if ((newState & BATTERY_LOW_BIT) != 0 &&
1650 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1651 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1652 }
1653 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001654 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657
The Android Open Source Project10592532009-03-18 17:39:46 -07001658 private void setLightBrightness(int mask, int value) {
1659 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1660 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1661 }
1662 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1663 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1664 }
1665 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1666 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
1670 class BrightnessState {
1671 final int mask;
1672
1673 boolean initialized;
1674 int targetValue;
1675 float curValue;
1676 float delta;
1677 boolean animating;
1678
1679 BrightnessState(int m) {
1680 mask = m;
1681 }
1682
1683 public void dump(PrintWriter pw, String prefix) {
1684 pw.println(prefix + "animating=" + animating
1685 + " targetValue=" + targetValue
1686 + " curValue=" + curValue
1687 + " delta=" + delta);
1688 }
1689
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001690 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001691 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 if (!initialized) {
1693 initialized = true;
1694 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001695 } else if (targetValue == target) {
1696 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001699 delta = (targetValue -
1700 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1701 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001703 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001705 + " target=" + targetValue + " delta=" + delta
1706 + " nominalCurrentValue=" + nominalCurrentValue
1707 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001710 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
1712
1713 boolean stepLocked() {
1714 if (!animating) return false;
1715 if (false && mSpew) {
1716 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1717 + " target=" + targetValue + " delta=" + delta);
1718 }
1719 curValue += delta;
1720 int curIntValue = (int)curValue;
1721 boolean more = true;
1722 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001723 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 more = false;
1725 } else if (delta > 0) {
1726 if (curIntValue >= targetValue) {
1727 curValue = curIntValue = targetValue;
1728 more = false;
1729 }
1730 } else {
1731 if (curIntValue <= targetValue) {
1732 curValue = curIntValue = targetValue;
1733 more = false;
1734 }
1735 }
1736 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001737 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 animating = more;
1739 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001740 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001741 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743 }
1744 return more;
1745 }
1746 }
1747
1748 private class LightAnimator implements Runnable {
1749 public void run() {
1750 synchronized (mLocks) {
1751 long now = SystemClock.uptimeMillis();
1752 boolean more = mScreenBrightness.stepLocked();
1753 if (mKeyboardBrightness.stepLocked()) {
1754 more = true;
1755 }
1756 if (mButtonBrightness.stepLocked()) {
1757 more = true;
1758 }
1759 if (more) {
1760 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1761 }
1762 }
1763 }
1764 }
1765
1766 private int getPreferredBrightness() {
1767 try {
1768 if (mScreenBrightnessOverride >= 0) {
1769 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001770 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1771 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001772 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1775 SCREEN_BRIGHTNESS);
1776 // Don't let applications turn the screen all the way off
1777 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1778 } catch (SettingNotFoundException snfe) {
1779 return Power.BRIGHTNESS_ON;
1780 }
1781 }
1782
1783 boolean screenIsOn() {
1784 synchronized (mLocks) {
1785 return (mPowerState & SCREEN_ON_BIT) != 0;
1786 }
1787 }
1788
1789 boolean screenIsBright() {
1790 synchronized (mLocks) {
1791 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1792 }
1793 }
1794
Mike Lockwood200b30b2009-09-20 00:23:59 -04001795 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001796 // cancel animation so userActivity will succeed
1797 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001798 boolean savedActivityAllowed = mUserActivityAllowed;
1799 mUserActivityAllowed = true;
1800 userActivity(SystemClock.uptimeMillis(), false);
1801 mUserActivityAllowed = savedActivityAllowed;
1802 }
1803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1805 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1806 userActivity(time, noChangeLights, OTHER_EVENT, force);
1807 }
1808
1809 public void userActivity(long time, boolean noChangeLights) {
1810 userActivity(time, noChangeLights, OTHER_EVENT, false);
1811 }
1812
1813 public void userActivity(long time, boolean noChangeLights, int eventType) {
1814 userActivity(time, noChangeLights, eventType, false);
1815 }
1816
1817 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1818 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1819
1820 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001821 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001823 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 return;
1826 }
1827
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001828 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1829 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1830 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1831 if (false) {
1832 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1833 }
1834 return;
1835 }
1836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 if (false) {
1838 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1839 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1840 } else {
1841 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1842 }
1843 }
1844
1845 synchronized (mLocks) {
1846 if (mSpew) {
1847 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1848 + " mUserActivityAllowed=" + mUserActivityAllowed
1849 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001850 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1851 + " mProximitySensorActive=" + mProximitySensorActive
1852 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
Mike Lockwood05067122009-10-27 23:07:25 -04001854 // ignore user activity if we are in the process of turning off the screen
1855 if (mScreenBrightness.animating && mScreenBrightness.targetValue == 0) {
1856 Log.d(TAG, "ignoring user activity while turning off screen");
1857 return;
1858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 if (mLastEventTime <= time || force) {
1860 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001861 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001862 // Only turn on button backlights if a button was pressed
1863 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001864 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1866 } else {
1867 // don't clear button/keyboard backlights when the screen is touched.
1868 mUserState |= SCREEN_BRIGHT;
1869 }
1870
Dianne Hackborn617f8772009-03-31 15:04:46 -07001871 int uid = Binder.getCallingUid();
1872 long ident = Binder.clearCallingIdentity();
1873 try {
1874 mBatteryStats.noteUserActivity(uid, eventType);
1875 } catch (RemoteException e) {
1876 // Ignore
1877 } finally {
1878 Binder.restoreCallingIdentity(ident);
1879 }
1880
Michael Chane96440f2009-05-06 10:27:36 -07001881 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1883 setTimeoutLocked(time, SCREEN_BRIGHT);
1884 }
1885 }
1886 }
1887 }
1888
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001889 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1890 try {
1891 int i;
1892 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1893 if (sensorValue < mAutoBrightnessLevels[i]) {
1894 break;
1895 }
1896 }
1897 return values[i];
1898 } catch (Exception e) {
1899 // guard against null pointer or index out of bounds errors
1900 Log.e(TAG, "getAutoBrightnessValue", e);
1901 return 255;
1902 }
1903 }
1904
Mike Lockwood20f87d72009-11-05 16:08:51 -05001905 private Runnable mProximityTask = new Runnable() {
1906 public void run() {
1907 synchronized (mLocks) {
1908 if (mProximityPendingValue != -1) {
1909 proximityChangedLocked(mProximityPendingValue == 1);
1910 mProximityPendingValue = -1;
1911 }
1912 }
1913 }
1914 };
1915
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001916 private Runnable mAutoBrightnessTask = new Runnable() {
1917 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001918 synchronized (mLocks) {
1919 int value = (int)mLightSensorPendingValue;
1920 if (value >= 0) {
1921 mLightSensorPendingValue = -1;
1922 lightSensorChangedLocked(value);
1923 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001924 }
1925 }
1926 };
1927
1928 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001929 if (mDebugLightSensor) {
1930 Log.d(TAG, "lightSensorChangedLocked " + value);
1931 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001932
1933 if (mLightSensorValue != value) {
1934 mLightSensorValue = value;
1935 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1936 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1937 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001938 int keyboardValue;
1939 if (mKeyboardVisible) {
1940 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1941 } else {
1942 keyboardValue = 0;
1943 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001944 mLightSensorBrightness = lcdValue;
1945
1946 if (mDebugLightSensor) {
1947 Log.d(TAG, "lcdValue " + lcdValue);
1948 Log.d(TAG, "buttonValue " + buttonValue);
1949 Log.d(TAG, "keyboardValue " + keyboardValue);
1950 }
1951
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001952 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001953 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001954 if (ANIMATE_SCREEN_LIGHTS) {
1955 if (mScreenBrightness.setTargetLocked(lcdValue,
1956 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1957 (int)mScreenBrightness.curValue)) {
1958 startAnimation = true;
1959 }
1960 } else {
1961 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1962 lcdValue);
1963 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001964 }
1965 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001966 if (mButtonBrightness.setTargetLocked(buttonValue,
1967 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1968 (int)mButtonBrightness.curValue)) {
1969 startAnimation = true;
1970 }
1971 } else {
1972 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1973 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001974 }
1975 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001976 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1977 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1978 (int)mKeyboardBrightness.curValue)) {
1979 startAnimation = true;
1980 }
1981 } else {
1982 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1983 keyboardValue);
1984 }
1985 if (startAnimation) {
1986 if (mDebugLightSensor) {
1987 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
1988 }
1989 mHandler.removeCallbacks(mLightAnimator);
1990 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001991 }
1992 }
1993 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001994 }
1995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 /**
1997 * The user requested that we go to sleep (probably with the power button).
1998 * This overrides all wake locks that are held.
1999 */
2000 public void goToSleep(long time)
2001 {
2002 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2003 synchronized (mLocks) {
2004 goToSleepLocked(time);
2005 }
2006 }
2007
2008 /**
2009 * Returns the time the screen has been on since boot, in millis.
2010 * @return screen on time
2011 */
2012 public long getScreenOnTime() {
2013 synchronized (mLocks) {
2014 if (mScreenOnStartTime == 0) {
2015 return mScreenOnTime;
2016 } else {
2017 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2018 }
2019 }
2020 }
2021
2022 private void goToSleepLocked(long time) {
2023
2024 if (mLastEventTime <= time) {
2025 mLastEventTime = time;
2026 // cancel all of the wake locks
2027 mWakeLockState = SCREEN_OFF;
2028 int N = mLocks.size();
2029 int numCleared = 0;
2030 for (int i=0; i<N; i++) {
2031 WakeLock wl = mLocks.get(i);
2032 if (isScreenLock(wl.flags)) {
2033 mLocks.get(i).activated = false;
2034 numCleared++;
2035 }
2036 }
2037 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002038 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 mUserState = SCREEN_OFF;
2040 setPowerState(SCREEN_OFF, false, true);
2041 cancelTimerLocked();
2042 }
2043 }
2044
2045 public long timeSinceScreenOn() {
2046 synchronized (mLocks) {
2047 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2048 return 0;
2049 }
2050 return SystemClock.elapsedRealtime() - mScreenOffTime;
2051 }
2052 }
2053
2054 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002055 synchronized (mLocks) {
2056 if (mSpew) {
2057 Log.d(TAG, "setKeyboardVisibility: " + visible);
2058 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002059 if (mKeyboardVisible != visible) {
2060 mKeyboardVisible = visible;
2061 // don't signal user activity if the screen is off; other code
2062 // will take care of turning on due to a true change to the lid
2063 // switch and synchronized with the lock screen.
2064 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002065 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002066 // force recompute of backlight values
2067 if (mLightSensorValue >= 0) {
2068 int value = (int)mLightSensorValue;
2069 mLightSensorValue = -1;
2070 lightSensorChangedLocked(value);
2071 }
2072 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002073 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2074 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002075 }
2076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
2078
2079 /**
2080 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2081 */
2082 public void enableUserActivity(boolean enabled) {
2083 synchronized (mLocks) {
2084 mUserActivityAllowed = enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086 }
2087
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002088 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002089 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002090 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002091 mAutoBrightessEnabled = enabled;
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002092 if (screenIsOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002093 // force recompute of backlight values
2094 if (mLightSensorValue >= 0) {
2095 int value = (int)mLightSensorValue;
2096 mLightSensorValue = -1;
2097 lightSensorChangedLocked(value);
2098 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002099 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002100 }
2101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 /** Sets the screen off timeouts:
2104 * mKeylightDelay
2105 * mDimDelay
2106 * mScreenOffDelay
2107 * */
2108 private void setScreenOffTimeoutsLocked() {
2109 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2110 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2111 mDimDelay = -1;
2112 mScreenOffDelay = 0;
2113 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2114 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2115 mDimDelay = -1;
2116 mScreenOffDelay = 0;
2117 } else {
2118 int totalDelay = mTotalDelaySetting;
2119 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2120 if (totalDelay < 0) {
2121 mScreenOffDelay = Integer.MAX_VALUE;
2122 } else if (mKeylightDelay < totalDelay) {
2123 // subtract the time that the keylight delay. This will give us the
2124 // remainder of the time that we need to sleep to get the accurate
2125 // screen off timeout.
2126 mScreenOffDelay = totalDelay - mKeylightDelay;
2127 } else {
2128 mScreenOffDelay = 0;
2129 }
2130 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2131 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2132 mScreenOffDelay = LONG_DIM_TIME;
2133 } else {
2134 mDimDelay = -1;
2135 }
2136 }
2137 if (mSpew) {
2138 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2139 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2140 + " mDimScreen=" + mDimScreen);
2141 }
2142 }
2143
2144 /**
2145 * Refreshes cached Gservices settings. Called once on startup, and
2146 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2147 * GservicesChangedReceiver).
2148 */
2149 private void updateGservicesValues() {
2150 mShortKeylightDelay = Settings.Gservices.getInt(
2151 mContext.getContentResolver(),
2152 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2153 SHORT_KEYLIGHT_DELAY_DEFAULT);
2154 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2155 }
2156
2157 /**
2158 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2159 * which tells us we need to refresh our cached Gservices settings.
2160 */
2161 private class GservicesChangedReceiver extends BroadcastReceiver {
2162 @Override
2163 public void onReceive(Context context, Intent intent) {
2164 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2165 updateGservicesValues();
2166 }
2167 }
2168
2169 private class LockList extends ArrayList<WakeLock>
2170 {
2171 void addLock(WakeLock wl)
2172 {
2173 int index = getIndex(wl.binder);
2174 if (index < 0) {
2175 this.add(wl);
2176 }
2177 }
2178
2179 WakeLock removeLock(IBinder binder)
2180 {
2181 int index = getIndex(binder);
2182 if (index >= 0) {
2183 return this.remove(index);
2184 } else {
2185 return null;
2186 }
2187 }
2188
2189 int getIndex(IBinder binder)
2190 {
2191 int N = this.size();
2192 for (int i=0; i<N; i++) {
2193 if (this.get(i).binder == binder) {
2194 return i;
2195 }
2196 }
2197 return -1;
2198 }
2199
2200 int gatherState()
2201 {
2202 int result = 0;
2203 int N = this.size();
2204 for (int i=0; i<N; i++) {
2205 WakeLock wl = this.get(i);
2206 if (wl.activated) {
2207 if (isScreenLock(wl.flags)) {
2208 result |= wl.minState;
2209 }
2210 }
2211 }
2212 return result;
2213 }
Michael Chane96440f2009-05-06 10:27:36 -07002214
2215 int reactivateScreenLocksLocked()
2216 {
2217 int result = 0;
2218 int N = this.size();
2219 for (int i=0; i<N; i++) {
2220 WakeLock wl = this.get(i);
2221 if (isScreenLock(wl.flags)) {
2222 wl.activated = true;
2223 result |= wl.minState;
2224 }
2225 }
2226 return result;
2227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229
2230 void setPolicy(WindowManagerPolicy p) {
2231 synchronized (mLocks) {
2232 mPolicy = p;
2233 mLocks.notifyAll();
2234 }
2235 }
2236
2237 WindowManagerPolicy getPolicyLocked() {
2238 while (mPolicy == null || !mDoneBooting) {
2239 try {
2240 mLocks.wait();
2241 } catch (InterruptedException e) {
2242 // Ignore
2243 }
2244 }
2245 return mPolicy;
2246 }
2247
2248 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002249 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2250 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2251 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002252 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002253 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002254 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002255 }
2256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 synchronized (mLocks) {
2258 Log.d(TAG, "system ready!");
2259 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002260 long identity = Binder.clearCallingIdentity();
2261 try {
2262 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2263 mBatteryStats.noteScreenOn();
2264 } catch (RemoteException e) {
2265 // Nothing interesting to do.
2266 } finally {
2267 Binder.restoreCallingIdentity(identity);
2268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2270 updateWakeLockLocked();
2271 mLocks.notifyAll();
2272 }
2273 }
2274
2275 public void monitor() {
2276 synchronized (mLocks) { }
2277 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002278
2279 public int getSupportedWakeLockFlags() {
2280 int result = PowerManager.PARTIAL_WAKE_LOCK
2281 | PowerManager.FULL_WAKE_LOCK
2282 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2283
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002284 if (mProximitySensor != null) {
2285 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2286 }
2287
2288 return result;
2289 }
2290
Mike Lockwood237a2992009-09-15 14:42:16 -04002291 public void setBacklightBrightness(int brightness) {
2292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2293 // Don't let applications turn the screen all the way off
2294 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2295 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
Mike Lockwooddf024922009-10-29 21:29:15 -04002296 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2297 (mKeyboardVisible ? brightness : 0));
Mike Lockwood237a2992009-09-15 14:42:16 -04002298 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2299 long identity = Binder.clearCallingIdentity();
2300 try {
2301 mBatteryStats.noteScreenBrightness(brightness);
2302 } catch (RemoteException e) {
2303 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2304 } finally {
2305 Binder.restoreCallingIdentity(identity);
2306 }
2307
2308 // update our animation state
2309 if (ANIMATE_SCREEN_LIGHTS) {
2310 mScreenBrightness.curValue = brightness;
2311 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002312 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002313 }
2314 if (ANIMATE_KEYBOARD_LIGHTS) {
2315 mKeyboardBrightness.curValue = brightness;
2316 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002317 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002318 }
2319 if (ANIMATE_BUTTON_LIGHTS) {
2320 mButtonBrightness.curValue = brightness;
2321 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002322 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002323 }
2324 }
2325
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002326 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002327 if (mSpew) {
2328 Log.d(TAG, "enableProximityLockLocked");
2329 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002330 // clear calling identity so sensor manager battery stats are accurate
2331 long identity = Binder.clearCallingIdentity();
2332 try {
2333 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2334 SensorManager.SENSOR_DELAY_NORMAL);
2335 } finally {
2336 Binder.restoreCallingIdentity(identity);
2337 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002338 }
2339
2340 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002341 if (mSpew) {
2342 Log.d(TAG, "disableProximityLockLocked");
2343 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002344 // clear calling identity so sensor manager battery stats are accurate
2345 long identity = Binder.clearCallingIdentity();
2346 try {
2347 mSensorManager.unregisterListener(mProximityListener);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002348 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002349 } finally {
2350 Binder.restoreCallingIdentity(identity);
2351 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002352 if (mProximitySensorActive) {
2353 mProximitySensorActive = false;
2354 forceUserActivityLocked();
Mike Lockwood200b30b2009-09-20 00:23:59 -04002355 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002356 }
2357
Mike Lockwood20f87d72009-11-05 16:08:51 -05002358 private void proximityChangedLocked(boolean active) {
2359 if (mSpew) {
2360 Log.d(TAG, "proximityChangedLocked, active: " + active);
2361 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002362 if (mProximityCount <= 0) {
2363 Log.d(TAG, "Ignoring proximity change after last proximity lock is released");
2364 return;
2365 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002366 if (active) {
2367 goToSleepLocked(SystemClock.uptimeMillis());
2368 mProximitySensorActive = true;
2369 } else {
2370 // proximity sensor negative events trigger as user activity.
2371 // temporarily set mUserActivityAllowed to true so this will work
2372 // even when the keyguard is on.
2373 mProximitySensorActive = false;
2374 forceUserActivityLocked();
2375 }
2376 }
2377
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002378 private void enableLightSensor(boolean enable) {
2379 if (mDebugLightSensor) {
2380 Log.d(TAG, "enableLightSensor " + enable);
2381 }
2382 if (mSensorManager != null && mLightSensorEnabled != enable) {
2383 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002384 // clear calling identity so sensor manager battery stats are accurate
2385 long identity = Binder.clearCallingIdentity();
2386 try {
2387 if (enable) {
2388 mSensorManager.registerListener(mLightListener, mLightSensor,
2389 SensorManager.SENSOR_DELAY_NORMAL);
2390 } else {
2391 mSensorManager.unregisterListener(mLightListener);
2392 mHandler.removeCallbacks(mAutoBrightnessTask);
2393 }
2394 } finally {
2395 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002396 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002397 }
2398 }
2399
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002400 SensorEventListener mProximityListener = new SensorEventListener() {
2401 public void onSensorChanged(SensorEvent event) {
2402 long milliseconds = event.timestamp / 1000000;
2403 synchronized (mLocks) {
2404 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002405 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2406 mLastProximityEventTime = milliseconds;
2407 mHandler.removeCallbacks(mProximityTask);
2408
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002409 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002410 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2411 distance < mProximitySensor.getMaximumRange());
2412
2413 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2414 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2415 mProximityPendingValue = (active ? 1 : 0);
2416 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002417 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002418 // process the value immediately
2419 mProximityPendingValue = -1;
2420 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002421 }
2422 }
2423 }
2424
2425 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2426 // ignore
2427 }
2428 };
2429
2430 SensorEventListener mLightListener = new SensorEventListener() {
2431 public void onSensorChanged(SensorEvent event) {
2432 synchronized (mLocks) {
2433 int value = (int)event.values[0];
2434 if (mDebugLightSensor) {
2435 Log.d(TAG, "onSensorChanged: light value: " + value);
2436 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002437 mHandler.removeCallbacks(mAutoBrightnessTask);
2438 if (mLightSensorValue != value) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002439 if (mLightSensorValue == -1) {
2440 // process the value immediately
2441 lightSensorChangedLocked(value);
2442 } else {
2443 // delay processing to debounce the sensor
2444 mLightSensorPendingValue = value;
2445 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2446 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002447 } else {
2448 mLightSensorPendingValue = -1;
2449 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002450 }
2451 }
2452
2453 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2454 // ignore
2455 }
2456 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457}