blob: 596325c2e232540ee6c4fe23632d1bf681ffa0d6 [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 {
Mike Lockwood497087e32009-11-08 18:33:03 -05001443 // cancel light sensor task
1444 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 mScreenOffTime = SystemClock.elapsedRealtime();
1446 long identity = Binder.clearCallingIdentity();
1447 try {
1448 mBatteryStats.noteScreenOff();
1449 } catch (RemoteException e) {
1450 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1451 } finally {
1452 Binder.restoreCallingIdentity(identity);
1453 }
1454 mPowerState &= ~SCREEN_ON_BIT;
1455 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001456 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 } else {
1458 mOffBecauseOfUser = becauseOfUser;
1459 err = 0;
1460 mLastTouchDown = 0;
1461 }
1462 }
1463 }
1464 }
1465 }
1466
Joe Onorato128e7292009-03-24 18:41:31 -07001467 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 // I don't think we need to check the current state here because all of these
1469 // Power.setScreenState and sendNotificationLocked can both handle being
1470 // called multiple times in the same state. -joeo
1471 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1472 mTotalTouchDownTime, mTouchCycles);
1473 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001474 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 if (mScreenOnStartTime != 0) {
1476 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1477 mScreenOnStartTime = 0;
1478 }
1479 if (err == 0) {
1480 int why = becauseOfUser
1481 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1482 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1483 sendNotificationLocked(false, why);
1484 }
1485 return err;
1486 }
1487
1488 private boolean batteryIsLow() {
1489 return (!mIsPowered &&
1490 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1491 }
1492
The Android Open Source Project10592532009-03-18 17:39:46 -07001493 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001494 final int oldState = mPowerState;
1495 final int realDifference = (newState ^ oldState);
1496 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001498 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500
1501 int offMask = 0;
1502 int dimMask = 0;
1503 int onMask = 0;
1504
1505 int preferredBrightness = getPreferredBrightness();
1506 boolean startAnimation = false;
1507
1508 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1509 if (ANIMATE_KEYBOARD_LIGHTS) {
1510 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1511 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001512 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1513 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 } else {
1515 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001516 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1517 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519 startAnimation = true;
1520 } else {
1521 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001522 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001524 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526 }
1527 }
1528
1529 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1530 if (ANIMATE_BUTTON_LIGHTS) {
1531 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1532 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001533 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1534 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 } else {
1536 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001537 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1538 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 startAnimation = true;
1541 } else {
1542 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001543 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001545 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548 }
1549
1550 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1551 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001552 int nominalCurrentValue = -1;
1553 // If there was an actual difference in the light state, then
1554 // figure out the "ideal" current value based on the previous
1555 // state. Otherwise, this is a change due to the brightness
1556 // override, so we want to animate from whatever the current
1557 // value is.
1558 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1559 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1560 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1561 nominalCurrentValue = preferredBrightness;
1562 break;
1563 case SCREEN_ON_BIT:
1564 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1565 break;
1566 case 0:
1567 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1568 break;
1569 case SCREEN_BRIGHT_BIT:
1570 default:
1571 // not possible
1572 nominalCurrentValue = (int)mScreenBrightness.curValue;
1573 break;
1574 }
Joe Onorato128e7292009-03-24 18:41:31 -07001575 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001576 int brightness = preferredBrightness;
1577 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1579 // dim or turn off backlight, depending on if the screen is on
1580 // the scale is because the brightness ramp isn't linear and this biases
1581 // it so the later parts take longer.
1582 final float scale = 1.5f;
1583 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1584 if (ratio > 1.0f) ratio = 1.0f;
1585 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1587 // was bright
1588 steps = ANIM_STEPS;
1589 } else {
1590 // was dim
1591 steps = (int)(ANIM_STEPS*ratio*scale);
1592 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001593 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if ((oldState & SCREEN_ON_BIT) != 0) {
1596 // was bright
1597 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1598 } else {
1599 // was dim
1600 steps = (int)(ANIM_STEPS*ratio);
1601 }
1602 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1603 // If the "stay on while plugged in" option is
1604 // turned on, then the screen will often not
1605 // automatically turn off while plugged in. To
1606 // still have a sense of when it is inactive, we
1607 // will then count going dim as turning off.
1608 mScreenOffTime = SystemClock.elapsedRealtime();
1609 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001610 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001613 long identity = Binder.clearCallingIdentity();
1614 try {
1615 mBatteryStats.noteScreenBrightness(brightness);
1616 } catch (RemoteException e) {
1617 // Nothing interesting to do.
1618 } finally {
1619 Binder.restoreCallingIdentity(identity);
1620 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001621 if (mScreenBrightness.setTargetLocked(brightness,
1622 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1623 startAnimation = true;
1624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 } else {
1626 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1627 // dim or turn off backlight, depending on if the screen is on
1628 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001629 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001631 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001634 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 }
1637 }
1638
1639 if (startAnimation) {
1640 if (mSpew) {
1641 Log.i(TAG, "Scheduling light animator!");
1642 }
1643 mHandler.removeCallbacks(mLightAnimator);
1644 mHandler.post(mLightAnimator);
1645 }
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (offMask != 0) {
1648 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001649 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 if (dimMask != 0) {
1652 int brightness = Power.BRIGHTNESS_DIM;
1653 if ((newState & BATTERY_LOW_BIT) != 0 &&
1654 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1655 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1656 }
1657 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001658 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 if (onMask != 0) {
1661 int brightness = getPreferredBrightness();
1662 if ((newState & BATTERY_LOW_BIT) != 0 &&
1663 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1664 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1665 }
1666 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001667 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670
The Android Open Source Project10592532009-03-18 17:39:46 -07001671 private void setLightBrightness(int mask, int value) {
1672 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1673 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1674 }
1675 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1676 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1677 }
1678 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1679 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
1683 class BrightnessState {
1684 final int mask;
1685
1686 boolean initialized;
1687 int targetValue;
1688 float curValue;
1689 float delta;
1690 boolean animating;
1691
1692 BrightnessState(int m) {
1693 mask = m;
1694 }
1695
1696 public void dump(PrintWriter pw, String prefix) {
1697 pw.println(prefix + "animating=" + animating
1698 + " targetValue=" + targetValue
1699 + " curValue=" + curValue
1700 + " delta=" + delta);
1701 }
1702
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001703 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001704 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 if (!initialized) {
1706 initialized = true;
1707 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001708 } else if (targetValue == target) {
1709 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001712 delta = (targetValue -
1713 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1714 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001716 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001718 + " target=" + targetValue + " delta=" + delta
1719 + " nominalCurrentValue=" + nominalCurrentValue
1720 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001723 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
1725
1726 boolean stepLocked() {
1727 if (!animating) return false;
1728 if (false && mSpew) {
1729 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1730 + " target=" + targetValue + " delta=" + delta);
1731 }
1732 curValue += delta;
1733 int curIntValue = (int)curValue;
1734 boolean more = true;
1735 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001736 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 more = false;
1738 } else if (delta > 0) {
1739 if (curIntValue >= targetValue) {
1740 curValue = curIntValue = targetValue;
1741 more = false;
1742 }
1743 } else {
1744 if (curIntValue <= targetValue) {
1745 curValue = curIntValue = targetValue;
1746 more = false;
1747 }
1748 }
1749 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001750 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 animating = more;
1752 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001753 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001754 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756 }
1757 return more;
1758 }
1759 }
1760
1761 private class LightAnimator implements Runnable {
1762 public void run() {
1763 synchronized (mLocks) {
1764 long now = SystemClock.uptimeMillis();
1765 boolean more = mScreenBrightness.stepLocked();
1766 if (mKeyboardBrightness.stepLocked()) {
1767 more = true;
1768 }
1769 if (mButtonBrightness.stepLocked()) {
1770 more = true;
1771 }
1772 if (more) {
1773 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1774 }
1775 }
1776 }
1777 }
1778
1779 private int getPreferredBrightness() {
1780 try {
1781 if (mScreenBrightnessOverride >= 0) {
1782 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001783 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1784 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001785 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1788 SCREEN_BRIGHTNESS);
1789 // Don't let applications turn the screen all the way off
1790 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1791 } catch (SettingNotFoundException snfe) {
1792 return Power.BRIGHTNESS_ON;
1793 }
1794 }
1795
Charles Mendis322591c2009-10-29 11:06:59 -07001796 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 synchronized (mLocks) {
1798 return (mPowerState & SCREEN_ON_BIT) != 0;
1799 }
1800 }
1801
Charles Mendis322591c2009-10-29 11:06:59 -07001802 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 synchronized (mLocks) {
1804 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1805 }
1806 }
1807
Mike Lockwood497087e32009-11-08 18:33:03 -05001808 private boolean isScreenTurningOffLocked() {
1809 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1810 }
1811
Mike Lockwood200b30b2009-09-20 00:23:59 -04001812 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001813 // cancel animation so userActivity will succeed
1814 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001815 boolean savedActivityAllowed = mUserActivityAllowed;
1816 mUserActivityAllowed = true;
1817 userActivity(SystemClock.uptimeMillis(), false);
1818 mUserActivityAllowed = savedActivityAllowed;
1819 }
1820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1823 userActivity(time, noChangeLights, OTHER_EVENT, force);
1824 }
1825
1826 public void userActivity(long time, boolean noChangeLights) {
1827 userActivity(time, noChangeLights, OTHER_EVENT, false);
1828 }
1829
1830 public void userActivity(long time, boolean noChangeLights, int eventType) {
1831 userActivity(time, noChangeLights, eventType, false);
1832 }
1833
1834 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1835 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1836
1837 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001838 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001840 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842 return;
1843 }
1844
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001845 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1846 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1847 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1848 if (false) {
1849 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1850 }
1851 return;
1852 }
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if (false) {
1855 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1856 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1857 } else {
1858 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1859 }
1860 }
1861
1862 synchronized (mLocks) {
1863 if (mSpew) {
1864 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1865 + " mUserActivityAllowed=" + mUserActivityAllowed
1866 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001867 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1868 + " mProximitySensorActive=" + mProximitySensorActive
1869 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
Mike Lockwood05067122009-10-27 23:07:25 -04001871 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001872 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001873 Log.d(TAG, "ignoring user activity while turning off screen");
1874 return;
1875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 if (mLastEventTime <= time || force) {
1877 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001878 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001879 // Only turn on button backlights if a button was pressed
1880 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001881 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1883 } else {
1884 // don't clear button/keyboard backlights when the screen is touched.
1885 mUserState |= SCREEN_BRIGHT;
1886 }
1887
Dianne Hackborn617f8772009-03-31 15:04:46 -07001888 int uid = Binder.getCallingUid();
1889 long ident = Binder.clearCallingIdentity();
1890 try {
1891 mBatteryStats.noteUserActivity(uid, eventType);
1892 } catch (RemoteException e) {
1893 // Ignore
1894 } finally {
1895 Binder.restoreCallingIdentity(ident);
1896 }
1897
Michael Chane96440f2009-05-06 10:27:36 -07001898 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1900 setTimeoutLocked(time, SCREEN_BRIGHT);
1901 }
1902 }
1903 }
1904 }
1905
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001906 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1907 try {
1908 int i;
1909 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1910 if (sensorValue < mAutoBrightnessLevels[i]) {
1911 break;
1912 }
1913 }
1914 return values[i];
1915 } catch (Exception e) {
1916 // guard against null pointer or index out of bounds errors
1917 Log.e(TAG, "getAutoBrightnessValue", e);
1918 return 255;
1919 }
1920 }
1921
Mike Lockwood20f87d72009-11-05 16:08:51 -05001922 private Runnable mProximityTask = new Runnable() {
1923 public void run() {
1924 synchronized (mLocks) {
1925 if (mProximityPendingValue != -1) {
1926 proximityChangedLocked(mProximityPendingValue == 1);
1927 mProximityPendingValue = -1;
1928 }
1929 }
1930 }
1931 };
1932
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001933 private Runnable mAutoBrightnessTask = new Runnable() {
1934 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001935 synchronized (mLocks) {
1936 int value = (int)mLightSensorPendingValue;
1937 if (value >= 0) {
1938 mLightSensorPendingValue = -1;
1939 lightSensorChangedLocked(value);
1940 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001941 }
1942 }
1943 };
1944
1945 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001946 if (mDebugLightSensor) {
1947 Log.d(TAG, "lightSensorChangedLocked " + value);
1948 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001949
1950 if (mLightSensorValue != value) {
1951 mLightSensorValue = value;
1952 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1953 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1954 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001955 int keyboardValue;
1956 if (mKeyboardVisible) {
1957 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1958 } else {
1959 keyboardValue = 0;
1960 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001961 mLightSensorBrightness = lcdValue;
1962
1963 if (mDebugLightSensor) {
1964 Log.d(TAG, "lcdValue " + lcdValue);
1965 Log.d(TAG, "buttonValue " + buttonValue);
1966 Log.d(TAG, "keyboardValue " + keyboardValue);
1967 }
1968
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001969 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001970 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001971 if (ANIMATE_SCREEN_LIGHTS) {
1972 if (mScreenBrightness.setTargetLocked(lcdValue,
1973 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1974 (int)mScreenBrightness.curValue)) {
1975 startAnimation = true;
1976 }
1977 } else {
1978 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1979 lcdValue);
1980 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001981 }
1982 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001983 if (mButtonBrightness.setTargetLocked(buttonValue,
1984 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1985 (int)mButtonBrightness.curValue)) {
1986 startAnimation = true;
1987 }
1988 } else {
1989 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
1990 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001991 }
1992 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001993 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
1994 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1995 (int)mKeyboardBrightness.curValue)) {
1996 startAnimation = true;
1997 }
1998 } else {
1999 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2000 keyboardValue);
2001 }
2002 if (startAnimation) {
2003 if (mDebugLightSensor) {
2004 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2005 }
2006 mHandler.removeCallbacks(mLightAnimator);
2007 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002008 }
2009 }
2010 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002011 }
2012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 /**
2014 * The user requested that we go to sleep (probably with the power button).
2015 * This overrides all wake locks that are held.
2016 */
2017 public void goToSleep(long time)
2018 {
2019 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2020 synchronized (mLocks) {
2021 goToSleepLocked(time);
2022 }
2023 }
2024
2025 /**
2026 * Returns the time the screen has been on since boot, in millis.
2027 * @return screen on time
2028 */
2029 public long getScreenOnTime() {
2030 synchronized (mLocks) {
2031 if (mScreenOnStartTime == 0) {
2032 return mScreenOnTime;
2033 } else {
2034 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2035 }
2036 }
2037 }
2038
2039 private void goToSleepLocked(long time) {
2040
2041 if (mLastEventTime <= time) {
2042 mLastEventTime = time;
2043 // cancel all of the wake locks
2044 mWakeLockState = SCREEN_OFF;
2045 int N = mLocks.size();
2046 int numCleared = 0;
2047 for (int i=0; i<N; i++) {
2048 WakeLock wl = mLocks.get(i);
2049 if (isScreenLock(wl.flags)) {
2050 mLocks.get(i).activated = false;
2051 numCleared++;
2052 }
2053 }
2054 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002055 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 mUserState = SCREEN_OFF;
2057 setPowerState(SCREEN_OFF, false, true);
2058 cancelTimerLocked();
2059 }
2060 }
2061
2062 public long timeSinceScreenOn() {
2063 synchronized (mLocks) {
2064 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2065 return 0;
2066 }
2067 return SystemClock.elapsedRealtime() - mScreenOffTime;
2068 }
2069 }
2070
2071 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002072 synchronized (mLocks) {
2073 if (mSpew) {
2074 Log.d(TAG, "setKeyboardVisibility: " + visible);
2075 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002076 if (mKeyboardVisible != visible) {
2077 mKeyboardVisible = visible;
2078 // don't signal user activity if the screen is off; other code
2079 // will take care of turning on due to a true change to the lid
2080 // switch and synchronized with the lock screen.
2081 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002082 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002083 // force recompute of backlight values
2084 if (mLightSensorValue >= 0) {
2085 int value = (int)mLightSensorValue;
2086 mLightSensorValue = -1;
2087 lightSensorChangedLocked(value);
2088 }
2089 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002090 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2091 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002092 }
2093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095
2096 /**
2097 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2098 */
2099 public void enableUserActivity(boolean enabled) {
2100 synchronized (mLocks) {
2101 mUserActivityAllowed = enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103 }
2104
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002105 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002106 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002107 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002108 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002109 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002110 // force recompute of backlight values
2111 if (mLightSensorValue >= 0) {
2112 int value = (int)mLightSensorValue;
2113 mLightSensorValue = -1;
2114 lightSensorChangedLocked(value);
2115 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002116 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002117 }
2118 }
2119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 /** Sets the screen off timeouts:
2121 * mKeylightDelay
2122 * mDimDelay
2123 * mScreenOffDelay
2124 * */
2125 private void setScreenOffTimeoutsLocked() {
2126 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2127 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2128 mDimDelay = -1;
2129 mScreenOffDelay = 0;
2130 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2131 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2132 mDimDelay = -1;
2133 mScreenOffDelay = 0;
2134 } else {
2135 int totalDelay = mTotalDelaySetting;
2136 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2137 if (totalDelay < 0) {
2138 mScreenOffDelay = Integer.MAX_VALUE;
2139 } else if (mKeylightDelay < totalDelay) {
2140 // subtract the time that the keylight delay. This will give us the
2141 // remainder of the time that we need to sleep to get the accurate
2142 // screen off timeout.
2143 mScreenOffDelay = totalDelay - mKeylightDelay;
2144 } else {
2145 mScreenOffDelay = 0;
2146 }
2147 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2148 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2149 mScreenOffDelay = LONG_DIM_TIME;
2150 } else {
2151 mDimDelay = -1;
2152 }
2153 }
2154 if (mSpew) {
2155 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2156 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2157 + " mDimScreen=" + mDimScreen);
2158 }
2159 }
2160
2161 /**
2162 * Refreshes cached Gservices settings. Called once on startup, and
2163 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2164 * GservicesChangedReceiver).
2165 */
2166 private void updateGservicesValues() {
2167 mShortKeylightDelay = Settings.Gservices.getInt(
2168 mContext.getContentResolver(),
2169 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2170 SHORT_KEYLIGHT_DELAY_DEFAULT);
2171 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2172 }
2173
2174 /**
2175 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2176 * which tells us we need to refresh our cached Gservices settings.
2177 */
2178 private class GservicesChangedReceiver extends BroadcastReceiver {
2179 @Override
2180 public void onReceive(Context context, Intent intent) {
2181 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2182 updateGservicesValues();
2183 }
2184 }
2185
2186 private class LockList extends ArrayList<WakeLock>
2187 {
2188 void addLock(WakeLock wl)
2189 {
2190 int index = getIndex(wl.binder);
2191 if (index < 0) {
2192 this.add(wl);
2193 }
2194 }
2195
2196 WakeLock removeLock(IBinder binder)
2197 {
2198 int index = getIndex(binder);
2199 if (index >= 0) {
2200 return this.remove(index);
2201 } else {
2202 return null;
2203 }
2204 }
2205
2206 int getIndex(IBinder binder)
2207 {
2208 int N = this.size();
2209 for (int i=0; i<N; i++) {
2210 if (this.get(i).binder == binder) {
2211 return i;
2212 }
2213 }
2214 return -1;
2215 }
2216
2217 int gatherState()
2218 {
2219 int result = 0;
2220 int N = this.size();
2221 for (int i=0; i<N; i++) {
2222 WakeLock wl = this.get(i);
2223 if (wl.activated) {
2224 if (isScreenLock(wl.flags)) {
2225 result |= wl.minState;
2226 }
2227 }
2228 }
2229 return result;
2230 }
Michael Chane96440f2009-05-06 10:27:36 -07002231
2232 int reactivateScreenLocksLocked()
2233 {
2234 int result = 0;
2235 int N = this.size();
2236 for (int i=0; i<N; i++) {
2237 WakeLock wl = this.get(i);
2238 if (isScreenLock(wl.flags)) {
2239 wl.activated = true;
2240 result |= wl.minState;
2241 }
2242 }
2243 return result;
2244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246
2247 void setPolicy(WindowManagerPolicy p) {
2248 synchronized (mLocks) {
2249 mPolicy = p;
2250 mLocks.notifyAll();
2251 }
2252 }
2253
2254 WindowManagerPolicy getPolicyLocked() {
2255 while (mPolicy == null || !mDoneBooting) {
2256 try {
2257 mLocks.wait();
2258 } catch (InterruptedException e) {
2259 // Ignore
2260 }
2261 }
2262 return mPolicy;
2263 }
2264
2265 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002266 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2267 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2268 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002269 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002270 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002271 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002272 }
2273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 synchronized (mLocks) {
2275 Log.d(TAG, "system ready!");
2276 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002277 long identity = Binder.clearCallingIdentity();
2278 try {
2279 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2280 mBatteryStats.noteScreenOn();
2281 } catch (RemoteException e) {
2282 // Nothing interesting to do.
2283 } finally {
2284 Binder.restoreCallingIdentity(identity);
2285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2287 updateWakeLockLocked();
2288 mLocks.notifyAll();
2289 }
2290 }
2291
2292 public void monitor() {
2293 synchronized (mLocks) { }
2294 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002295
2296 public int getSupportedWakeLockFlags() {
2297 int result = PowerManager.PARTIAL_WAKE_LOCK
2298 | PowerManager.FULL_WAKE_LOCK
2299 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2300
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002301 if (mProximitySensor != null) {
2302 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2303 }
2304
2305 return result;
2306 }
2307
Mike Lockwood237a2992009-09-15 14:42:16 -04002308 public void setBacklightBrightness(int brightness) {
2309 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2310 // Don't let applications turn the screen all the way off
2311 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2312 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
Mike Lockwooddf024922009-10-29 21:29:15 -04002313 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2314 (mKeyboardVisible ? brightness : 0));
Mike Lockwood237a2992009-09-15 14:42:16 -04002315 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2316 long identity = Binder.clearCallingIdentity();
2317 try {
2318 mBatteryStats.noteScreenBrightness(brightness);
2319 } catch (RemoteException e) {
2320 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2321 } finally {
2322 Binder.restoreCallingIdentity(identity);
2323 }
2324
2325 // update our animation state
2326 if (ANIMATE_SCREEN_LIGHTS) {
2327 mScreenBrightness.curValue = brightness;
2328 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002329 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002330 }
2331 if (ANIMATE_KEYBOARD_LIGHTS) {
2332 mKeyboardBrightness.curValue = brightness;
2333 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002334 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002335 }
2336 if (ANIMATE_BUTTON_LIGHTS) {
2337 mButtonBrightness.curValue = brightness;
2338 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002339 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002340 }
2341 }
2342
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002343 private void enableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002344 if (mSpew) {
2345 Log.d(TAG, "enableProximityLockLocked");
2346 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002347 // clear calling identity so sensor manager battery stats are accurate
2348 long identity = Binder.clearCallingIdentity();
2349 try {
2350 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2351 SensorManager.SENSOR_DELAY_NORMAL);
2352 } finally {
2353 Binder.restoreCallingIdentity(identity);
2354 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002355 }
2356
2357 private void disableProximityLockLocked() {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002358 if (mSpew) {
2359 Log.d(TAG, "disableProximityLockLocked");
2360 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002361 // clear calling identity so sensor manager battery stats are accurate
2362 long identity = Binder.clearCallingIdentity();
2363 try {
2364 mSensorManager.unregisterListener(mProximityListener);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002365 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002366 } finally {
2367 Binder.restoreCallingIdentity(identity);
2368 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002369 if (mProximitySensorActive) {
2370 mProximitySensorActive = false;
2371 forceUserActivityLocked();
Mike Lockwood200b30b2009-09-20 00:23:59 -04002372 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002373 }
2374
Mike Lockwood20f87d72009-11-05 16:08:51 -05002375 private void proximityChangedLocked(boolean active) {
2376 if (mSpew) {
2377 Log.d(TAG, "proximityChangedLocked, active: " + active);
2378 }
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002379 if (mProximityCount <= 0) {
2380 Log.d(TAG, "Ignoring proximity change after last proximity lock is released");
2381 return;
2382 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002383 if (active) {
2384 goToSleepLocked(SystemClock.uptimeMillis());
2385 mProximitySensorActive = true;
2386 } else {
2387 // proximity sensor negative events trigger as user activity.
2388 // temporarily set mUserActivityAllowed to true so this will work
2389 // even when the keyguard is on.
2390 mProximitySensorActive = false;
2391 forceUserActivityLocked();
2392 }
2393 }
2394
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002395 private void enableLightSensor(boolean enable) {
2396 if (mDebugLightSensor) {
2397 Log.d(TAG, "enableLightSensor " + enable);
2398 }
2399 if (mSensorManager != null && mLightSensorEnabled != enable) {
2400 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002401 // clear calling identity so sensor manager battery stats are accurate
2402 long identity = Binder.clearCallingIdentity();
2403 try {
2404 if (enable) {
2405 mSensorManager.registerListener(mLightListener, mLightSensor,
2406 SensorManager.SENSOR_DELAY_NORMAL);
2407 } else {
2408 mSensorManager.unregisterListener(mLightListener);
2409 mHandler.removeCallbacks(mAutoBrightnessTask);
2410 }
2411 } finally {
2412 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002413 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002414 }
2415 }
2416
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002417 SensorEventListener mProximityListener = new SensorEventListener() {
2418 public void onSensorChanged(SensorEvent event) {
2419 long milliseconds = event.timestamp / 1000000;
2420 synchronized (mLocks) {
2421 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002422 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2423 mLastProximityEventTime = milliseconds;
2424 mHandler.removeCallbacks(mProximityTask);
2425
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002426 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002427 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2428 distance < mProximitySensor.getMaximumRange());
2429
2430 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2431 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2432 mProximityPendingValue = (active ? 1 : 0);
2433 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002434 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002435 // process the value immediately
2436 mProximityPendingValue = -1;
2437 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002438 }
2439 }
2440 }
2441
2442 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2443 // ignore
2444 }
2445 };
2446
2447 SensorEventListener mLightListener = new SensorEventListener() {
2448 public void onSensorChanged(SensorEvent event) {
2449 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002450 // ignore light sensor while screen is turning off
2451 if (isScreenTurningOffLocked()) {
2452 return;
2453 }
2454
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002455 int value = (int)event.values[0];
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002456 long milliseconds = event.timestamp / 1000000;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002457 if (mDebugLightSensor) {
2458 Log.d(TAG, "onSensorChanged: light value: " + value);
2459 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002460 mHandler.removeCallbacks(mAutoBrightnessTask);
2461 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002462 if (mLightSensorValue == -1 ||
2463 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2464 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002465 lightSensorChangedLocked(value);
2466 } else {
2467 // delay processing to debounce the sensor
2468 mLightSensorPendingValue = value;
2469 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2470 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002471 } else {
2472 mLightSensorPendingValue = -1;
2473 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002474 }
2475 }
2476
2477 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2478 // ignore
2479 }
2480 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481}