blob: af93d3639de7a83135995619c0f0d182db85595e [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.
Mike Lockwood9b8136922009-11-06 15:53:59 -050094 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070095
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>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500215 // mScreenOnTime and mScreenOnStartTime are used for computing total time screen
216 // has been on since boot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 private long mScreenOnTime;
218 private long mScreenOnStartTime;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500219 // mLastScreenOnTime is the time the screen was last turned on
220 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 private boolean mPreventScreenOn;
222 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400223 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700224 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700225 private int[] mAutoBrightnessLevels;
226 private int[] mLcdBacklightValues;
227 private int[] mButtonBacklightValues;
228 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500229 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
231 // Used when logging number and duration of touch-down cycles
232 private long mTotalTouchDownTime;
233 private long mLastTouchDown;
234 private int mTouchCycles;
235
236 // could be either static or controllable at runtime
237 private static final boolean mSpew = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400238 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 /*
241 static PrintStream mLog;
242 static {
243 try {
244 mLog = new PrintStream("/data/power.log");
245 }
246 catch (FileNotFoundException e) {
247 android.util.Log.e(TAG, "Life is hard", e);
248 }
249 }
250 static class Log {
251 static void d(String tag, String s) {
252 mLog.println(s);
253 android.util.Log.d(tag, s);
254 }
255 static void i(String tag, String s) {
256 mLog.println(s);
257 android.util.Log.i(tag, s);
258 }
259 static void w(String tag, String s) {
260 mLog.println(s);
261 android.util.Log.w(tag, s);
262 }
263 static void e(String tag, String s) {
264 mLog.println(s);
265 android.util.Log.e(tag, s);
266 }
267 }
268 */
269
270 /**
271 * This class works around a deadlock between the lock in PowerManager.WakeLock
272 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
273 * mToken object so it can be accessed from any thread, but it calls into here
274 * with its lock held. This class is essentially a reimplementation of
275 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
276 * only call it with our own locks held.
277 */
278 private class UnsynchronizedWakeLock {
279 int mFlags;
280 String mTag;
281 IBinder mToken;
282 int mCount = 0;
283 boolean mRefCounted;
284
285 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
286 mFlags = flags;
287 mTag = tag;
288 mToken = new Binder();
289 mRefCounted = refCounted;
290 }
291
292 public void acquire() {
293 if (!mRefCounted || mCount++ == 0) {
294 long ident = Binder.clearCallingIdentity();
295 try {
296 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
297 MY_UID, mTag);
298 } finally {
299 Binder.restoreCallingIdentity(ident);
300 }
301 }
302 }
303
304 public void release() {
305 if (!mRefCounted || --mCount == 0) {
306 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
307 }
308 if (mCount < 0) {
309 throw new RuntimeException("WakeLock under-locked " + mTag);
310 }
311 }
312
313 public String toString() {
314 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
315 + " mCount=" + mCount + ")";
316 }
317 }
318
319 private final class BatteryReceiver extends BroadcastReceiver {
320 @Override
321 public void onReceive(Context context, Intent intent) {
322 synchronized (mLocks) {
323 boolean wasPowered = mIsPowered;
324 mIsPowered = mBatteryService.isPowered();
325
326 if (mIsPowered != wasPowered) {
327 // update mStayOnWhilePluggedIn wake lock
328 updateWakeLockLocked();
329
330 // treat plugging and unplugging the devices as a user activity.
331 // users find it disconcerting when they unplug the device
332 // and it shuts off right away.
333 // temporarily set mUserActivityAllowed to true so this will work
334 // even when the keyguard is on.
335 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400336 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338 }
339 }
340 }
341 }
342
343 /**
344 * Set the setting that determines whether the device stays on when plugged in.
345 * The argument is a bit string, with each bit specifying a power source that,
346 * when the device is connected to that source, causes the device to stay on.
347 * See {@link android.os.BatteryManager} for the list of power sources that
348 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
349 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
350 * @param val an {@code int} containing the bits that specify which power sources
351 * should cause the device to stay on.
352 */
353 public void setStayOnSetting(int val) {
354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
355 Settings.System.putInt(mContext.getContentResolver(),
356 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
357 }
358
359 private class SettingsObserver implements Observer {
360 private int getInt(String name) {
361 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
362 }
363
364 public void update(Observable o, Object arg) {
365 synchronized (mLocks) {
366 // STAY_ON_WHILE_PLUGGED_IN
367 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
368 updateWakeLockLocked();
369
370 // SCREEN_OFF_TIMEOUT
371 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
372
373 // DIM_SCREEN
374 //mDimScreen = getInt(DIM_SCREEN) != 0;
375
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700376 // SCREEN_BRIGHTNESS_MODE
377 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 // recalculate everything
380 setScreenOffTimeoutsLocked();
381 }
382 }
383 }
384
385 PowerManagerService()
386 {
387 // Hack to get our uid... should have a func for this.
388 long token = Binder.clearCallingIdentity();
389 MY_UID = Binder.getCallingUid();
390 Binder.restoreCallingIdentity(token);
391
392 // XXX remove this when the kernel doesn't timeout wake locks
393 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
394
395 // assume nothing is on yet
396 mUserState = mPowerState = 0;
397
398 // Add ourself to the Watchdog monitors.
399 Watchdog.getInstance().addMonitor(this);
400 mScreenOnStartTime = SystemClock.elapsedRealtime();
401 }
402
403 private ContentQueryMap mSettings;
404
The Android Open Source Project10592532009-03-18 17:39:46 -0700405 void init(Context context, HardwareService hardware, IActivityManager activity,
406 BatteryService battery) {
407 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 mContext = context;
409 mActivityService = activity;
410 mBatteryStats = BatteryStatsService.getService();
411 mBatteryService = battery;
412
413 mHandlerThread = new HandlerThread("PowerManagerService") {
414 @Override
415 protected void onLooperPrepared() {
416 super.onLooperPrepared();
417 initInThread();
418 }
419 };
420 mHandlerThread.start();
421
422 synchronized (mHandlerThread) {
423 while (!mInitComplete) {
424 try {
425 mHandlerThread.wait();
426 } catch (InterruptedException e) {
427 // Ignore
428 }
429 }
430 }
431 }
432
433 void initInThread() {
434 mHandler = new Handler();
435
436 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700437 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
439 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
440 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
441 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
442 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
443 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
444
445 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
446 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
447 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
448 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
449
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700450 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400451
452 // read settings for auto-brightness
453 mUseSoftwareAutoBrightness = resources.getBoolean(
454 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400455 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700456 mAutoBrightnessLevels = resources.getIntArray(
457 com.android.internal.R.array.config_autoBrightnessLevels);
458 mLcdBacklightValues = resources.getIntArray(
459 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
460 mButtonBacklightValues = resources.getIntArray(
461 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
462 mKeyboardBacklightValues = resources.getIntArray(
463 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500464 mLightSensorWarmupTime = resources.getInteger(
465 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700466 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700467
468 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
470 "(" + Settings.System.NAME + "=?) or ("
471 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700472 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700474 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
475 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 null);
477 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
478 SettingsObserver settingsObserver = new SettingsObserver();
479 mSettings.addObserver(settingsObserver);
480
481 // pretend that the settings changed so we will get their initial state
482 settingsObserver.update(mSettings, null);
483
484 // register for the battery changed notifications
485 IntentFilter filter = new IntentFilter();
486 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
487 mContext.registerReceiver(new BatteryReceiver(), filter);
488
489 // Listen for Gservices changes
490 IntentFilter gservicesChangedFilter =
491 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
492 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
493 // And explicitly do the initial update of our cached settings
494 updateGservicesValues();
495
Mike Lockwood4984e732009-11-01 08:16:33 -0500496 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400497 // turn the screen on
498 setPowerState(SCREEN_BRIGHT);
499 } else {
500 // turn everything on
501 setPowerState(ALL_BRIGHT);
502 }
Dan Murphy951764b2009-08-27 14:59:03 -0500503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 synchronized (mHandlerThread) {
505 mInitComplete = true;
506 mHandlerThread.notifyAll();
507 }
508 }
509
510 private class WakeLock implements IBinder.DeathRecipient
511 {
512 WakeLock(int f, IBinder b, String t, int u) {
513 super();
514 flags = f;
515 binder = b;
516 tag = t;
517 uid = u == MY_UID ? Process.SYSTEM_UID : u;
518 if (u != MY_UID || (
519 !"KEEP_SCREEN_ON_FLAG".equals(tag)
520 && !"KeyInputQueue".equals(tag))) {
521 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
522 ? BatteryStats.WAKE_TYPE_PARTIAL
523 : BatteryStats.WAKE_TYPE_FULL;
524 } else {
525 monitorType = -1;
526 }
527 try {
528 b.linkToDeath(this, 0);
529 } catch (RemoteException e) {
530 binderDied();
531 }
532 }
533 public void binderDied() {
534 synchronized (mLocks) {
535 releaseWakeLockLocked(this.binder, true);
536 }
537 }
538 final int flags;
539 final IBinder binder;
540 final String tag;
541 final int uid;
542 final int monitorType;
543 boolean activated = true;
544 int minState;
545 }
546
547 private void updateWakeLockLocked() {
548 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
549 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
550 mStayOnWhilePluggedInScreenDimLock.acquire();
551 mStayOnWhilePluggedInPartialLock.acquire();
552 } else {
553 mStayOnWhilePluggedInScreenDimLock.release();
554 mStayOnWhilePluggedInPartialLock.release();
555 }
556 }
557
558 private boolean isScreenLock(int flags)
559 {
560 int n = flags & LOCK_MASK;
561 return n == PowerManager.FULL_WAKE_LOCK
562 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
563 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
564 }
565
566 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700568 if (uid != Process.myUid()) {
569 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 long ident = Binder.clearCallingIdentity();
572 try {
573 synchronized (mLocks) {
574 acquireWakeLockLocked(flags, lock, uid, tag);
575 }
576 } finally {
577 Binder.restoreCallingIdentity(ident);
578 }
579 }
580
581 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
582 int acquireUid = -1;
583 String acquireName = null;
584 int acquireType = -1;
585
586 if (mSpew) {
587 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
588 }
589
590 int index = mLocks.getIndex(lock);
591 WakeLock wl;
592 boolean newlock;
593 if (index < 0) {
594 wl = new WakeLock(flags, lock, tag, uid);
595 switch (wl.flags & LOCK_MASK)
596 {
597 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500598 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400599 wl.minState = SCREEN_BRIGHT;
600 } else {
601 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 break;
604 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
605 wl.minState = SCREEN_BRIGHT;
606 break;
607 case PowerManager.SCREEN_DIM_WAKE_LOCK:
608 wl.minState = SCREEN_DIM;
609 break;
610 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700611 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 break;
613 default:
614 // just log and bail. we're in the server, so don't
615 // throw an exception.
616 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
617 + " flags=" + flags);
618 return;
619 }
620 mLocks.addLock(wl);
621 newlock = true;
622 } else {
623 wl = mLocks.get(index);
624 newlock = false;
625 }
626 if (isScreenLock(flags)) {
627 // if this causes a wakeup, we reactivate all of the locks and
628 // set it to whatever they want. otherwise, we modulate that
629 // by the current state so we never turn it more on than
630 // it already is.
631 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700632 int oldWakeLockState = mWakeLockState;
633 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 if (mSpew) {
635 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700636 + " mWakeLockState=0x"
637 + Integer.toHexString(mWakeLockState)
638 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 } else {
641 if (mSpew) {
642 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
643 + " mLocks.gatherState()=0x"
644 + Integer.toHexString(mLocks.gatherState())
645 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
646 }
647 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
648 }
649 setPowerState(mWakeLockState | mUserState);
650 }
651 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
652 if (newlock) {
653 mPartialCount++;
654 if (mPartialCount == 1) {
655 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
656 }
657 }
658 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700659 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
660 mProximityCount++;
661 if (mProximityCount == 1) {
662 enableProximityLockLocked();
663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
665 if (newlock) {
666 acquireUid = wl.uid;
667 acquireName = wl.tag;
668 acquireType = wl.monitorType;
669 }
670
671 if (acquireType >= 0) {
672 try {
673 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
674 } catch (RemoteException e) {
675 // Ignore
676 }
677 }
678 }
679
680 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700681 int uid = Binder.getCallingUid();
682 if (uid != Process.myUid()) {
683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
686 synchronized (mLocks) {
687 releaseWakeLockLocked(lock, false);
688 }
689 }
690
691 private void releaseWakeLockLocked(IBinder lock, boolean death) {
692 int releaseUid;
693 String releaseName;
694 int releaseType;
695
696 WakeLock wl = mLocks.removeLock(lock);
697 if (wl == null) {
698 return;
699 }
700
701 if (mSpew) {
702 Log.d(TAG, "releaseWakeLock flags=0x"
703 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
704 }
705
706 if (isScreenLock(wl.flags)) {
707 mWakeLockState = mLocks.gatherState();
708 // goes in the middle to reduce flicker
709 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
710 userActivity(SystemClock.uptimeMillis(), false);
711 }
712 setPowerState(mWakeLockState | mUserState);
713 }
714 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
715 mPartialCount--;
716 if (mPartialCount == 0) {
717 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
718 Power.releaseWakeLock(PARTIAL_NAME);
719 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700720 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
721 mProximityCount--;
722 if (mProximityCount == 0) {
723 disableProximityLockLocked();
724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 }
726 // Unlink the lock from the binder.
727 wl.binder.unlinkToDeath(wl, 0);
728 releaseUid = wl.uid;
729 releaseName = wl.tag;
730 releaseType = wl.monitorType;
731
732 if (releaseType >= 0) {
733 long origId = Binder.clearCallingIdentity();
734 try {
735 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
736 } catch (RemoteException e) {
737 // Ignore
738 } finally {
739 Binder.restoreCallingIdentity(origId);
740 }
741 }
742 }
743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 private class PokeLock implements IBinder.DeathRecipient
745 {
746 PokeLock(int p, IBinder b, String t) {
747 super();
748 this.pokey = p;
749 this.binder = b;
750 this.tag = t;
751 try {
752 b.linkToDeath(this, 0);
753 } catch (RemoteException e) {
754 binderDied();
755 }
756 }
757 public void binderDied() {
758 setPokeLock(0, this.binder, this.tag);
759 }
760 int pokey;
761 IBinder binder;
762 String tag;
763 boolean awakeOnSet;
764 }
765
766 public void setPokeLock(int pokey, IBinder token, String tag) {
767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
768 if (token == null) {
769 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
770 return;
771 }
772
773 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
774 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
775 + " and POKE_LOCK_MEDIUM_TIMEOUT");
776 }
777
778 synchronized (mLocks) {
779 if (pokey != 0) {
780 PokeLock p = mPokeLocks.get(token);
781 int oldPokey = 0;
782 if (p != null) {
783 oldPokey = p.pokey;
784 p.pokey = pokey;
785 } else {
786 p = new PokeLock(pokey, token, tag);
787 mPokeLocks.put(token, p);
788 }
789 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
790 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
791 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
792 p.awakeOnSet = true;
793 }
794 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700795 PokeLock rLock = mPokeLocks.remove(token);
796 if (rLock != null) {
797 token.unlinkToDeath(rLock, 0);
798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800
801 int oldPokey = mPokey;
802 int cumulative = 0;
803 boolean oldAwakeOnSet = mPokeAwakeOnSet;
804 boolean awakeOnSet = false;
805 for (PokeLock p: mPokeLocks.values()) {
806 cumulative |= p.pokey;
807 if (p.awakeOnSet) {
808 awakeOnSet = true;
809 }
810 }
811 mPokey = cumulative;
812 mPokeAwakeOnSet = awakeOnSet;
813
814 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
815 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
816
817 if (oldCumulativeTimeout != newCumulativeTimeout) {
818 setScreenOffTimeoutsLocked();
819 // reset the countdown timer, but use the existing nextState so it doesn't
820 // change anything
821 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
822 }
823 }
824 }
825
826 private static String lockType(int type)
827 {
828 switch (type)
829 {
830 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700831 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700833 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700835 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700837 return "PARTIAL_WAKE_LOCK ";
838 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
839 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 default:
David Brown251faa62009-08-02 22:04:36 -0700841 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843 }
844
845 private static String dumpPowerState(int state) {
846 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
847 ? "KEYBOARD_BRIGHT_BIT " : "")
848 + (((state & SCREEN_BRIGHT_BIT) != 0)
849 ? "SCREEN_BRIGHT_BIT " : "")
850 + (((state & SCREEN_ON_BIT) != 0)
851 ? "SCREEN_ON_BIT " : "")
852 + (((state & BATTERY_LOW_BIT) != 0)
853 ? "BATTERY_LOW_BIT " : "");
854 }
855
856 @Override
857 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
858 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
859 != PackageManager.PERMISSION_GRANTED) {
860 pw.println("Permission Denial: can't dump PowerManager from from pid="
861 + Binder.getCallingPid()
862 + ", uid=" + Binder.getCallingUid());
863 return;
864 }
865
866 long now = SystemClock.uptimeMillis();
867
868 pw.println("Power Manager State:");
869 pw.println(" mIsPowered=" + mIsPowered
870 + " mPowerState=" + mPowerState
871 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
872 + " ms");
873 pw.println(" mPartialCount=" + mPartialCount);
874 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
875 pw.println(" mUserState=" + dumpPowerState(mUserState));
876 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
877 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
878 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
879 + " " + ((mNextTimeout-now)/1000) + "s from now");
880 pw.println(" mDimScreen=" + mDimScreen
881 + " mStayOnConditions=" + mStayOnConditions);
882 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
883 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700884 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
885 + ',' + mBroadcastQueue[2] + "}");
886 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
887 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
889 pw.println(" mKeyboardVisible=" + mKeyboardVisible
890 + " mUserActivityAllowed=" + mUserActivityAllowed);
891 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
892 + " mScreenOffDelay=" + mScreenOffDelay);
893 pw.println(" mPreventScreenOn=" + mPreventScreenOn
894 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
895 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500896 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
898 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
899 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
900 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700901 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500902 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
903 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700904 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
905 pw.println(" mLightSensorValue=" + mLightSensorValue);
906 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400907 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700908 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 mScreenBrightness.dump(pw, " mScreenBrightness: ");
910 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
911 mButtonBrightness.dump(pw, " mButtonBrightness: ");
912
913 int N = mLocks.size();
914 pw.println();
915 pw.println("mLocks.size=" + N + ":");
916 for (int i=0; i<N; i++) {
917 WakeLock wl = mLocks.get(i);
918 String type = lockType(wl.flags & LOCK_MASK);
919 String acquireCausesWakeup = "";
920 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
921 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
922 }
923 String activated = "";
924 if (wl.activated) {
925 activated = " activated";
926 }
927 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
928 + activated + " (minState=" + wl.minState + ")");
929 }
930
931 pw.println();
932 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
933 for (PokeLock p: mPokeLocks.values()) {
934 pw.println(" poke lock '" + p.tag + "':"
935 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
936 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700937 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
938 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
940 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
941 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
942 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
943 }
944
945 pw.println();
946 }
947
948 private void setTimeoutLocked(long now, int nextState)
949 {
950 if (mDoneBooting) {
951 mHandler.removeCallbacks(mTimeoutTask);
952 mTimeoutTask.nextState = nextState;
953 long when = now;
954 switch (nextState)
955 {
956 case SCREEN_BRIGHT:
957 when += mKeylightDelay;
958 break;
959 case SCREEN_DIM:
960 if (mDimDelay >= 0) {
961 when += mDimDelay;
962 break;
963 } else {
964 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
965 }
966 case SCREEN_OFF:
967 synchronized (mLocks) {
968 when += mScreenOffDelay;
969 }
970 break;
971 }
972 if (mSpew) {
973 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
974 + " when=" + when);
975 }
976 mHandler.postAtTime(mTimeoutTask, when);
977 mNextTimeout = when; // for debugging
978 }
979 }
980
981 private void cancelTimerLocked()
982 {
983 mHandler.removeCallbacks(mTimeoutTask);
984 mTimeoutTask.nextState = -1;
985 }
986
987 private class TimeoutTask implements Runnable
988 {
989 int nextState; // access should be synchronized on mLocks
990 public void run()
991 {
992 synchronized (mLocks) {
993 if (mSpew) {
994 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
995 }
996
997 if (nextState == -1) {
998 return;
999 }
1000
1001 mUserState = this.nextState;
1002 setPowerState(this.nextState | mWakeLockState);
1003
1004 long now = SystemClock.uptimeMillis();
1005
1006 switch (this.nextState)
1007 {
1008 case SCREEN_BRIGHT:
1009 if (mDimDelay >= 0) {
1010 setTimeoutLocked(now, SCREEN_DIM);
1011 break;
1012 }
1013 case SCREEN_DIM:
1014 setTimeoutLocked(now, SCREEN_OFF);
1015 break;
1016 }
1017 }
1018 }
1019 }
1020
1021 private void sendNotificationLocked(boolean on, int why)
1022 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001023 if (!on) {
1024 mStillNeedSleepNotification = false;
1025 }
1026
Joe Onorato128e7292009-03-24 18:41:31 -07001027 // Add to the queue.
1028 int index = 0;
1029 while (mBroadcastQueue[index] != -1) {
1030 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
Joe Onorato128e7292009-03-24 18:41:31 -07001032 mBroadcastQueue[index] = on ? 1 : 0;
1033 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034
Joe Onorato128e7292009-03-24 18:41:31 -07001035 // If we added it position 2, then there is a pair that can be stripped.
1036 // If we added it position 1 and we're turning the screen off, we can strip
1037 // the pair and do nothing, because the screen is already off, and therefore
1038 // keyguard has already been enabled.
1039 // However, if we added it at position 1 and we're turning it on, then position
1040 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1041 // on, so have to run the queue then.
1042 if (index == 2) {
1043 // Also, while we're collapsing them, if it's going to be an "off," and one
1044 // is off because of user, then use that, regardless of whether it's the first
1045 // or second one.
1046 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1047 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1048 }
1049 mBroadcastQueue[0] = on ? 1 : 0;
1050 mBroadcastQueue[1] = -1;
1051 mBroadcastQueue[2] = -1;
1052 index = 0;
1053 }
1054 if (index == 1 && !on) {
1055 mBroadcastQueue[0] = -1;
1056 mBroadcastQueue[1] = -1;
1057 index = -1;
1058 // The wake lock was being held, but we're not actually going to do any
1059 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1061 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001062 }
1063
1064 // Now send the message.
1065 if (index >= 0) {
1066 // Acquire the broadcast wake lock before changing the power
1067 // state. It will be release after the broadcast is sent.
1068 // We always increment the ref count for each notification in the queue
1069 // and always decrement when that notification is handled.
1070 mBroadcastWakeLock.acquire();
1071 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1072 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 }
1075
1076 private Runnable mNotificationTask = new Runnable()
1077 {
1078 public void run()
1079 {
Joe Onorato128e7292009-03-24 18:41:31 -07001080 while (true) {
1081 int value;
1082 int why;
1083 WindowManagerPolicy policy;
1084 synchronized (mLocks) {
1085 value = mBroadcastQueue[0];
1086 why = mBroadcastWhy[0];
1087 for (int i=0; i<2; i++) {
1088 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1089 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1090 }
1091 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
Joe Onorato128e7292009-03-24 18:41:31 -07001093 if (value == 1) {
1094 mScreenOnStart = SystemClock.uptimeMillis();
1095
1096 policy.screenTurnedOn();
1097 try {
1098 ActivityManagerNative.getDefault().wakingUp();
1099 } catch (RemoteException e) {
1100 // ignore it
1101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102
Joe Onorato128e7292009-03-24 18:41:31 -07001103 if (mSpew) {
1104 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1105 }
1106 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1107 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1108 mScreenOnBroadcastDone, mHandler, 0, null, null);
1109 } else {
1110 synchronized (mLocks) {
1111 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1112 mBroadcastWakeLock.mCount);
1113 mBroadcastWakeLock.release();
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116 }
Joe Onorato128e7292009-03-24 18:41:31 -07001117 else if (value == 0) {
1118 mScreenOffStart = SystemClock.uptimeMillis();
1119
1120 policy.screenTurnedOff(why);
1121 try {
1122 ActivityManagerNative.getDefault().goingToSleep();
1123 } catch (RemoteException e) {
1124 // ignore it.
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
Joe Onorato128e7292009-03-24 18:41:31 -07001127 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1128 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1129 mScreenOffBroadcastDone, mHandler, 0, null, null);
1130 } else {
1131 synchronized (mLocks) {
1132 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1133 mBroadcastWakeLock.mCount);
1134 mBroadcastWakeLock.release();
1135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137 }
Joe Onorato128e7292009-03-24 18:41:31 -07001138 else {
1139 // If we're in this case, then this handler is running for a previous
1140 // paired transaction. mBroadcastWakeLock will already have been released.
1141 break;
1142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
1144 }
1145 };
1146
1147 long mScreenOnStart;
1148 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1149 public void onReceive(Context context, Intent intent) {
1150 synchronized (mLocks) {
1151 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1152 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1153 mBroadcastWakeLock.release();
1154 }
1155 }
1156 };
1157
1158 long mScreenOffStart;
1159 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1160 public void onReceive(Context context, Intent intent) {
1161 synchronized (mLocks) {
1162 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1163 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1164 mBroadcastWakeLock.release();
1165 }
1166 }
1167 };
1168
1169 void logPointerUpEvent() {
1170 if (LOG_TOUCH_DOWNS) {
1171 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1172 mLastTouchDown = 0;
1173 }
1174 }
1175
1176 void logPointerDownEvent() {
1177 if (LOG_TOUCH_DOWNS) {
1178 // If we are not already timing a down/up sequence
1179 if (mLastTouchDown == 0) {
1180 mLastTouchDown = SystemClock.elapsedRealtime();
1181 mTouchCycles++;
1182 }
1183 }
1184 }
1185
1186 /**
1187 * Prevents the screen from turning on even if it *should* turn on due
1188 * to a subsequent full wake lock being acquired.
1189 * <p>
1190 * This is a temporary hack that allows an activity to "cover up" any
1191 * display glitches that happen during the activity's startup
1192 * sequence. (Specifically, this API was added to work around a
1193 * cosmetic bug in the "incoming call" sequence, where the lock screen
1194 * would flicker briefly before the incoming call UI became visible.)
1195 * TODO: There ought to be a more elegant way of doing this,
1196 * probably by having the PowerManager and ActivityManager
1197 * work together to let apps specify that the screen on/off
1198 * state should be synchronized with the Activity lifecycle.
1199 * <p>
1200 * Note that calling preventScreenOn(true) will NOT turn the screen
1201 * off if it's currently on. (This API only affects *future*
1202 * acquisitions of full wake locks.)
1203 * But calling preventScreenOn(false) WILL turn the screen on if
1204 * it's currently off because of a prior preventScreenOn(true) call.
1205 * <p>
1206 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1207 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1208 * call doesn't occur within 5 seconds, we'll turn the screen back on
1209 * ourselves (and log a warning about it); this prevents a buggy app
1210 * from disabling the screen forever.)
1211 * <p>
1212 * TODO: this feature should really be controlled by a new type of poke
1213 * lock (rather than an IPowerManager call).
1214 */
1215 public void preventScreenOn(boolean prevent) {
1216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1217
1218 synchronized (mLocks) {
1219 if (prevent) {
1220 // First of all, grab a partial wake lock to
1221 // make sure the CPU stays on during the entire
1222 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1223 mPreventScreenOnPartialLock.acquire();
1224
1225 // Post a forceReenableScreen() call (for 5 seconds in the
1226 // future) to make sure the matching preventScreenOn(false) call
1227 // has happened by then.
1228 mHandler.removeCallbacks(mForceReenableScreenTask);
1229 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1230
1231 // Finally, set the flag that prevents the screen from turning on.
1232 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001233 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 mPreventScreenOn = true;
1235 } else {
1236 // (Re)enable the screen.
1237 mPreventScreenOn = false;
1238
1239 // We're "undoing" a the prior preventScreenOn(true) call, so we
1240 // no longer need the 5-second safeguard.
1241 mHandler.removeCallbacks(mForceReenableScreenTask);
1242
1243 // Forcibly turn on the screen if it's supposed to be on. (This
1244 // handles the case where the screen is currently off because of
1245 // a prior preventScreenOn(true) call.)
1246 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1247 if (mSpew) {
1248 Log.d(TAG,
1249 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1250 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001251 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001253 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
1255 }
1256
1257 // Release the partial wake lock that we held during the
1258 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1259 mPreventScreenOnPartialLock.release();
1260 }
1261 }
1262 }
1263
1264 public void setScreenBrightnessOverride(int brightness) {
1265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1266
1267 synchronized (mLocks) {
1268 if (mScreenBrightnessOverride != brightness) {
1269 mScreenBrightnessOverride = brightness;
1270 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1271 }
1272 }
1273 }
1274
1275 /**
1276 * Sanity-check that gets called 5 seconds after any call to
1277 * preventScreenOn(true). This ensures that the original call
1278 * is followed promptly by a call to preventScreenOn(false).
1279 */
1280 private void forceReenableScreen() {
1281 // We shouldn't get here at all if mPreventScreenOn is false, since
1282 // we should have already removed any existing
1283 // mForceReenableScreenTask messages...
1284 if (!mPreventScreenOn) {
1285 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1286 return;
1287 }
1288
1289 // Uh oh. It's been 5 seconds since a call to
1290 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1291 // This means the app that called preventScreenOn(true) is either
1292 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1293 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1294 // crashed before doing so.)
1295
1296 // Log a warning, and forcibly turn the screen back on.
1297 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1298 + "Forcing the screen back on...");
1299 preventScreenOn(false);
1300 }
1301
1302 private Runnable mForceReenableScreenTask = new Runnable() {
1303 public void run() {
1304 forceReenableScreen();
1305 }
1306 };
1307
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001308 private int setScreenStateLocked(boolean on) {
1309 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001310 if (err == 0) {
1311 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1312 if (mUseSoftwareAutoBrightness) {
1313 enableLightSensor(on);
1314 if (!on) {
1315 // make sure button and key backlights are off too
1316 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1317 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
1318 // clear current value so we will update based on the new conditions
1319 // when the sensor is reenabled.
1320 mLightSensorValue = -1;
1321 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001322 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001323 }
1324 return err;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 private void setPowerState(int state)
1328 {
1329 setPowerState(state, false, false);
1330 }
1331
1332 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1333 {
1334 synchronized (mLocks) {
1335 int err;
1336
1337 if (mSpew) {
1338 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1339 + " newState=0x" + Integer.toHexString(newState)
1340 + " noChangeLights=" + noChangeLights);
1341 }
1342
1343 if (noChangeLights) {
1344 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1345 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001346 if (mProximitySensorActive) {
1347 // don't turn on the screen when the proximity sensor lock is held
1348 newState = (newState & ~SCREEN_BRIGHT);
1349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
1351 if (batteryIsLow()) {
1352 newState |= BATTERY_LOW_BIT;
1353 } else {
1354 newState &= ~BATTERY_LOW_BIT;
1355 }
1356 if (newState == mPowerState) {
1357 return;
1358 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001359
Mike Lockwood4984e732009-11-01 08:16:33 -05001360 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 newState |= ALL_BRIGHT;
1362 }
1363
1364 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1365 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1366
1367 if (mSpew) {
1368 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1369 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1370 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1371 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1372 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1373 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1374 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1375 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1376 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1377 + " newScreenOn=" + newScreenOn);
1378 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1379 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1380 }
1381
1382 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001383 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1385 }
1386
1387 if (oldScreenOn != newScreenOn) {
1388 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001389 // When the user presses the power button, we need to always send out the
1390 // notification that it's going to sleep so the keyguard goes on. But
1391 // we can't do that until the screen fades out, so we don't show the keyguard
1392 // too early.
1393 if (mStillNeedSleepNotification) {
1394 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 // Turn on the screen UNLESS there was a prior
1398 // preventScreenOn(true) request. (Note that the lifetime
1399 // of a single preventScreenOn() request is limited to 5
1400 // seconds to prevent a buggy app from disabling the
1401 // screen forever; see forceReenableScreen().)
1402 boolean reallyTurnScreenOn = true;
1403 if (mSpew) {
1404 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1405 + mPreventScreenOn);
1406 }
1407
1408 if (mPreventScreenOn) {
1409 if (mSpew) {
1410 Log.d(TAG, "- PREVENTING screen from really turning on!");
1411 }
1412 reallyTurnScreenOn = false;
1413 }
1414 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001415 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 long identity = Binder.clearCallingIdentity();
1417 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001418 mBatteryStats.noteScreenBrightness(
1419 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 mBatteryStats.noteScreenOn();
1421 } catch (RemoteException e) {
1422 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1423 } finally {
1424 Binder.restoreCallingIdentity(identity);
1425 }
1426 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001427 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 // But continue as if we really did turn the screen on...
1429 err = 0;
1430 }
1431
1432 mScreenOnStartTime = SystemClock.elapsedRealtime();
1433 mLastTouchDown = 0;
1434 mTotalTouchDownTime = 0;
1435 mTouchCycles = 0;
1436 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1437 mTotalTouchDownTime, mTouchCycles);
1438 if (err == 0) {
1439 mPowerState |= SCREEN_ON_BIT;
1440 sendNotificationLocked(true, -1);
1441 }
1442 } else {
1443 mScreenOffTime = SystemClock.elapsedRealtime();
1444 long identity = Binder.clearCallingIdentity();
1445 try {
1446 mBatteryStats.noteScreenOff();
1447 } catch (RemoteException e) {
1448 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1449 } finally {
1450 Binder.restoreCallingIdentity(identity);
1451 }
1452 mPowerState &= ~SCREEN_ON_BIT;
1453 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001454 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 } else {
1456 mOffBecauseOfUser = becauseOfUser;
1457 err = 0;
1458 mLastTouchDown = 0;
1459 }
1460 }
1461 }
1462 }
1463 }
1464
Joe Onorato128e7292009-03-24 18:41:31 -07001465 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 // I don't think we need to check the current state here because all of these
1467 // Power.setScreenState and sendNotificationLocked can both handle being
1468 // called multiple times in the same state. -joeo
1469 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1470 mTotalTouchDownTime, mTouchCycles);
1471 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001472 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 if (mScreenOnStartTime != 0) {
1474 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1475 mScreenOnStartTime = 0;
1476 }
1477 if (err == 0) {
1478 int why = becauseOfUser
1479 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1480 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1481 sendNotificationLocked(false, why);
1482 }
1483 return err;
1484 }
1485
1486 private boolean batteryIsLow() {
1487 return (!mIsPowered &&
1488 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1489 }
1490
The Android Open Source Project10592532009-03-18 17:39:46 -07001491 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001492 final int oldState = mPowerState;
1493 final int realDifference = (newState ^ oldState);
1494 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001496 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498
1499 int offMask = 0;
1500 int dimMask = 0;
1501 int onMask = 0;
1502
1503 int preferredBrightness = getPreferredBrightness();
1504 boolean startAnimation = false;
1505
1506 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1507 if (ANIMATE_KEYBOARD_LIGHTS) {
1508 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1509 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001510 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1511 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 } else {
1513 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001514 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1515 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 startAnimation = true;
1518 } else {
1519 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001520 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001522 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524 }
1525 }
1526
1527 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1528 if (ANIMATE_BUTTON_LIGHTS) {
1529 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1530 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001531 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1532 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 } else {
1534 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001535 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1536 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 startAnimation = true;
1539 } else {
1540 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001541 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001543 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546 }
1547
1548 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1549 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001550 int nominalCurrentValue = -1;
1551 // If there was an actual difference in the light state, then
1552 // figure out the "ideal" current value based on the previous
1553 // state. Otherwise, this is a change due to the brightness
1554 // override, so we want to animate from whatever the current
1555 // value is.
1556 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1557 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1558 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1559 nominalCurrentValue = preferredBrightness;
1560 break;
1561 case SCREEN_ON_BIT:
1562 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1563 break;
1564 case 0:
1565 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1566 break;
1567 case SCREEN_BRIGHT_BIT:
1568 default:
1569 // not possible
1570 nominalCurrentValue = (int)mScreenBrightness.curValue;
1571 break;
1572 }
Joe Onorato128e7292009-03-24 18:41:31 -07001573 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001574 int brightness = preferredBrightness;
1575 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1577 // dim or turn off backlight, depending on if the screen is on
1578 // the scale is because the brightness ramp isn't linear and this biases
1579 // it so the later parts take longer.
1580 final float scale = 1.5f;
1581 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1582 if (ratio > 1.0f) ratio = 1.0f;
1583 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1585 // was bright
1586 steps = ANIM_STEPS;
1587 } else {
1588 // was dim
1589 steps = (int)(ANIM_STEPS*ratio*scale);
1590 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001591 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 if ((oldState & SCREEN_ON_BIT) != 0) {
1594 // was bright
1595 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1596 } else {
1597 // was dim
1598 steps = (int)(ANIM_STEPS*ratio);
1599 }
1600 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1601 // If the "stay on while plugged in" option is
1602 // turned on, then the screen will often not
1603 // automatically turn off while plugged in. To
1604 // still have a sense of when it is inactive, we
1605 // will then count going dim as turning off.
1606 mScreenOffTime = SystemClock.elapsedRealtime();
1607 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001608 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001611 long identity = Binder.clearCallingIdentity();
1612 try {
1613 mBatteryStats.noteScreenBrightness(brightness);
1614 } catch (RemoteException e) {
1615 // Nothing interesting to do.
1616 } finally {
1617 Binder.restoreCallingIdentity(identity);
1618 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001619 if (mScreenBrightness.setTargetLocked(brightness,
1620 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1621 startAnimation = true;
1622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 } else {
1624 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1625 // dim or turn off backlight, depending on if the screen is on
1626 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001627 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001632 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 }
1635 }
1636
1637 if (startAnimation) {
1638 if (mSpew) {
1639 Log.i(TAG, "Scheduling light animator!");
1640 }
1641 mHandler.removeCallbacks(mLightAnimator);
1642 mHandler.post(mLightAnimator);
1643 }
1644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (offMask != 0) {
1646 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001647 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 if (dimMask != 0) {
1650 int brightness = Power.BRIGHTNESS_DIM;
1651 if ((newState & BATTERY_LOW_BIT) != 0 &&
1652 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1653 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1654 }
1655 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001656 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658 if (onMask != 0) {
1659 int brightness = getPreferredBrightness();
1660 if ((newState & BATTERY_LOW_BIT) != 0 &&
1661 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1662 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1663 }
1664 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001665 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668
The Android Open Source Project10592532009-03-18 17:39:46 -07001669 private void setLightBrightness(int mask, int value) {
1670 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1671 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1672 }
1673 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1674 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1675 }
1676 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1677 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680
1681 class BrightnessState {
1682 final int mask;
1683
1684 boolean initialized;
1685 int targetValue;
1686 float curValue;
1687 float delta;
1688 boolean animating;
1689
1690 BrightnessState(int m) {
1691 mask = m;
1692 }
1693
1694 public void dump(PrintWriter pw, String prefix) {
1695 pw.println(prefix + "animating=" + animating
1696 + " targetValue=" + targetValue
1697 + " curValue=" + curValue
1698 + " delta=" + delta);
1699 }
1700
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001701 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001702 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 if (!initialized) {
1704 initialized = true;
1705 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001706 } else if (targetValue == target) {
1707 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001710 delta = (targetValue -
1711 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1712 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001714 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001716 + " target=" + targetValue + " delta=" + delta
1717 + " nominalCurrentValue=" + nominalCurrentValue
1718 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
1720 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001721 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723
1724 boolean stepLocked() {
1725 if (!animating) return false;
1726 if (false && mSpew) {
1727 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1728 + " target=" + targetValue + " delta=" + delta);
1729 }
1730 curValue += delta;
1731 int curIntValue = (int)curValue;
1732 boolean more = true;
1733 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001734 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 more = false;
1736 } else if (delta > 0) {
1737 if (curIntValue >= targetValue) {
1738 curValue = curIntValue = targetValue;
1739 more = false;
1740 }
1741 } else {
1742 if (curIntValue <= targetValue) {
1743 curValue = curIntValue = targetValue;
1744 more = false;
1745 }
1746 }
1747 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001748 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 animating = more;
1750 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001751 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001752 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754 }
1755 return more;
1756 }
1757 }
1758
1759 private class LightAnimator implements Runnable {
1760 public void run() {
1761 synchronized (mLocks) {
1762 long now = SystemClock.uptimeMillis();
1763 boolean more = mScreenBrightness.stepLocked();
1764 if (mKeyboardBrightness.stepLocked()) {
1765 more = true;
1766 }
1767 if (mButtonBrightness.stepLocked()) {
1768 more = true;
1769 }
1770 if (more) {
1771 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1772 }
1773 }
1774 }
1775 }
1776
1777 private int getPreferredBrightness() {
1778 try {
1779 if (mScreenBrightnessOverride >= 0) {
1780 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001781 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1782 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001783 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 }
1785 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1786 SCREEN_BRIGHTNESS);
1787 // Don't let applications turn the screen all the way off
1788 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1789 } catch (SettingNotFoundException snfe) {
1790 return Power.BRIGHTNESS_ON;
1791 }
1792 }
1793
Charles Mendis322591c2009-10-29 11:06:59 -07001794 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 synchronized (mLocks) {
1796 return (mPowerState & SCREEN_ON_BIT) != 0;
1797 }
1798 }
1799
Charles Mendis322591c2009-10-29 11:06:59 -07001800 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 synchronized (mLocks) {
1802 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1803 }
1804 }
1805
Mike Lockwood200b30b2009-09-20 00:23:59 -04001806 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001807 // cancel animation so userActivity will succeed
1808 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001809 boolean savedActivityAllowed = mUserActivityAllowed;
1810 mUserActivityAllowed = true;
1811 userActivity(SystemClock.uptimeMillis(), false);
1812 mUserActivityAllowed = savedActivityAllowed;
1813 }
1814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1816 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1817 userActivity(time, noChangeLights, OTHER_EVENT, force);
1818 }
1819
1820 public void userActivity(long time, boolean noChangeLights) {
1821 userActivity(time, noChangeLights, OTHER_EVENT, false);
1822 }
1823
1824 public void userActivity(long time, boolean noChangeLights, int eventType) {
1825 userActivity(time, noChangeLights, eventType, false);
1826 }
1827
1828 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1829 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1830
1831 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001832 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001834 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 return;
1837 }
1838
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001839 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1840 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1841 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1842 if (false) {
1843 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1844 }
1845 return;
1846 }
1847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 if (false) {
1849 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1850 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1851 } else {
1852 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1853 }
1854 }
1855
1856 synchronized (mLocks) {
1857 if (mSpew) {
1858 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1859 + " mUserActivityAllowed=" + mUserActivityAllowed
1860 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001861 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1862 + " mProximitySensorActive=" + mProximitySensorActive
1863 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
Mike Lockwood05067122009-10-27 23:07:25 -04001865 // ignore user activity if we are in the process of turning off the screen
1866 if (mScreenBrightness.animating && mScreenBrightness.targetValue == 0) {
1867 Log.d(TAG, "ignoring user activity while turning off screen");
1868 return;
1869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 if (mLastEventTime <= time || force) {
1871 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001872 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001873 // Only turn on button backlights if a button was pressed
1874 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001875 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1877 } else {
1878 // don't clear button/keyboard backlights when the screen is touched.
1879 mUserState |= SCREEN_BRIGHT;
1880 }
1881
Dianne Hackborn617f8772009-03-31 15:04:46 -07001882 int uid = Binder.getCallingUid();
1883 long ident = Binder.clearCallingIdentity();
1884 try {
1885 mBatteryStats.noteUserActivity(uid, eventType);
1886 } catch (RemoteException e) {
1887 // Ignore
1888 } finally {
1889 Binder.restoreCallingIdentity(ident);
1890 }
1891
Michael Chane96440f2009-05-06 10:27:36 -07001892 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1894 setTimeoutLocked(time, SCREEN_BRIGHT);
1895 }
1896 }
1897 }
1898 }
1899
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001900 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1901 try {
1902 int i;
1903 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1904 if (sensorValue < mAutoBrightnessLevels[i]) {
1905 break;
1906 }
1907 }
1908 return values[i];
1909 } catch (Exception e) {
1910 // guard against null pointer or index out of bounds errors
1911 Log.e(TAG, "getAutoBrightnessValue", e);
1912 return 255;
1913 }
1914 }
1915
Mike Lockwood20f87d72009-11-05 16:08:51 -05001916 private Runnable mProximityTask = new Runnable() {
1917 public void run() {
1918 synchronized (mLocks) {
1919 if (mProximityPendingValue != -1) {
1920 proximityChangedLocked(mProximityPendingValue == 1);
1921 mProximityPendingValue = -1;
1922 }
1923 }
1924 }
1925 };
1926
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001927 private Runnable mAutoBrightnessTask = new Runnable() {
1928 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001929 synchronized (mLocks) {
1930 int value = (int)mLightSensorPendingValue;
1931 if (value >= 0) {
1932 mLightSensorPendingValue = -1;
1933 lightSensorChangedLocked(value);
1934 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001935 }
1936 }
1937 };
1938
1939 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001940 if (mDebugLightSensor) {
1941 Log.d(TAG, "lightSensorChangedLocked " + value);
1942 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001943
1944 if (mLightSensorValue != value) {
1945 mLightSensorValue = value;
1946 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1947 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1948 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001949 int keyboardValue;
1950 if (mKeyboardVisible) {
1951 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1952 } else {
1953 keyboardValue = 0;
1954 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001955 mLightSensorBrightness = lcdValue;
1956
1957 if (mDebugLightSensor) {
1958 Log.d(TAG, "lcdValue " + lcdValue);
1959 Log.d(TAG, "buttonValue " + buttonValue);
1960 Log.d(TAG, "keyboardValue " + keyboardValue);
1961 }
1962
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001963 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001964 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001965 if (ANIMATE_SCREEN_LIGHTS) {
1966 if (mScreenBrightness.setTargetLocked(lcdValue,
1967 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1968 (int)mScreenBrightness.curValue)) {
1969 startAnimation = true;
1970 }
1971 } else {
1972 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1973 lcdValue);
1974 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001975 }
1976 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001977 if (mButtonBrightness.setTargetLocked(buttonValue,
1978 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1979 (int)mButtonBrightness.curValue)) {
1980 startAnimation = true;
1981 }
1982 } else {
1983 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1984 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001985 }
1986 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001987 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1988 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1989 (int)mKeyboardBrightness.curValue)) {
1990 startAnimation = true;
1991 }
1992 } else {
1993 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
1994 keyboardValue);
1995 }
1996 if (startAnimation) {
1997 if (mDebugLightSensor) {
1998 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
1999 }
2000 mHandler.removeCallbacks(mLightAnimator);
2001 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002002 }
2003 }
2004 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002005 }
2006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 /**
2008 * The user requested that we go to sleep (probably with the power button).
2009 * This overrides all wake locks that are held.
2010 */
2011 public void goToSleep(long time)
2012 {
2013 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2014 synchronized (mLocks) {
2015 goToSleepLocked(time);
2016 }
2017 }
2018
2019 /**
2020 * Returns the time the screen has been on since boot, in millis.
2021 * @return screen on time
2022 */
2023 public long getScreenOnTime() {
2024 synchronized (mLocks) {
2025 if (mScreenOnStartTime == 0) {
2026 return mScreenOnTime;
2027 } else {
2028 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2029 }
2030 }
2031 }
2032
2033 private void goToSleepLocked(long time) {
2034
2035 if (mLastEventTime <= time) {
2036 mLastEventTime = time;
2037 // cancel all of the wake locks
2038 mWakeLockState = SCREEN_OFF;
2039 int N = mLocks.size();
2040 int numCleared = 0;
2041 for (int i=0; i<N; i++) {
2042 WakeLock wl = mLocks.get(i);
2043 if (isScreenLock(wl.flags)) {
2044 mLocks.get(i).activated = false;
2045 numCleared++;
2046 }
2047 }
2048 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002049 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 mUserState = SCREEN_OFF;
2051 setPowerState(SCREEN_OFF, false, true);
2052 cancelTimerLocked();
2053 }
2054 }
2055
2056 public long timeSinceScreenOn() {
2057 synchronized (mLocks) {
2058 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2059 return 0;
2060 }
2061 return SystemClock.elapsedRealtime() - mScreenOffTime;
2062 }
2063 }
2064
2065 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002066 synchronized (mLocks) {
2067 if (mSpew) {
2068 Log.d(TAG, "setKeyboardVisibility: " + visible);
2069 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002070 if (mKeyboardVisible != visible) {
2071 mKeyboardVisible = visible;
2072 // don't signal user activity if the screen is off; other code
2073 // will take care of turning on due to a true change to the lid
2074 // switch and synchronized with the lock screen.
2075 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002076 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002077 // force recompute of backlight values
2078 if (mLightSensorValue >= 0) {
2079 int value = (int)mLightSensorValue;
2080 mLightSensorValue = -1;
2081 lightSensorChangedLocked(value);
2082 }
2083 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002084 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2085 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002086 }
2087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
2090 /**
2091 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2092 */
2093 public void enableUserActivity(boolean enabled) {
2094 synchronized (mLocks) {
2095 mUserActivityAllowed = enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097 }
2098
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002099 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002100 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002101 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002102 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002103 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002104 // force recompute of backlight values
2105 if (mLightSensorValue >= 0) {
2106 int value = (int)mLightSensorValue;
2107 mLightSensorValue = -1;
2108 lightSensorChangedLocked(value);
2109 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002110 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002111 }
2112 }
2113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 /** Sets the screen off timeouts:
2115 * mKeylightDelay
2116 * mDimDelay
2117 * mScreenOffDelay
2118 * */
2119 private void setScreenOffTimeoutsLocked() {
2120 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2121 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2122 mDimDelay = -1;
2123 mScreenOffDelay = 0;
2124 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2125 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2126 mDimDelay = -1;
2127 mScreenOffDelay = 0;
2128 } else {
2129 int totalDelay = mTotalDelaySetting;
2130 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2131 if (totalDelay < 0) {
2132 mScreenOffDelay = Integer.MAX_VALUE;
2133 } else if (mKeylightDelay < totalDelay) {
2134 // subtract the time that the keylight delay. This will give us the
2135 // remainder of the time that we need to sleep to get the accurate
2136 // screen off timeout.
2137 mScreenOffDelay = totalDelay - mKeylightDelay;
2138 } else {
2139 mScreenOffDelay = 0;
2140 }
2141 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2142 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2143 mScreenOffDelay = LONG_DIM_TIME;
2144 } else {
2145 mDimDelay = -1;
2146 }
2147 }
2148 if (mSpew) {
2149 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2150 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2151 + " mDimScreen=" + mDimScreen);
2152 }
2153 }
2154
2155 /**
2156 * Refreshes cached Gservices settings. Called once on startup, and
2157 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2158 * GservicesChangedReceiver).
2159 */
2160 private void updateGservicesValues() {
2161 mShortKeylightDelay = Settings.Gservices.getInt(
2162 mContext.getContentResolver(),
2163 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2164 SHORT_KEYLIGHT_DELAY_DEFAULT);
2165 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2166 }
2167
2168 /**
2169 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2170 * which tells us we need to refresh our cached Gservices settings.
2171 */
2172 private class GservicesChangedReceiver extends BroadcastReceiver {
2173 @Override
2174 public void onReceive(Context context, Intent intent) {
2175 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2176 updateGservicesValues();
2177 }
2178 }
2179
2180 private class LockList extends ArrayList<WakeLock>
2181 {
2182 void addLock(WakeLock wl)
2183 {
2184 int index = getIndex(wl.binder);
2185 if (index < 0) {
2186 this.add(wl);
2187 }
2188 }
2189
2190 WakeLock removeLock(IBinder binder)
2191 {
2192 int index = getIndex(binder);
2193 if (index >= 0) {
2194 return this.remove(index);
2195 } else {
2196 return null;
2197 }
2198 }
2199
2200 int getIndex(IBinder binder)
2201 {
2202 int N = this.size();
2203 for (int i=0; i<N; i++) {
2204 if (this.get(i).binder == binder) {
2205 return i;
2206 }
2207 }
2208 return -1;
2209 }
2210
2211 int gatherState()
2212 {
2213 int result = 0;
2214 int N = this.size();
2215 for (int i=0; i<N; i++) {
2216 WakeLock wl = this.get(i);
2217 if (wl.activated) {
2218 if (isScreenLock(wl.flags)) {
2219 result |= wl.minState;
2220 }
2221 }
2222 }
2223 return result;
2224 }
Michael Chane96440f2009-05-06 10:27:36 -07002225
2226 int reactivateScreenLocksLocked()
2227 {
2228 int result = 0;
2229 int N = this.size();
2230 for (int i=0; i<N; i++) {
2231 WakeLock wl = this.get(i);
2232 if (isScreenLock(wl.flags)) {
2233 wl.activated = true;
2234 result |= wl.minState;
2235 }
2236 }
2237 return result;
2238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240
2241 void setPolicy(WindowManagerPolicy p) {
2242 synchronized (mLocks) {
2243 mPolicy = p;
2244 mLocks.notifyAll();
2245 }
2246 }
2247
2248 WindowManagerPolicy getPolicyLocked() {
2249 while (mPolicy == null || !mDoneBooting) {
2250 try {
2251 mLocks.wait();
2252 } catch (InterruptedException e) {
2253 // Ignore
2254 }
2255 }
2256 return mPolicy;
2257 }
2258
2259 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002260 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2261 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2262 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002263 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002264 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002265 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002266 }
2267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 synchronized (mLocks) {
2269 Log.d(TAG, "system ready!");
2270 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002271 long identity = Binder.clearCallingIdentity();
2272 try {
2273 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2274 mBatteryStats.noteScreenOn();
2275 } catch (RemoteException e) {
2276 // Nothing interesting to do.
2277 } finally {
2278 Binder.restoreCallingIdentity(identity);
2279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2281 updateWakeLockLocked();
2282 mLocks.notifyAll();
2283 }
2284 }
2285
2286 public void monitor() {
2287 synchronized (mLocks) { }
2288 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002289
2290 public int getSupportedWakeLockFlags() {
2291 int result = PowerManager.PARTIAL_WAKE_LOCK
2292 | PowerManager.FULL_WAKE_LOCK
2293 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2294
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002295 if (mProximitySensor != null) {
2296 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2297 }
2298
2299 return result;
2300 }
2301
Mike Lockwood237a2992009-09-15 14:42:16 -04002302 public void setBacklightBrightness(int brightness) {
2303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2304 // Don't let applications turn the screen all the way off
2305 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2306 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
Mike Lockwooddf024922009-10-29 21:29:15 -04002307 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2308 (mKeyboardVisible ? brightness : 0));
Mike Lockwood237a2992009-09-15 14:42:16 -04002309 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2310 long identity = Binder.clearCallingIdentity();
2311 try {
2312 mBatteryStats.noteScreenBrightness(brightness);
2313 } catch (RemoteException e) {
2314 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2315 } finally {
2316 Binder.restoreCallingIdentity(identity);
2317 }
2318
2319 // update our animation state
2320 if (ANIMATE_SCREEN_LIGHTS) {
2321 mScreenBrightness.curValue = brightness;
2322 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002323 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002324 }
2325 if (ANIMATE_KEYBOARD_LIGHTS) {
2326 mKeyboardBrightness.curValue = brightness;
2327 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002328 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002329 }
2330 if (ANIMATE_BUTTON_LIGHTS) {
2331 mButtonBrightness.curValue = brightness;
2332 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002333 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002334 }
2335 }
2336
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002337 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002338 if (mSpew) {
2339 Log.d(TAG, "enableProximityLockLocked");
2340 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002341 // clear calling identity so sensor manager battery stats are accurate
2342 long identity = Binder.clearCallingIdentity();
2343 try {
2344 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2345 SensorManager.SENSOR_DELAY_NORMAL);
2346 } finally {
2347 Binder.restoreCallingIdentity(identity);
2348 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002349 }
2350
2351 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002352 if (mSpew) {
2353 Log.d(TAG, "disableProximityLockLocked");
2354 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002355 // clear calling identity so sensor manager battery stats are accurate
2356 long identity = Binder.clearCallingIdentity();
2357 try {
2358 mSensorManager.unregisterListener(mProximityListener);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002359 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002360 } finally {
2361 Binder.restoreCallingIdentity(identity);
2362 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002363 if (mProximitySensorActive) {
2364 mProximitySensorActive = false;
2365 forceUserActivityLocked();
Mike Lockwood200b30b2009-09-20 00:23:59 -04002366 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002367 }
2368
Mike Lockwood20f87d72009-11-05 16:08:51 -05002369 private void proximityChangedLocked(boolean active) {
2370 if (mSpew) {
2371 Log.d(TAG, "proximityChangedLocked, active: " + active);
2372 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002373 if (mProximityCount <= 0) {
2374 Log.d(TAG, "Ignoring proximity change after last proximity lock is released");
2375 return;
2376 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002377 if (active) {
2378 goToSleepLocked(SystemClock.uptimeMillis());
2379 mProximitySensorActive = true;
2380 } else {
2381 // proximity sensor negative events trigger as user activity.
2382 // temporarily set mUserActivityAllowed to true so this will work
2383 // even when the keyguard is on.
2384 mProximitySensorActive = false;
2385 forceUserActivityLocked();
2386 }
2387 }
2388
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002389 private void enableLightSensor(boolean enable) {
2390 if (mDebugLightSensor) {
2391 Log.d(TAG, "enableLightSensor " + enable);
2392 }
2393 if (mSensorManager != null && mLightSensorEnabled != enable) {
2394 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002395 // clear calling identity so sensor manager battery stats are accurate
2396 long identity = Binder.clearCallingIdentity();
2397 try {
2398 if (enable) {
2399 mSensorManager.registerListener(mLightListener, mLightSensor,
2400 SensorManager.SENSOR_DELAY_NORMAL);
2401 } else {
2402 mSensorManager.unregisterListener(mLightListener);
2403 mHandler.removeCallbacks(mAutoBrightnessTask);
2404 }
2405 } finally {
2406 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002407 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002408 }
2409 }
2410
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002411 SensorEventListener mProximityListener = new SensorEventListener() {
2412 public void onSensorChanged(SensorEvent event) {
2413 long milliseconds = event.timestamp / 1000000;
2414 synchronized (mLocks) {
2415 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002416 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2417 mLastProximityEventTime = milliseconds;
2418 mHandler.removeCallbacks(mProximityTask);
2419
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002420 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002421 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2422 distance < mProximitySensor.getMaximumRange());
2423
2424 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2425 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2426 mProximityPendingValue = (active ? 1 : 0);
2427 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002428 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002429 // process the value immediately
2430 mProximityPendingValue = -1;
2431 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002432 }
2433 }
2434 }
2435
2436 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2437 // ignore
2438 }
2439 };
2440
2441 SensorEventListener mLightListener = new SensorEventListener() {
2442 public void onSensorChanged(SensorEvent event) {
2443 synchronized (mLocks) {
2444 int value = (int)event.values[0];
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002445 long milliseconds = event.timestamp / 1000000;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002446 if (mDebugLightSensor) {
2447 Log.d(TAG, "onSensorChanged: light value: " + value);
2448 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002449 mHandler.removeCallbacks(mAutoBrightnessTask);
2450 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002451 if (mLightSensorValue == -1 ||
2452 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2453 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002454 lightSensorChangedLocked(value);
2455 } else {
2456 // delay processing to debounce the sensor
2457 mLightSensorPendingValue = value;
2458 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2459 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002460 } else {
2461 mLightSensorPendingValue = -1;
2462 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002463 }
2464 }
2465
2466 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2467 // ignore
2468 }
2469 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470}