blob: dd4a630a828f248a32e57b7a7006e3c3fb613e66 [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;
161 private int mPowerState;
162 private boolean mOffBecauseOfUser;
163 private int mUserState;
164 private boolean mKeyboardVisible = false;
165 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500166 private int mProximityWakeLockCount = 0;
167 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700168 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500169 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
170 private long mLastProximityEventTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 private int mTotalDelaySetting;
172 private int mKeylightDelay;
173 private int mDimDelay;
174 private int mScreenOffDelay;
175 private int mWakeLockState;
176 private long mLastEventTime = 0;
177 private long mScreenOffTime;
178 private volatile WindowManagerPolicy mPolicy;
179 private final LockList mLocks = new LockList();
180 private Intent mScreenOffIntent;
181 private Intent mScreenOnIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 private HardwareService mHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private Context mContext;
184 private UnsynchronizedWakeLock mBroadcastWakeLock;
185 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
186 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
187 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
188 private HandlerThread mHandlerThread;
189 private Handler mHandler;
190 private TimeoutTask mTimeoutTask = new TimeoutTask();
191 private LightAnimator mLightAnimator = new LightAnimator();
192 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700193 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700195 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700197 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700198 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 private boolean mIsPowered = false;
200 private IActivityManager mActivityService;
201 private IBatteryStats mBatteryStats;
202 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700203 private SensorManager mSensorManager;
204 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400205 private Sensor mLightSensor;
206 private boolean mLightSensorEnabled;
207 private float mLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700208 private float mLightSensorPendingValue = -1;
209 private int mLightSensorBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private boolean mDimScreen = true;
211 private long mNextTimeout;
212 private volatile int mPokey = 0;
213 private volatile boolean mPokeAwakeOnSet = false;
214 private volatile boolean mInitComplete = false;
215 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500216 // mScreenOnTime and mScreenOnStartTime are used for computing total time screen
217 // has been on since boot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 private long mScreenOnTime;
219 private long mScreenOnStartTime;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500220 // mLastScreenOnTime is the time the screen was last turned on
221 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private boolean mPreventScreenOn;
223 private int mScreenBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400224 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700225 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700226 private int[] mAutoBrightnessLevels;
227 private int[] mLcdBacklightValues;
228 private int[] mButtonBacklightValues;
229 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500230 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 // Used when logging number and duration of touch-down cycles
233 private long mTotalTouchDownTime;
234 private long mLastTouchDown;
235 private int mTouchCycles;
236
237 // could be either static or controllable at runtime
238 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500239 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400240 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 /*
243 static PrintStream mLog;
244 static {
245 try {
246 mLog = new PrintStream("/data/power.log");
247 }
248 catch (FileNotFoundException e) {
249 android.util.Log.e(TAG, "Life is hard", e);
250 }
251 }
252 static class Log {
253 static void d(String tag, String s) {
254 mLog.println(s);
255 android.util.Log.d(tag, s);
256 }
257 static void i(String tag, String s) {
258 mLog.println(s);
259 android.util.Log.i(tag, s);
260 }
261 static void w(String tag, String s) {
262 mLog.println(s);
263 android.util.Log.w(tag, s);
264 }
265 static void e(String tag, String s) {
266 mLog.println(s);
267 android.util.Log.e(tag, s);
268 }
269 }
270 */
271
272 /**
273 * This class works around a deadlock between the lock in PowerManager.WakeLock
274 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
275 * mToken object so it can be accessed from any thread, but it calls into here
276 * with its lock held. This class is essentially a reimplementation of
277 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
278 * only call it with our own locks held.
279 */
280 private class UnsynchronizedWakeLock {
281 int mFlags;
282 String mTag;
283 IBinder mToken;
284 int mCount = 0;
285 boolean mRefCounted;
286
287 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
288 mFlags = flags;
289 mTag = tag;
290 mToken = new Binder();
291 mRefCounted = refCounted;
292 }
293
294 public void acquire() {
295 if (!mRefCounted || mCount++ == 0) {
296 long ident = Binder.clearCallingIdentity();
297 try {
298 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
299 MY_UID, mTag);
300 } finally {
301 Binder.restoreCallingIdentity(ident);
302 }
303 }
304 }
305
306 public void release() {
307 if (!mRefCounted || --mCount == 0) {
308 PowerManagerService.this.releaseWakeLockLocked(mToken, false);
309 }
310 if (mCount < 0) {
311 throw new RuntimeException("WakeLock under-locked " + mTag);
312 }
313 }
314
315 public String toString() {
316 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
317 + " mCount=" + mCount + ")";
318 }
319 }
320
321 private final class BatteryReceiver extends BroadcastReceiver {
322 @Override
323 public void onReceive(Context context, Intent intent) {
324 synchronized (mLocks) {
325 boolean wasPowered = mIsPowered;
326 mIsPowered = mBatteryService.isPowered();
327
328 if (mIsPowered != wasPowered) {
329 // update mStayOnWhilePluggedIn wake lock
330 updateWakeLockLocked();
331
332 // treat plugging and unplugging the devices as a user activity.
333 // users find it disconcerting when they unplug the device
334 // and it shuts off right away.
335 // temporarily set mUserActivityAllowed to true so this will work
336 // even when the keyguard is on.
337 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400338 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340 }
341 }
342 }
343 }
344
345 /**
346 * Set the setting that determines whether the device stays on when plugged in.
347 * The argument is a bit string, with each bit specifying a power source that,
348 * when the device is connected to that source, causes the device to stay on.
349 * See {@link android.os.BatteryManager} for the list of power sources that
350 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
351 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
352 * @param val an {@code int} containing the bits that specify which power sources
353 * should cause the device to stay on.
354 */
355 public void setStayOnSetting(int val) {
356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
357 Settings.System.putInt(mContext.getContentResolver(),
358 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
359 }
360
361 private class SettingsObserver implements Observer {
362 private int getInt(String name) {
363 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
364 }
365
366 public void update(Observable o, Object arg) {
367 synchronized (mLocks) {
368 // STAY_ON_WHILE_PLUGGED_IN
369 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
370 updateWakeLockLocked();
371
372 // SCREEN_OFF_TIMEOUT
373 mTotalDelaySetting = getInt(SCREEN_OFF_TIMEOUT);
374
375 // DIM_SCREEN
376 //mDimScreen = getInt(DIM_SCREEN) != 0;
377
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700378 // SCREEN_BRIGHTNESS_MODE
379 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 // recalculate everything
382 setScreenOffTimeoutsLocked();
383 }
384 }
385 }
386
387 PowerManagerService()
388 {
389 // Hack to get our uid... should have a func for this.
390 long token = Binder.clearCallingIdentity();
391 MY_UID = Binder.getCallingUid();
392 Binder.restoreCallingIdentity(token);
393
394 // XXX remove this when the kernel doesn't timeout wake locks
395 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
396
397 // assume nothing is on yet
398 mUserState = mPowerState = 0;
399
400 // Add ourself to the Watchdog monitors.
401 Watchdog.getInstance().addMonitor(this);
402 mScreenOnStartTime = SystemClock.elapsedRealtime();
403 }
404
405 private ContentQueryMap mSettings;
406
The Android Open Source Project10592532009-03-18 17:39:46 -0700407 void init(Context context, HardwareService hardware, IActivityManager activity,
408 BatteryService battery) {
409 mHardware = hardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 mContext = context;
411 mActivityService = activity;
412 mBatteryStats = BatteryStatsService.getService();
413 mBatteryService = battery;
414
415 mHandlerThread = new HandlerThread("PowerManagerService") {
416 @Override
417 protected void onLooperPrepared() {
418 super.onLooperPrepared();
419 initInThread();
420 }
421 };
422 mHandlerThread.start();
423
424 synchronized (mHandlerThread) {
425 while (!mInitComplete) {
426 try {
427 mHandlerThread.wait();
428 } catch (InterruptedException e) {
429 // Ignore
430 }
431 }
432 }
433 }
434
435 void initInThread() {
436 mHandler = new Handler();
437
438 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700439 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
441 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
442 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
443 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
444 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
445 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
446
447 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
448 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
449 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
450 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
451
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700452 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400453
454 // read settings for auto-brightness
455 mUseSoftwareAutoBrightness = resources.getBoolean(
456 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400457 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700458 mAutoBrightnessLevels = resources.getIntArray(
459 com.android.internal.R.array.config_autoBrightnessLevels);
460 mLcdBacklightValues = resources.getIntArray(
461 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
462 mButtonBacklightValues = resources.getIntArray(
463 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
464 mKeyboardBacklightValues = resources.getIntArray(
465 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500466 mLightSensorWarmupTime = resources.getInteger(
467 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700468 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700469
470 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
472 "(" + Settings.System.NAME + "=?) or ("
473 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700474 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700476 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
477 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 null);
479 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
480 SettingsObserver settingsObserver = new SettingsObserver();
481 mSettings.addObserver(settingsObserver);
482
483 // pretend that the settings changed so we will get their initial state
484 settingsObserver.update(mSettings, null);
485
486 // register for the battery changed notifications
487 IntentFilter filter = new IntentFilter();
488 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
489 mContext.registerReceiver(new BatteryReceiver(), filter);
490
491 // Listen for Gservices changes
492 IntentFilter gservicesChangedFilter =
493 new IntentFilter(Settings.Gservices.CHANGED_ACTION);
494 mContext.registerReceiver(new GservicesChangedReceiver(), gservicesChangedFilter);
495 // And explicitly do the initial update of our cached settings
496 updateGservicesValues();
497
Mike Lockwood4984e732009-11-01 08:16:33 -0500498 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400499 // turn the screen on
500 setPowerState(SCREEN_BRIGHT);
501 } else {
502 // turn everything on
503 setPowerState(ALL_BRIGHT);
504 }
Dan Murphy951764b2009-08-27 14:59:03 -0500505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 synchronized (mHandlerThread) {
507 mInitComplete = true;
508 mHandlerThread.notifyAll();
509 }
510 }
511
512 private class WakeLock implements IBinder.DeathRecipient
513 {
514 WakeLock(int f, IBinder b, String t, int u) {
515 super();
516 flags = f;
517 binder = b;
518 tag = t;
519 uid = u == MY_UID ? Process.SYSTEM_UID : u;
520 if (u != MY_UID || (
521 !"KEEP_SCREEN_ON_FLAG".equals(tag)
522 && !"KeyInputQueue".equals(tag))) {
523 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
524 ? BatteryStats.WAKE_TYPE_PARTIAL
525 : BatteryStats.WAKE_TYPE_FULL;
526 } else {
527 monitorType = -1;
528 }
529 try {
530 b.linkToDeath(this, 0);
531 } catch (RemoteException e) {
532 binderDied();
533 }
534 }
535 public void binderDied() {
536 synchronized (mLocks) {
537 releaseWakeLockLocked(this.binder, true);
538 }
539 }
540 final int flags;
541 final IBinder binder;
542 final String tag;
543 final int uid;
544 final int monitorType;
545 boolean activated = true;
546 int minState;
547 }
548
549 private void updateWakeLockLocked() {
550 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
551 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
552 mStayOnWhilePluggedInScreenDimLock.acquire();
553 mStayOnWhilePluggedInPartialLock.acquire();
554 } else {
555 mStayOnWhilePluggedInScreenDimLock.release();
556 mStayOnWhilePluggedInPartialLock.release();
557 }
558 }
559
560 private boolean isScreenLock(int flags)
561 {
562 int n = flags & LOCK_MASK;
563 return n == PowerManager.FULL_WAKE_LOCK
564 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
565 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
566 }
567
568 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700570 if (uid != Process.myUid()) {
571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 long ident = Binder.clearCallingIdentity();
574 try {
575 synchronized (mLocks) {
576 acquireWakeLockLocked(flags, lock, uid, tag);
577 }
578 } finally {
579 Binder.restoreCallingIdentity(ident);
580 }
581 }
582
583 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
584 int acquireUid = -1;
585 String acquireName = null;
586 int acquireType = -1;
587
588 if (mSpew) {
589 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
590 }
591
592 int index = mLocks.getIndex(lock);
593 WakeLock wl;
594 boolean newlock;
595 if (index < 0) {
596 wl = new WakeLock(flags, lock, tag, uid);
597 switch (wl.flags & LOCK_MASK)
598 {
599 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500600 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400601 wl.minState = SCREEN_BRIGHT;
602 } else {
603 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 break;
606 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
607 wl.minState = SCREEN_BRIGHT;
608 break;
609 case PowerManager.SCREEN_DIM_WAKE_LOCK:
610 wl.minState = SCREEN_DIM;
611 break;
612 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700613 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 break;
615 default:
616 // just log and bail. we're in the server, so don't
617 // throw an exception.
618 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
619 + " flags=" + flags);
620 return;
621 }
622 mLocks.addLock(wl);
623 newlock = true;
624 } else {
625 wl = mLocks.get(index);
626 newlock = false;
627 }
628 if (isScreenLock(flags)) {
629 // if this causes a wakeup, we reactivate all of the locks and
630 // set it to whatever they want. otherwise, we modulate that
631 // by the current state so we never turn it more on than
632 // it already is.
633 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700634 int oldWakeLockState = mWakeLockState;
635 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 if (mSpew) {
637 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700638 + " mWakeLockState=0x"
639 + Integer.toHexString(mWakeLockState)
640 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 } else {
643 if (mSpew) {
644 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
645 + " mLocks.gatherState()=0x"
646 + Integer.toHexString(mLocks.gatherState())
647 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
648 }
649 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
650 }
651 setPowerState(mWakeLockState | mUserState);
652 }
653 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
654 if (newlock) {
655 mPartialCount++;
656 if (mPartialCount == 1) {
657 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 1, tag);
658 }
659 }
660 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700661 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500662 mProximityWakeLockCount++;
663 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700664 enableProximityLockLocked();
665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667 if (newlock) {
668 acquireUid = wl.uid;
669 acquireName = wl.tag;
670 acquireType = wl.monitorType;
671 }
672
673 if (acquireType >= 0) {
674 try {
675 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
676 } catch (RemoteException e) {
677 // Ignore
678 }
679 }
680 }
681
682 public void releaseWakeLock(IBinder lock) {
Michael Chane96440f2009-05-06 10:27:36 -0700683 int uid = Binder.getCallingUid();
684 if (uid != Process.myUid()) {
685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 synchronized (mLocks) {
689 releaseWakeLockLocked(lock, false);
690 }
691 }
692
693 private void releaseWakeLockLocked(IBinder lock, boolean death) {
694 int releaseUid;
695 String releaseName;
696 int releaseType;
697
698 WakeLock wl = mLocks.removeLock(lock);
699 if (wl == null) {
700 return;
701 }
702
703 if (mSpew) {
704 Log.d(TAG, "releaseWakeLock flags=0x"
705 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
706 }
707
708 if (isScreenLock(wl.flags)) {
709 mWakeLockState = mLocks.gatherState();
710 // goes in the middle to reduce flicker
711 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
712 userActivity(SystemClock.uptimeMillis(), false);
713 }
714 setPowerState(mWakeLockState | mUserState);
715 }
716 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
717 mPartialCount--;
718 if (mPartialCount == 0) {
719 if (LOG_PARTIAL_WL) EventLog.writeEvent(LOG_POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
720 Power.releaseWakeLock(PARTIAL_NAME);
721 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700722 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500723 mProximityWakeLockCount--;
724 if (mProximityWakeLockCount == 0) {
725 if (mProximitySensorActive) {
726 // wait for proximity sensor to go negative before disabling sensor
727 if (mDebugProximitySensor) {
728 Log.d(TAG, "waiting for proximity sensor to go negative");
729 }
730 } else {
731 disableProximityLockLocked();
732 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735 // Unlink the lock from the binder.
736 wl.binder.unlinkToDeath(wl, 0);
737 releaseUid = wl.uid;
738 releaseName = wl.tag;
739 releaseType = wl.monitorType;
740
741 if (releaseType >= 0) {
742 long origId = Binder.clearCallingIdentity();
743 try {
744 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
745 } catch (RemoteException e) {
746 // Ignore
747 } finally {
748 Binder.restoreCallingIdentity(origId);
749 }
750 }
751 }
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 private class PokeLock implements IBinder.DeathRecipient
754 {
755 PokeLock(int p, IBinder b, String t) {
756 super();
757 this.pokey = p;
758 this.binder = b;
759 this.tag = t;
760 try {
761 b.linkToDeath(this, 0);
762 } catch (RemoteException e) {
763 binderDied();
764 }
765 }
766 public void binderDied() {
767 setPokeLock(0, this.binder, this.tag);
768 }
769 int pokey;
770 IBinder binder;
771 String tag;
772 boolean awakeOnSet;
773 }
774
775 public void setPokeLock(int pokey, IBinder token, String tag) {
776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
777 if (token == null) {
778 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
779 return;
780 }
781
782 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
783 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
784 + " and POKE_LOCK_MEDIUM_TIMEOUT");
785 }
786
787 synchronized (mLocks) {
788 if (pokey != 0) {
789 PokeLock p = mPokeLocks.get(token);
790 int oldPokey = 0;
791 if (p != null) {
792 oldPokey = p.pokey;
793 p.pokey = pokey;
794 } else {
795 p = new PokeLock(pokey, token, tag);
796 mPokeLocks.put(token, p);
797 }
798 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
799 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
800 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
801 p.awakeOnSet = true;
802 }
803 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700804 PokeLock rLock = mPokeLocks.remove(token);
805 if (rLock != null) {
806 token.unlinkToDeath(rLock, 0);
807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809
810 int oldPokey = mPokey;
811 int cumulative = 0;
812 boolean oldAwakeOnSet = mPokeAwakeOnSet;
813 boolean awakeOnSet = false;
814 for (PokeLock p: mPokeLocks.values()) {
815 cumulative |= p.pokey;
816 if (p.awakeOnSet) {
817 awakeOnSet = true;
818 }
819 }
820 mPokey = cumulative;
821 mPokeAwakeOnSet = awakeOnSet;
822
823 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
824 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
825
826 if (oldCumulativeTimeout != newCumulativeTimeout) {
827 setScreenOffTimeoutsLocked();
828 // reset the countdown timer, but use the existing nextState so it doesn't
829 // change anything
830 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
831 }
832 }
833 }
834
835 private static String lockType(int type)
836 {
837 switch (type)
838 {
839 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700840 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700842 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700844 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700846 return "PARTIAL_WAKE_LOCK ";
847 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
848 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 default:
David Brown251faa62009-08-02 22:04:36 -0700850 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852 }
853
854 private static String dumpPowerState(int state) {
855 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
856 ? "KEYBOARD_BRIGHT_BIT " : "")
857 + (((state & SCREEN_BRIGHT_BIT) != 0)
858 ? "SCREEN_BRIGHT_BIT " : "")
859 + (((state & SCREEN_ON_BIT) != 0)
860 ? "SCREEN_ON_BIT " : "")
861 + (((state & BATTERY_LOW_BIT) != 0)
862 ? "BATTERY_LOW_BIT " : "");
863 }
864
865 @Override
866 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
867 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
868 != PackageManager.PERMISSION_GRANTED) {
869 pw.println("Permission Denial: can't dump PowerManager from from pid="
870 + Binder.getCallingPid()
871 + ", uid=" + Binder.getCallingUid());
872 return;
873 }
874
875 long now = SystemClock.uptimeMillis();
876
877 pw.println("Power Manager State:");
878 pw.println(" mIsPowered=" + mIsPowered
879 + " mPowerState=" + mPowerState
880 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
881 + " ms");
882 pw.println(" mPartialCount=" + mPartialCount);
883 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
884 pw.println(" mUserState=" + dumpPowerState(mUserState));
885 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
886 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
887 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
888 + " " + ((mNextTimeout-now)/1000) + "s from now");
889 pw.println(" mDimScreen=" + mDimScreen
890 + " mStayOnConditions=" + mStayOnConditions);
891 pw.println(" mOffBecauseOfUser=" + mOffBecauseOfUser
892 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700893 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
894 + ',' + mBroadcastQueue[2] + "}");
895 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
896 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
898 pw.println(" mKeyboardVisible=" + mKeyboardVisible
899 + " mUserActivityAllowed=" + mUserActivityAllowed);
900 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
901 + " mScreenOffDelay=" + mScreenOffDelay);
902 pw.println(" mPreventScreenOn=" + mPreventScreenOn
903 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride);
904 pw.println(" mTotalDelaySetting=" + mTotalDelaySetting);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500905 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
907 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
908 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
909 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500910 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
911 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700912 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500913 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
914 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700915 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
916 pw.println(" mLightSensorValue=" + mLightSensorValue);
917 pw.println(" mLightSensorPendingValue=" + mLightSensorPendingValue);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400918 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700919 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mScreenBrightness.dump(pw, " mScreenBrightness: ");
921 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
922 mButtonBrightness.dump(pw, " mButtonBrightness: ");
923
924 int N = mLocks.size();
925 pw.println();
926 pw.println("mLocks.size=" + N + ":");
927 for (int i=0; i<N; i++) {
928 WakeLock wl = mLocks.get(i);
929 String type = lockType(wl.flags & LOCK_MASK);
930 String acquireCausesWakeup = "";
931 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
932 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
933 }
934 String activated = "";
935 if (wl.activated) {
936 activated = " activated";
937 }
938 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
939 + activated + " (minState=" + wl.minState + ")");
940 }
941
942 pw.println();
943 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
944 for (PokeLock p: mPokeLocks.values()) {
945 pw.println(" poke lock '" + p.tag + "':"
946 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
947 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -0700948 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
949 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
951 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
952 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
953 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
954 }
955
956 pw.println();
957 }
958
959 private void setTimeoutLocked(long now, int nextState)
960 {
961 if (mDoneBooting) {
962 mHandler.removeCallbacks(mTimeoutTask);
963 mTimeoutTask.nextState = nextState;
964 long when = now;
965 switch (nextState)
966 {
967 case SCREEN_BRIGHT:
968 when += mKeylightDelay;
969 break;
970 case SCREEN_DIM:
971 if (mDimDelay >= 0) {
972 when += mDimDelay;
973 break;
974 } else {
975 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
976 }
977 case SCREEN_OFF:
978 synchronized (mLocks) {
979 when += mScreenOffDelay;
980 }
981 break;
982 }
983 if (mSpew) {
984 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
985 + " when=" + when);
986 }
987 mHandler.postAtTime(mTimeoutTask, when);
988 mNextTimeout = when; // for debugging
989 }
990 }
991
992 private void cancelTimerLocked()
993 {
994 mHandler.removeCallbacks(mTimeoutTask);
995 mTimeoutTask.nextState = -1;
996 }
997
998 private class TimeoutTask implements Runnable
999 {
1000 int nextState; // access should be synchronized on mLocks
1001 public void run()
1002 {
1003 synchronized (mLocks) {
1004 if (mSpew) {
1005 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1006 }
1007
1008 if (nextState == -1) {
1009 return;
1010 }
1011
1012 mUserState = this.nextState;
1013 setPowerState(this.nextState | mWakeLockState);
1014
1015 long now = SystemClock.uptimeMillis();
1016
1017 switch (this.nextState)
1018 {
1019 case SCREEN_BRIGHT:
1020 if (mDimDelay >= 0) {
1021 setTimeoutLocked(now, SCREEN_DIM);
1022 break;
1023 }
1024 case SCREEN_DIM:
1025 setTimeoutLocked(now, SCREEN_OFF);
1026 break;
1027 }
1028 }
1029 }
1030 }
1031
1032 private void sendNotificationLocked(boolean on, int why)
1033 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001034 if (!on) {
1035 mStillNeedSleepNotification = false;
1036 }
1037
Joe Onorato128e7292009-03-24 18:41:31 -07001038 // Add to the queue.
1039 int index = 0;
1040 while (mBroadcastQueue[index] != -1) {
1041 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
Joe Onorato128e7292009-03-24 18:41:31 -07001043 mBroadcastQueue[index] = on ? 1 : 0;
1044 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045
Joe Onorato128e7292009-03-24 18:41:31 -07001046 // If we added it position 2, then there is a pair that can be stripped.
1047 // If we added it position 1 and we're turning the screen off, we can strip
1048 // the pair and do nothing, because the screen is already off, and therefore
1049 // keyguard has already been enabled.
1050 // However, if we added it at position 1 and we're turning it on, then position
1051 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1052 // on, so have to run the queue then.
1053 if (index == 2) {
1054 // Also, while we're collapsing them, if it's going to be an "off," and one
1055 // is off because of user, then use that, regardless of whether it's the first
1056 // or second one.
1057 if (!on && why == WindowManagerPolicy.OFF_BECAUSE_OF_USER) {
1058 mBroadcastWhy[0] = WindowManagerPolicy.OFF_BECAUSE_OF_USER;
1059 }
1060 mBroadcastQueue[0] = on ? 1 : 0;
1061 mBroadcastQueue[1] = -1;
1062 mBroadcastQueue[2] = -1;
1063 index = 0;
1064 }
1065 if (index == 1 && !on) {
1066 mBroadcastQueue[0] = -1;
1067 mBroadcastQueue[1] = -1;
1068 index = -1;
1069 // The wake lock was being held, but we're not actually going to do any
1070 // broadcasts, so release the wake lock.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
1072 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001073 }
1074
1075 // Now send the message.
1076 if (index >= 0) {
1077 // Acquire the broadcast wake lock before changing the power
1078 // state. It will be release after the broadcast is sent.
1079 // We always increment the ref count for each notification in the queue
1080 // and always decrement when that notification is handled.
1081 mBroadcastWakeLock.acquire();
1082 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
1083 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086
1087 private Runnable mNotificationTask = new Runnable()
1088 {
1089 public void run()
1090 {
Joe Onorato128e7292009-03-24 18:41:31 -07001091 while (true) {
1092 int value;
1093 int why;
1094 WindowManagerPolicy policy;
1095 synchronized (mLocks) {
1096 value = mBroadcastQueue[0];
1097 why = mBroadcastWhy[0];
1098 for (int i=0; i<2; i++) {
1099 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1100 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1101 }
1102 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
Joe Onorato128e7292009-03-24 18:41:31 -07001104 if (value == 1) {
1105 mScreenOnStart = SystemClock.uptimeMillis();
1106
1107 policy.screenTurnedOn();
1108 try {
1109 ActivityManagerNative.getDefault().wakingUp();
1110 } catch (RemoteException e) {
1111 // ignore it
1112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113
Joe Onorato128e7292009-03-24 18:41:31 -07001114 if (mSpew) {
1115 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1116 }
1117 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1118 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1119 mScreenOnBroadcastDone, mHandler, 0, null, null);
1120 } else {
1121 synchronized (mLocks) {
1122 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 2,
1123 mBroadcastWakeLock.mCount);
1124 mBroadcastWakeLock.release();
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127 }
Joe Onorato128e7292009-03-24 18:41:31 -07001128 else if (value == 0) {
1129 mScreenOffStart = SystemClock.uptimeMillis();
1130
1131 policy.screenTurnedOff(why);
1132 try {
1133 ActivityManagerNative.getDefault().goingToSleep();
1134 } catch (RemoteException e) {
1135 // ignore it.
1136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137
Joe Onorato128e7292009-03-24 18:41:31 -07001138 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1139 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1140 mScreenOffBroadcastDone, mHandler, 0, null, null);
1141 } else {
1142 synchronized (mLocks) {
1143 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_STOP, 3,
1144 mBroadcastWakeLock.mCount);
1145 mBroadcastWakeLock.release();
1146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148 }
Joe Onorato128e7292009-03-24 18:41:31 -07001149 else {
1150 // If we're in this case, then this handler is running for a previous
1151 // paired transaction. mBroadcastWakeLock will already have been released.
1152 break;
1153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
1155 }
1156 };
1157
1158 long mScreenOnStart;
1159 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1160 public void onReceive(Context context, Intent intent) {
1161 synchronized (mLocks) {
1162 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 1,
1163 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1164 mBroadcastWakeLock.release();
1165 }
1166 }
1167 };
1168
1169 long mScreenOffStart;
1170 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1171 public void onReceive(Context context, Intent intent) {
1172 synchronized (mLocks) {
1173 EventLog.writeEvent(LOG_POWER_SCREEN_BROADCAST_DONE, 0,
1174 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1175 mBroadcastWakeLock.release();
1176 }
1177 }
1178 };
1179
1180 void logPointerUpEvent() {
1181 if (LOG_TOUCH_DOWNS) {
1182 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1183 mLastTouchDown = 0;
1184 }
1185 }
1186
1187 void logPointerDownEvent() {
1188 if (LOG_TOUCH_DOWNS) {
1189 // If we are not already timing a down/up sequence
1190 if (mLastTouchDown == 0) {
1191 mLastTouchDown = SystemClock.elapsedRealtime();
1192 mTouchCycles++;
1193 }
1194 }
1195 }
1196
1197 /**
1198 * Prevents the screen from turning on even if it *should* turn on due
1199 * to a subsequent full wake lock being acquired.
1200 * <p>
1201 * This is a temporary hack that allows an activity to "cover up" any
1202 * display glitches that happen during the activity's startup
1203 * sequence. (Specifically, this API was added to work around a
1204 * cosmetic bug in the "incoming call" sequence, where the lock screen
1205 * would flicker briefly before the incoming call UI became visible.)
1206 * TODO: There ought to be a more elegant way of doing this,
1207 * probably by having the PowerManager and ActivityManager
1208 * work together to let apps specify that the screen on/off
1209 * state should be synchronized with the Activity lifecycle.
1210 * <p>
1211 * Note that calling preventScreenOn(true) will NOT turn the screen
1212 * off if it's currently on. (This API only affects *future*
1213 * acquisitions of full wake locks.)
1214 * But calling preventScreenOn(false) WILL turn the screen on if
1215 * it's currently off because of a prior preventScreenOn(true) call.
1216 * <p>
1217 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1218 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1219 * call doesn't occur within 5 seconds, we'll turn the screen back on
1220 * ourselves (and log a warning about it); this prevents a buggy app
1221 * from disabling the screen forever.)
1222 * <p>
1223 * TODO: this feature should really be controlled by a new type of poke
1224 * lock (rather than an IPowerManager call).
1225 */
1226 public void preventScreenOn(boolean prevent) {
1227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1228
1229 synchronized (mLocks) {
1230 if (prevent) {
1231 // First of all, grab a partial wake lock to
1232 // make sure the CPU stays on during the entire
1233 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1234 mPreventScreenOnPartialLock.acquire();
1235
1236 // Post a forceReenableScreen() call (for 5 seconds in the
1237 // future) to make sure the matching preventScreenOn(false) call
1238 // has happened by then.
1239 mHandler.removeCallbacks(mForceReenableScreenTask);
1240 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1241
1242 // Finally, set the flag that prevents the screen from turning on.
1243 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001244 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mPreventScreenOn = true;
1246 } else {
1247 // (Re)enable the screen.
1248 mPreventScreenOn = false;
1249
1250 // We're "undoing" a the prior preventScreenOn(true) call, so we
1251 // no longer need the 5-second safeguard.
1252 mHandler.removeCallbacks(mForceReenableScreenTask);
1253
1254 // Forcibly turn on the screen if it's supposed to be on. (This
1255 // handles the case where the screen is currently off because of
1256 // a prior preventScreenOn(true) call.)
1257 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1258 if (mSpew) {
1259 Log.d(TAG,
1260 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1261 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001262 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001264 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
1266 }
1267
1268 // Release the partial wake lock that we held during the
1269 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1270 mPreventScreenOnPartialLock.release();
1271 }
1272 }
1273 }
1274
1275 public void setScreenBrightnessOverride(int brightness) {
1276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1277
1278 synchronized (mLocks) {
1279 if (mScreenBrightnessOverride != brightness) {
1280 mScreenBrightnessOverride = brightness;
1281 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1282 }
1283 }
1284 }
1285
1286 /**
1287 * Sanity-check that gets called 5 seconds after any call to
1288 * preventScreenOn(true). This ensures that the original call
1289 * is followed promptly by a call to preventScreenOn(false).
1290 */
1291 private void forceReenableScreen() {
1292 // We shouldn't get here at all if mPreventScreenOn is false, since
1293 // we should have already removed any existing
1294 // mForceReenableScreenTask messages...
1295 if (!mPreventScreenOn) {
1296 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1297 return;
1298 }
1299
1300 // Uh oh. It's been 5 seconds since a call to
1301 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1302 // This means the app that called preventScreenOn(true) is either
1303 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1304 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1305 // crashed before doing so.)
1306
1307 // Log a warning, and forcibly turn the screen back on.
1308 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1309 + "Forcing the screen back on...");
1310 preventScreenOn(false);
1311 }
1312
1313 private Runnable mForceReenableScreenTask = new Runnable() {
1314 public void run() {
1315 forceReenableScreen();
1316 }
1317 };
1318
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001319 private int setScreenStateLocked(boolean on) {
1320 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001321 if (err == 0) {
1322 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1323 if (mUseSoftwareAutoBrightness) {
1324 enableLightSensor(on);
1325 if (!on) {
1326 // make sure button and key backlights are off too
1327 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, 0);
1328 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, 0);
1329 // clear current value so we will update based on the new conditions
1330 // when the sensor is reenabled.
1331 mLightSensorValue = -1;
1332 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001333 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001334 }
1335 return err;
1336 }
1337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 private void setPowerState(int state)
1339 {
1340 setPowerState(state, false, false);
1341 }
1342
1343 private void setPowerState(int newState, boolean noChangeLights, boolean becauseOfUser)
1344 {
1345 synchronized (mLocks) {
1346 int err;
1347
1348 if (mSpew) {
1349 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1350 + " newState=0x" + Integer.toHexString(newState)
1351 + " noChangeLights=" + noChangeLights);
1352 }
1353
1354 if (noChangeLights) {
1355 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1356 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001357 if (mProximitySensorActive) {
1358 // don't turn on the screen when the proximity sensor lock is held
1359 newState = (newState & ~SCREEN_BRIGHT);
1360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361
1362 if (batteryIsLow()) {
1363 newState |= BATTERY_LOW_BIT;
1364 } else {
1365 newState &= ~BATTERY_LOW_BIT;
1366 }
1367 if (newState == mPowerState) {
1368 return;
1369 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001370
Mike Lockwood4984e732009-11-01 08:16:33 -05001371 if (!mDoneBooting && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 newState |= ALL_BRIGHT;
1373 }
1374
1375 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1376 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1377
Mike Lockwood24ace332009-11-09 19:53:08 -05001378 if (mPowerState != newState) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1380 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1381 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1382 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1383 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1384 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1385 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1386 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1387 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1388 + " newScreenOn=" + newScreenOn);
1389 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1390 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1391 }
1392
1393 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001394 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1396 }
1397
1398 if (oldScreenOn != newScreenOn) {
1399 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001400 // When the user presses the power button, we need to always send out the
1401 // notification that it's going to sleep so the keyguard goes on. But
1402 // we can't do that until the screen fades out, so we don't show the keyguard
1403 // too early.
1404 if (mStillNeedSleepNotification) {
1405 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1406 }
1407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 // Turn on the screen UNLESS there was a prior
1409 // preventScreenOn(true) request. (Note that the lifetime
1410 // of a single preventScreenOn() request is limited to 5
1411 // seconds to prevent a buggy app from disabling the
1412 // screen forever; see forceReenableScreen().)
1413 boolean reallyTurnScreenOn = true;
1414 if (mSpew) {
1415 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1416 + mPreventScreenOn);
1417 }
1418
1419 if (mPreventScreenOn) {
1420 if (mSpew) {
1421 Log.d(TAG, "- PREVENTING screen from really turning on!");
1422 }
1423 reallyTurnScreenOn = false;
1424 }
1425 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001426 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 long identity = Binder.clearCallingIdentity();
1428 try {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001429 mBatteryStats.noteScreenBrightness(
1430 getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 mBatteryStats.noteScreenOn();
1432 } catch (RemoteException e) {
1433 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1434 } finally {
1435 Binder.restoreCallingIdentity(identity);
1436 }
1437 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001438 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 // But continue as if we really did turn the screen on...
1440 err = 0;
1441 }
1442
1443 mScreenOnStartTime = SystemClock.elapsedRealtime();
1444 mLastTouchDown = 0;
1445 mTotalTouchDownTime = 0;
1446 mTouchCycles = 0;
1447 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 1, becauseOfUser ? 1 : 0,
1448 mTotalTouchDownTime, mTouchCycles);
1449 if (err == 0) {
1450 mPowerState |= SCREEN_ON_BIT;
1451 sendNotificationLocked(true, -1);
1452 }
1453 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001454 // cancel light sensor task
1455 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 mScreenOffTime = SystemClock.elapsedRealtime();
1457 long identity = Binder.clearCallingIdentity();
1458 try {
1459 mBatteryStats.noteScreenOff();
1460 } catch (RemoteException e) {
1461 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1462 } finally {
1463 Binder.restoreCallingIdentity(identity);
1464 }
1465 mPowerState &= ~SCREEN_ON_BIT;
1466 if (!mScreenBrightness.animating) {
Joe Onorato128e7292009-03-24 18:41:31 -07001467 err = screenOffFinishedAnimatingLocked(becauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 } else {
1469 mOffBecauseOfUser = becauseOfUser;
1470 err = 0;
1471 mLastTouchDown = 0;
1472 }
1473 }
1474 }
1475 }
1476 }
1477
Joe Onorato128e7292009-03-24 18:41:31 -07001478 private int screenOffFinishedAnimatingLocked(boolean becauseOfUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 // I don't think we need to check the current state here because all of these
1480 // Power.setScreenState and sendNotificationLocked can both handle being
1481 // called multiple times in the same state. -joeo
1482 EventLog.writeEvent(LOG_POWER_SCREEN_STATE, 0, becauseOfUser ? 1 : 0,
1483 mTotalTouchDownTime, mTouchCycles);
1484 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001485 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 if (mScreenOnStartTime != 0) {
1487 mScreenOnTime += SystemClock.elapsedRealtime() - mScreenOnStartTime;
1488 mScreenOnStartTime = 0;
1489 }
1490 if (err == 0) {
1491 int why = becauseOfUser
1492 ? WindowManagerPolicy.OFF_BECAUSE_OF_USER
1493 : WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
1494 sendNotificationLocked(false, why);
1495 }
1496 return err;
1497 }
1498
1499 private boolean batteryIsLow() {
1500 return (!mIsPowered &&
1501 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1502 }
1503
The Android Open Source Project10592532009-03-18 17:39:46 -07001504 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001505 final int oldState = mPowerState;
1506 final int realDifference = (newState ^ oldState);
1507 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511
1512 int offMask = 0;
1513 int dimMask = 0;
1514 int onMask = 0;
1515
1516 int preferredBrightness = getPreferredBrightness();
1517 boolean startAnimation = false;
1518
1519 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1520 if (ANIMATE_KEYBOARD_LIGHTS) {
1521 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1522 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001523 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1524 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 } else {
1526 mKeyboardBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001527 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1528 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530 startAnimation = true;
1531 } else {
1532 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001533 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001535 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537 }
1538 }
1539
1540 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1541 if (ANIMATE_BUTTON_LIGHTS) {
1542 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1543 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001544 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1545 preferredBrightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 } else {
1547 mButtonBrightness.setTargetLocked(preferredBrightness,
Joe Onorato128e7292009-03-24 18:41:31 -07001548 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1549 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 startAnimation = true;
1552 } else {
1553 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001554 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001556 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 }
1559 }
1560
1561 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1562 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001563 int nominalCurrentValue = -1;
1564 // If there was an actual difference in the light state, then
1565 // figure out the "ideal" current value based on the previous
1566 // state. Otherwise, this is a change due to the brightness
1567 // override, so we want to animate from whatever the current
1568 // value is.
1569 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1570 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1571 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1572 nominalCurrentValue = preferredBrightness;
1573 break;
1574 case SCREEN_ON_BIT:
1575 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1576 break;
1577 case 0:
1578 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1579 break;
1580 case SCREEN_BRIGHT_BIT:
1581 default:
1582 // not possible
1583 nominalCurrentValue = (int)mScreenBrightness.curValue;
1584 break;
1585 }
Joe Onorato128e7292009-03-24 18:41:31 -07001586 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001587 int brightness = preferredBrightness;
1588 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1590 // dim or turn off backlight, depending on if the screen is on
1591 // the scale is because the brightness ramp isn't linear and this biases
1592 // it so the later parts take longer.
1593 final float scale = 1.5f;
1594 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1595 if (ratio > 1.0f) ratio = 1.0f;
1596 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1598 // was bright
1599 steps = ANIM_STEPS;
1600 } else {
1601 // was dim
1602 steps = (int)(ANIM_STEPS*ratio*scale);
1603 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001604 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if ((oldState & SCREEN_ON_BIT) != 0) {
1607 // was bright
1608 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1609 } else {
1610 // was dim
1611 steps = (int)(ANIM_STEPS*ratio);
1612 }
1613 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1614 // If the "stay on while plugged in" option is
1615 // turned on, then the screen will often not
1616 // automatically turn off while plugged in. To
1617 // still have a sense of when it is inactive, we
1618 // will then count going dim as turning off.
1619 mScreenOffTime = SystemClock.elapsedRealtime();
1620 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001621 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001624 long identity = Binder.clearCallingIdentity();
1625 try {
1626 mBatteryStats.noteScreenBrightness(brightness);
1627 } catch (RemoteException e) {
1628 // Nothing interesting to do.
1629 } finally {
1630 Binder.restoreCallingIdentity(identity);
1631 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001632 if (mScreenBrightness.setTargetLocked(brightness,
1633 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1634 startAnimation = true;
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 } else {
1637 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1638 // dim or turn off backlight, depending on if the screen is on
1639 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001640 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001642 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001645 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 }
1648 }
1649
1650 if (startAnimation) {
1651 if (mSpew) {
1652 Log.i(TAG, "Scheduling light animator!");
1653 }
1654 mHandler.removeCallbacks(mLightAnimator);
1655 mHandler.post(mLightAnimator);
1656 }
1657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (offMask != 0) {
1659 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001660 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662 if (dimMask != 0) {
1663 int brightness = Power.BRIGHTNESS_DIM;
1664 if ((newState & BATTERY_LOW_BIT) != 0 &&
1665 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1666 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1667 }
1668 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001669 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
1671 if (onMask != 0) {
1672 int brightness = getPreferredBrightness();
1673 if ((newState & BATTERY_LOW_BIT) != 0 &&
1674 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1675 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1676 }
1677 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001678 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681
The Android Open Source Project10592532009-03-18 17:39:46 -07001682 private void setLightBrightness(int mask, int value) {
1683 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
1684 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, value);
1685 }
1686 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
1687 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, value);
1688 }
1689 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
1690 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD, value);
1691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
1694 class BrightnessState {
1695 final int mask;
1696
1697 boolean initialized;
1698 int targetValue;
1699 float curValue;
1700 float delta;
1701 boolean animating;
1702
1703 BrightnessState(int m) {
1704 mask = m;
1705 }
1706
1707 public void dump(PrintWriter pw, String prefix) {
1708 pw.println(prefix + "animating=" + animating
1709 + " targetValue=" + targetValue
1710 + " curValue=" + curValue
1711 + " delta=" + delta);
1712 }
1713
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001714 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001715 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if (!initialized) {
1717 initialized = true;
1718 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001719 } else if (targetValue == target) {
1720 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001723 delta = (targetValue -
1724 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1725 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001727 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001729 + " target=" + targetValue + " delta=" + delta
1730 + " nominalCurrentValue=" + nominalCurrentValue
1731 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
1733 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001734 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736
1737 boolean stepLocked() {
1738 if (!animating) return false;
1739 if (false && mSpew) {
1740 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1741 + " target=" + targetValue + " delta=" + delta);
1742 }
1743 curValue += delta;
1744 int curIntValue = (int)curValue;
1745 boolean more = true;
1746 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001747 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 more = false;
1749 } else if (delta > 0) {
1750 if (curIntValue >= targetValue) {
1751 curValue = curIntValue = targetValue;
1752 more = false;
1753 }
1754 } else {
1755 if (curIntValue <= targetValue) {
1756 curValue = curIntValue = targetValue;
1757 more = false;
1758 }
1759 }
1760 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001761 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 animating = more;
1763 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001764 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Joe Onorato128e7292009-03-24 18:41:31 -07001765 screenOffFinishedAnimatingLocked(mOffBecauseOfUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 }
1768 return more;
1769 }
1770 }
1771
1772 private class LightAnimator implements Runnable {
1773 public void run() {
1774 synchronized (mLocks) {
1775 long now = SystemClock.uptimeMillis();
1776 boolean more = mScreenBrightness.stepLocked();
1777 if (mKeyboardBrightness.stepLocked()) {
1778 more = true;
1779 }
1780 if (mButtonBrightness.stepLocked()) {
1781 more = true;
1782 }
1783 if (more) {
1784 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1785 }
1786 }
1787 }
1788 }
1789
1790 private int getPreferredBrightness() {
1791 try {
1792 if (mScreenBrightnessOverride >= 0) {
1793 return mScreenBrightnessOverride;
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001794 } else if (mLightSensorBrightness >= 0 && mUseSoftwareAutoBrightness
1795 && mAutoBrightessEnabled) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001796 return mLightSensorBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1799 SCREEN_BRIGHTNESS);
1800 // Don't let applications turn the screen all the way off
1801 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1802 } catch (SettingNotFoundException snfe) {
1803 return Power.BRIGHTNESS_ON;
1804 }
1805 }
1806
Charles Mendis322591c2009-10-29 11:06:59 -07001807 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 synchronized (mLocks) {
1809 return (mPowerState & SCREEN_ON_BIT) != 0;
1810 }
1811 }
1812
Charles Mendis322591c2009-10-29 11:06:59 -07001813 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 synchronized (mLocks) {
1815 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1816 }
1817 }
1818
Mike Lockwood497087e32009-11-08 18:33:03 -05001819 private boolean isScreenTurningOffLocked() {
1820 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1821 }
1822
Mike Lockwood200b30b2009-09-20 00:23:59 -04001823 private void forceUserActivityLocked() {
Mike Lockwood952211b2009-11-02 14:17:57 -05001824 // cancel animation so userActivity will succeed
1825 mScreenBrightness.animating = false;
Mike Lockwood200b30b2009-09-20 00:23:59 -04001826 boolean savedActivityAllowed = mUserActivityAllowed;
1827 mUserActivityAllowed = true;
1828 userActivity(SystemClock.uptimeMillis(), false);
1829 mUserActivityAllowed = savedActivityAllowed;
1830 }
1831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1833 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1834 userActivity(time, noChangeLights, OTHER_EVENT, force);
1835 }
1836
1837 public void userActivity(long time, boolean noChangeLights) {
1838 userActivity(time, noChangeLights, OTHER_EVENT, false);
1839 }
1840
1841 public void userActivity(long time, boolean noChangeLights, int eventType) {
1842 userActivity(time, noChangeLights, eventType, false);
1843 }
1844
1845 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1846 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1847
1848 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001849 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001851 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 return;
1854 }
1855
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001856 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1857 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1858 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1859 if (false) {
1860 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1861 }
1862 return;
1863 }
1864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 if (false) {
1866 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1867 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1868 } else {
1869 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1870 }
1871 }
1872
1873 synchronized (mLocks) {
1874 if (mSpew) {
1875 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1876 + " mUserActivityAllowed=" + mUserActivityAllowed
1877 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001878 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1879 + " mProximitySensorActive=" + mProximitySensorActive
1880 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
Mike Lockwood05067122009-10-27 23:07:25 -04001882 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001883 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001884 Log.d(TAG, "ignoring user activity while turning off screen");
1885 return;
1886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 if (mLastEventTime <= time || force) {
1888 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07001889 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001890 // Only turn on button backlights if a button was pressed
1891 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05001892 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
1894 } else {
1895 // don't clear button/keyboard backlights when the screen is touched.
1896 mUserState |= SCREEN_BRIGHT;
1897 }
1898
Dianne Hackborn617f8772009-03-31 15:04:46 -07001899 int uid = Binder.getCallingUid();
1900 long ident = Binder.clearCallingIdentity();
1901 try {
1902 mBatteryStats.noteUserActivity(uid, eventType);
1903 } catch (RemoteException e) {
1904 // Ignore
1905 } finally {
1906 Binder.restoreCallingIdentity(ident);
1907 }
1908
Michael Chane96440f2009-05-06 10:27:36 -07001909 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 setPowerState(mUserState | mWakeLockState, noChangeLights, true);
1911 setTimeoutLocked(time, SCREEN_BRIGHT);
1912 }
1913 }
1914 }
1915 }
1916
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001917 private int getAutoBrightnessValue(int sensorValue, int[] values) {
1918 try {
1919 int i;
1920 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
1921 if (sensorValue < mAutoBrightnessLevels[i]) {
1922 break;
1923 }
1924 }
1925 return values[i];
1926 } catch (Exception e) {
1927 // guard against null pointer or index out of bounds errors
1928 Log.e(TAG, "getAutoBrightnessValue", e);
1929 return 255;
1930 }
1931 }
1932
Mike Lockwood20f87d72009-11-05 16:08:51 -05001933 private Runnable mProximityTask = new Runnable() {
1934 public void run() {
1935 synchronized (mLocks) {
1936 if (mProximityPendingValue != -1) {
1937 proximityChangedLocked(mProximityPendingValue == 1);
1938 mProximityPendingValue = -1;
1939 }
1940 }
1941 }
1942 };
1943
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001944 private Runnable mAutoBrightnessTask = new Runnable() {
1945 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04001946 synchronized (mLocks) {
1947 int value = (int)mLightSensorPendingValue;
1948 if (value >= 0) {
1949 mLightSensorPendingValue = -1;
1950 lightSensorChangedLocked(value);
1951 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001952 }
1953 }
1954 };
1955
1956 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001957 if (mDebugLightSensor) {
1958 Log.d(TAG, "lightSensorChangedLocked " + value);
1959 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001960
1961 if (mLightSensorValue != value) {
1962 mLightSensorValue = value;
1963 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
1964 int lcdValue = getAutoBrightnessValue(value, mLcdBacklightValues);
1965 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04001966 int keyboardValue;
1967 if (mKeyboardVisible) {
1968 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
1969 } else {
1970 keyboardValue = 0;
1971 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001972 mLightSensorBrightness = lcdValue;
1973
1974 if (mDebugLightSensor) {
1975 Log.d(TAG, "lcdValue " + lcdValue);
1976 Log.d(TAG, "buttonValue " + buttonValue);
1977 Log.d(TAG, "keyboardValue " + keyboardValue);
1978 }
1979
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001980 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05001981 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001982 if (ANIMATE_SCREEN_LIGHTS) {
1983 if (mScreenBrightness.setTargetLocked(lcdValue,
1984 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
1985 (int)mScreenBrightness.curValue)) {
1986 startAnimation = true;
1987 }
1988 } else {
1989 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT,
1990 lcdValue);
1991 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001992 }
1993 if (ANIMATE_BUTTON_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04001994 if (mButtonBrightness.setTargetLocked(buttonValue,
1995 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1996 (int)mButtonBrightness.curValue)) {
1997 startAnimation = true;
1998 }
1999 } else {
2000 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS,
2001 buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002002 }
2003 if (ANIMATE_KEYBOARD_LIGHTS) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002004 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2005 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2006 (int)mKeyboardBrightness.curValue)) {
2007 startAnimation = true;
2008 }
2009 } else {
2010 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2011 keyboardValue);
2012 }
2013 if (startAnimation) {
2014 if (mDebugLightSensor) {
2015 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2016 }
2017 mHandler.removeCallbacks(mLightAnimator);
2018 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002019 }
2020 }
2021 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002022 }
2023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 /**
2025 * The user requested that we go to sleep (probably with the power button).
2026 * This overrides all wake locks that are held.
2027 */
2028 public void goToSleep(long time)
2029 {
2030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2031 synchronized (mLocks) {
2032 goToSleepLocked(time);
2033 }
2034 }
2035
2036 /**
2037 * Returns the time the screen has been on since boot, in millis.
2038 * @return screen on time
2039 */
2040 public long getScreenOnTime() {
2041 synchronized (mLocks) {
2042 if (mScreenOnStartTime == 0) {
2043 return mScreenOnTime;
2044 } else {
2045 return SystemClock.elapsedRealtime() - mScreenOnStartTime + mScreenOnTime;
2046 }
2047 }
2048 }
2049
2050 private void goToSleepLocked(long time) {
2051
2052 if (mLastEventTime <= time) {
2053 mLastEventTime = time;
2054 // cancel all of the wake locks
2055 mWakeLockState = SCREEN_OFF;
2056 int N = mLocks.size();
2057 int numCleared = 0;
2058 for (int i=0; i<N; i++) {
2059 WakeLock wl = mLocks.get(i);
2060 if (isScreenLock(wl.flags)) {
2061 mLocks.get(i).activated = false;
2062 numCleared++;
2063 }
2064 }
2065 EventLog.writeEvent(LOG_POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002066 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 mUserState = SCREEN_OFF;
2068 setPowerState(SCREEN_OFF, false, true);
2069 cancelTimerLocked();
2070 }
2071 }
2072
2073 public long timeSinceScreenOn() {
2074 synchronized (mLocks) {
2075 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2076 return 0;
2077 }
2078 return SystemClock.elapsedRealtime() - mScreenOffTime;
2079 }
2080 }
2081
2082 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002083 synchronized (mLocks) {
2084 if (mSpew) {
2085 Log.d(TAG, "setKeyboardVisibility: " + visible);
2086 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002087 if (mKeyboardVisible != visible) {
2088 mKeyboardVisible = visible;
2089 // don't signal user activity if the screen is off; other code
2090 // will take care of turning on due to a true change to the lid
2091 // switch and synchronized with the lock screen.
2092 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002093 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002094 // force recompute of backlight values
2095 if (mLightSensorValue >= 0) {
2096 int value = (int)mLightSensorValue;
2097 mLightSensorValue = -1;
2098 lightSensorChangedLocked(value);
2099 }
2100 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002101 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2102 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002103 }
2104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106
2107 /**
2108 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
2109 */
2110 public void enableUserActivity(boolean enabled) {
2111 synchronized (mLocks) {
2112 mUserActivityAllowed = enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002116 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002117 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002118 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002119 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002120 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002121 // force recompute of backlight values
2122 if (mLightSensorValue >= 0) {
2123 int value = (int)mLightSensorValue;
2124 mLightSensorValue = -1;
2125 lightSensorChangedLocked(value);
2126 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002127 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002128 }
2129 }
2130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 /** Sets the screen off timeouts:
2132 * mKeylightDelay
2133 * mDimDelay
2134 * mScreenOffDelay
2135 * */
2136 private void setScreenOffTimeoutsLocked() {
2137 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
2138 mKeylightDelay = mShortKeylightDelay; // Configurable via Gservices
2139 mDimDelay = -1;
2140 mScreenOffDelay = 0;
2141 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2142 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2143 mDimDelay = -1;
2144 mScreenOffDelay = 0;
2145 } else {
2146 int totalDelay = mTotalDelaySetting;
2147 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2148 if (totalDelay < 0) {
2149 mScreenOffDelay = Integer.MAX_VALUE;
2150 } else if (mKeylightDelay < totalDelay) {
2151 // subtract the time that the keylight delay. This will give us the
2152 // remainder of the time that we need to sleep to get the accurate
2153 // screen off timeout.
2154 mScreenOffDelay = totalDelay - mKeylightDelay;
2155 } else {
2156 mScreenOffDelay = 0;
2157 }
2158 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2159 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2160 mScreenOffDelay = LONG_DIM_TIME;
2161 } else {
2162 mDimDelay = -1;
2163 }
2164 }
2165 if (mSpew) {
2166 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2167 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2168 + " mDimScreen=" + mDimScreen);
2169 }
2170 }
2171
2172 /**
2173 * Refreshes cached Gservices settings. Called once on startup, and
2174 * on subsequent Settings.Gservices.CHANGED_ACTION broadcasts (see
2175 * GservicesChangedReceiver).
2176 */
2177 private void updateGservicesValues() {
2178 mShortKeylightDelay = Settings.Gservices.getInt(
2179 mContext.getContentResolver(),
2180 Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
2181 SHORT_KEYLIGHT_DELAY_DEFAULT);
2182 // Log.i(TAG, "updateGservicesValues(): mShortKeylightDelay now " + mShortKeylightDelay);
2183 }
2184
2185 /**
2186 * Receiver for the Gservices.CHANGED_ACTION broadcast intent,
2187 * which tells us we need to refresh our cached Gservices settings.
2188 */
2189 private class GservicesChangedReceiver extends BroadcastReceiver {
2190 @Override
2191 public void onReceive(Context context, Intent intent) {
2192 // Log.i(TAG, "GservicesChangedReceiver.onReceive(): " + intent);
2193 updateGservicesValues();
2194 }
2195 }
2196
2197 private class LockList extends ArrayList<WakeLock>
2198 {
2199 void addLock(WakeLock wl)
2200 {
2201 int index = getIndex(wl.binder);
2202 if (index < 0) {
2203 this.add(wl);
2204 }
2205 }
2206
2207 WakeLock removeLock(IBinder binder)
2208 {
2209 int index = getIndex(binder);
2210 if (index >= 0) {
2211 return this.remove(index);
2212 } else {
2213 return null;
2214 }
2215 }
2216
2217 int getIndex(IBinder binder)
2218 {
2219 int N = this.size();
2220 for (int i=0; i<N; i++) {
2221 if (this.get(i).binder == binder) {
2222 return i;
2223 }
2224 }
2225 return -1;
2226 }
2227
2228 int gatherState()
2229 {
2230 int result = 0;
2231 int N = this.size();
2232 for (int i=0; i<N; i++) {
2233 WakeLock wl = this.get(i);
2234 if (wl.activated) {
2235 if (isScreenLock(wl.flags)) {
2236 result |= wl.minState;
2237 }
2238 }
2239 }
2240 return result;
2241 }
Michael Chane96440f2009-05-06 10:27:36 -07002242
2243 int reactivateScreenLocksLocked()
2244 {
2245 int result = 0;
2246 int N = this.size();
2247 for (int i=0; i<N; i++) {
2248 WakeLock wl = this.get(i);
2249 if (isScreenLock(wl.flags)) {
2250 wl.activated = true;
2251 result |= wl.minState;
2252 }
2253 }
2254 return result;
2255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 }
2257
2258 void setPolicy(WindowManagerPolicy p) {
2259 synchronized (mLocks) {
2260 mPolicy = p;
2261 mLocks.notifyAll();
2262 }
2263 }
2264
2265 WindowManagerPolicy getPolicyLocked() {
2266 while (mPolicy == null || !mDoneBooting) {
2267 try {
2268 mLocks.wait();
2269 } catch (InterruptedException e) {
2270 // Ignore
2271 }
2272 }
2273 return mPolicy;
2274 }
2275
2276 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002277 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2278 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2279 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002280 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002281 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002282 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002283 }
2284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 synchronized (mLocks) {
2286 Log.d(TAG, "system ready!");
2287 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002288 long identity = Binder.clearCallingIdentity();
2289 try {
2290 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2291 mBatteryStats.noteScreenOn();
2292 } catch (RemoteException e) {
2293 // Nothing interesting to do.
2294 } finally {
2295 Binder.restoreCallingIdentity(identity);
2296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2298 updateWakeLockLocked();
2299 mLocks.notifyAll();
2300 }
2301 }
2302
2303 public void monitor() {
2304 synchronized (mLocks) { }
2305 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002306
2307 public int getSupportedWakeLockFlags() {
2308 int result = PowerManager.PARTIAL_WAKE_LOCK
2309 | PowerManager.FULL_WAKE_LOCK
2310 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2311
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002312 if (mProximitySensor != null) {
2313 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2314 }
2315
2316 return result;
2317 }
2318
Mike Lockwood237a2992009-09-15 14:42:16 -04002319 public void setBacklightBrightness(int brightness) {
2320 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2321 // Don't let applications turn the screen all the way off
2322 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2323 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BACKLIGHT, brightness);
Mike Lockwooddf024922009-10-29 21:29:15 -04002324 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_KEYBOARD,
2325 (mKeyboardVisible ? brightness : 0));
Mike Lockwood237a2992009-09-15 14:42:16 -04002326 mHardware.setLightBrightness_UNCHECKED(HardwareService.LIGHT_ID_BUTTONS, brightness);
2327 long identity = Binder.clearCallingIdentity();
2328 try {
2329 mBatteryStats.noteScreenBrightness(brightness);
2330 } catch (RemoteException e) {
2331 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2332 } finally {
2333 Binder.restoreCallingIdentity(identity);
2334 }
2335
2336 // update our animation state
2337 if (ANIMATE_SCREEN_LIGHTS) {
2338 mScreenBrightness.curValue = brightness;
2339 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002340 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002341 }
2342 if (ANIMATE_KEYBOARD_LIGHTS) {
2343 mKeyboardBrightness.curValue = brightness;
2344 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002345 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002346 }
2347 if (ANIMATE_BUTTON_LIGHTS) {
2348 mButtonBrightness.curValue = brightness;
2349 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002350 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002351 }
2352 }
2353
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002354 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002355 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002356 Log.d(TAG, "enableProximityLockLocked");
2357 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002358 if (!mProximitySensorEnabled) {
2359 // clear calling identity so sensor manager battery stats are accurate
2360 long identity = Binder.clearCallingIdentity();
2361 try {
2362 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2363 SensorManager.SENSOR_DELAY_NORMAL);
2364 mProximitySensorEnabled = true;
2365 } finally {
2366 Binder.restoreCallingIdentity(identity);
2367 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002368 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002369 }
2370
2371 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002372 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002373 Log.d(TAG, "disableProximityLockLocked");
2374 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002375 if (mProximitySensorEnabled) {
2376 // clear calling identity so sensor manager battery stats are accurate
2377 long identity = Binder.clearCallingIdentity();
2378 try {
2379 mSensorManager.unregisterListener(mProximityListener);
2380 mHandler.removeCallbacks(mProximityTask);
2381 mProximitySensorEnabled = false;
2382 } finally {
2383 Binder.restoreCallingIdentity(identity);
2384 }
2385 if (mProximitySensorActive) {
2386 mProximitySensorActive = false;
2387 forceUserActivityLocked();
2388 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002389 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002390 }
2391
Mike Lockwood20f87d72009-11-05 16:08:51 -05002392 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002393 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002394 Log.d(TAG, "proximityChangedLocked, active: " + active);
2395 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002396 if (!mProximitySensorEnabled) {
2397 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002398 return;
2399 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002400 if (active) {
2401 goToSleepLocked(SystemClock.uptimeMillis());
2402 mProximitySensorActive = true;
2403 } else {
2404 // proximity sensor negative events trigger as user activity.
2405 // temporarily set mUserActivityAllowed to true so this will work
2406 // even when the keyguard is on.
2407 mProximitySensorActive = false;
2408 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002409
2410 if (mProximityWakeLockCount == 0) {
2411 // disable sensor if we have no listeners left after proximity negative
2412 disableProximityLockLocked();
2413 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002414 }
2415 }
2416
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002417 private void enableLightSensor(boolean enable) {
2418 if (mDebugLightSensor) {
2419 Log.d(TAG, "enableLightSensor " + enable);
2420 }
2421 if (mSensorManager != null && mLightSensorEnabled != enable) {
2422 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002423 // clear calling identity so sensor manager battery stats are accurate
2424 long identity = Binder.clearCallingIdentity();
2425 try {
2426 if (enable) {
2427 mSensorManager.registerListener(mLightListener, mLightSensor,
2428 SensorManager.SENSOR_DELAY_NORMAL);
2429 } else {
2430 mSensorManager.unregisterListener(mLightListener);
2431 mHandler.removeCallbacks(mAutoBrightnessTask);
2432 }
2433 } finally {
2434 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002435 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002436 }
2437 }
2438
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002439 SensorEventListener mProximityListener = new SensorEventListener() {
2440 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002441 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002442 synchronized (mLocks) {
2443 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002444 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2445 mLastProximityEventTime = milliseconds;
2446 mHandler.removeCallbacks(mProximityTask);
2447
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002448 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002449 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2450 distance < mProximitySensor.getMaximumRange());
2451
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002452 if (mDebugProximitySensor) {
2453 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2454 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002455 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2456 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2457 mProximityPendingValue = (active ? 1 : 0);
2458 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002459 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002460 // process the value immediately
2461 mProximityPendingValue = -1;
2462 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002463 }
2464 }
2465 }
2466
2467 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2468 // ignore
2469 }
2470 };
2471
2472 SensorEventListener mLightListener = new SensorEventListener() {
2473 public void onSensorChanged(SensorEvent event) {
2474 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002475 // ignore light sensor while screen is turning off
2476 if (isScreenTurningOffLocked()) {
2477 return;
2478 }
2479
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002480 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002481 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002482 if (mDebugLightSensor) {
2483 Log.d(TAG, "onSensorChanged: light value: " + value);
2484 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002485 mHandler.removeCallbacks(mAutoBrightnessTask);
2486 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002487 if (mLightSensorValue == -1 ||
2488 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2489 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002490 lightSensorChangedLocked(value);
2491 } else {
2492 // delay processing to debounce the sensor
2493 mLightSensorPendingValue = value;
2494 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2495 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002496 } else {
2497 mLightSensorPendingValue = -1;
2498 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002499 }
2500 }
2501
2502 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2503 // ignore
2504 }
2505 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506}