blob: 1e7dd992c4a02c2ff68088154d7b3c7c84bcc671 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.app.IActivityManager;
24import android.content.BroadcastReceiver;
25import android.content.ContentQueryMap;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070031import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070034import android.hardware.Sensor;
35import android.hardware.SensorEvent;
36import android.hardware.SensorEventListener;
37import android.hardware.SensorManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.BatteryStats;
39import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080040import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Handler;
42import android.os.HandlerThread;
43import android.os.IBinder;
Doug Zongker43866e02010-01-07 12:09:54 -080044import android.os.IMountService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.IPowerManager;
46import android.os.LocalPowerManager;
47import android.os.Power;
48import android.os.PowerManager;
49import android.os.Process;
50import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080051import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.provider.Settings.SettingNotFoundException;
54import android.provider.Settings;
55import android.util.EventLog;
56import android.util.Log;
57import android.view.WindowManagerPolicy;
58import static android.provider.Settings.System.DIM_SCREEN;
59import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050060import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070061import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
63import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
64
65import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080066import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.io.PrintWriter;
68import java.util.ArrayList;
69import java.util.HashMap;
70import java.util.Observable;
71import java.util.Observer;
72
Mike Lockwoodbc706a02009-07-27 13:50:57 -070073class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040074 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76 private static final String TAG = "PowerManagerService";
77 static final String PARTIAL_NAME = "PowerManagerService";
78
79 private static final boolean LOG_PARTIAL_WL = false;
80
81 // Indicates whether touch-down cycles should be logged as part of the
82 // LOG_POWER_SCREEN_STATE log events
83 private static final boolean LOG_TOUCH_DOWNS = true;
84
85 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
86 | PowerManager.SCREEN_DIM_WAKE_LOCK
87 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070088 | PowerManager.FULL_WAKE_LOCK
89 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
91 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080092 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
94 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
95 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
96 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
97
Mike Lockwoodd7786b42009-10-15 17:09:16 -070098 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -050099 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700100
Mike Lockwood20f87d72009-11-05 16:08:51 -0500101 // For debouncing the proximity sensor.
102 private static final int PROXIMITY_SENSOR_DELAY = 1000;
103
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400104 // trigger proximity if distance is less than 5 cm
105 private static final float PROXIMITY_THRESHOLD = 5.0f;
106
Doug Zongker43866e02010-01-07 12:09:54 -0800107 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
109
110 // flags for setPowerState
111 private static final int SCREEN_ON_BIT = 0x00000001;
112 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
113 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
114 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
115 private static final int BATTERY_LOW_BIT = 0x00000010;
116
117 // values for setPowerState
118
119 // SCREEN_OFF == everything off
120 private static final int SCREEN_OFF = 0x00000000;
121
122 // SCREEN_DIM == screen on, screen backlight dim
123 private static final int SCREEN_DIM = SCREEN_ON_BIT;
124
125 // SCREEN_BRIGHT == screen on, screen backlight bright
126 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
127
128 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
129 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
130
131 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
132 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
133
134 // used for noChangeLights in setPowerState()
135 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
136
137 static final boolean ANIMATE_SCREEN_LIGHTS = true;
138 static final boolean ANIMATE_BUTTON_LIGHTS = false;
139 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400142 // Slower animation for autobrightness changes
143 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 // These magic numbers are the initial state of the LEDs at boot. Ideally
146 // we should read them from the driver, but our current hardware returns 0
147 // for the initial value. Oops!
148 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
149 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
150 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private final int MY_UID;
153
154 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500155 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private int mStayOnConditions = 0;
Joe Onorato128e7292009-03-24 18:41:31 -0700157 private int[] mBroadcastQueue = new int[] { -1, -1, -1 };
158 private int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private int mPartialCount = 0;
160 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500161 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
162 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
163 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mUserState;
165 private boolean mKeyboardVisible = false;
166 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500167 private int mProximityWakeLockCount = 0;
168 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700169 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500170 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
171 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800172 private int mScreenOffTimeoutSetting;
173 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 private int mKeylightDelay;
175 private int mDimDelay;
176 private int mScreenOffDelay;
177 private int mWakeLockState;
178 private long mLastEventTime = 0;
179 private long mScreenOffTime;
180 private volatile WindowManagerPolicy mPolicy;
181 private final LockList mLocks = new LockList();
182 private Intent mScreenOffIntent;
183 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500184 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500186 private LightsService.Light mLcdLight;
187 private LightsService.Light mButtonLight;
188 private LightsService.Light mKeyboardLight;
189 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private UnsynchronizedWakeLock mBroadcastWakeLock;
191 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
192 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
193 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500194 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private HandlerThread mHandlerThread;
196 private Handler mHandler;
197 private TimeoutTask mTimeoutTask = new TimeoutTask();
198 private LightAnimator mLightAnimator = new LightAnimator();
199 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700200 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700202 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700204 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700205 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private boolean mIsPowered = false;
207 private IActivityManager mActivityService;
208 private IBatteryStats mBatteryStats;
209 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700210 private SensorManager mSensorManager;
211 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400212 private Sensor mLightSensor;
213 private boolean mLightSensorEnabled;
214 private float mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500215 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700216 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500217 private int mLightSensorScreenBrightness = -1;
218 private int mLightSensorButtonBrightness = -1;
219 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500221 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private long mNextTimeout;
223 private volatile int mPokey = 0;
224 private volatile boolean mPokeAwakeOnSet = false;
225 private volatile boolean mInitComplete = false;
226 private HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500227 // mLastScreenOnTime is the time the screen was last turned on
228 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private boolean mPreventScreenOn;
230 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500231 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400232 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700233 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700234 private int[] mAutoBrightnessLevels;
235 private int[] mLcdBacklightValues;
236 private int[] mButtonBacklightValues;
237 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500238 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Used when logging number and duration of touch-down cycles
241 private long mTotalTouchDownTime;
242 private long mLastTouchDown;
243 private int mTouchCycles;
244
245 // could be either static or controllable at runtime
246 private static final boolean mSpew = false;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500247 private static final boolean mDebugProximitySensor = (true || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400248 private static final boolean mDebugLightSensor = (false || mSpew);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
250 /*
251 static PrintStream mLog;
252 static {
253 try {
254 mLog = new PrintStream("/data/power.log");
255 }
256 catch (FileNotFoundException e) {
257 android.util.Log.e(TAG, "Life is hard", e);
258 }
259 }
260 static class Log {
261 static void d(String tag, String s) {
262 mLog.println(s);
263 android.util.Log.d(tag, s);
264 }
265 static void i(String tag, String s) {
266 mLog.println(s);
267 android.util.Log.i(tag, s);
268 }
269 static void w(String tag, String s) {
270 mLog.println(s);
271 android.util.Log.w(tag, s);
272 }
273 static void e(String tag, String s) {
274 mLog.println(s);
275 android.util.Log.e(tag, s);
276 }
277 }
278 */
279
280 /**
281 * This class works around a deadlock between the lock in PowerManager.WakeLock
282 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
283 * mToken object so it can be accessed from any thread, but it calls into here
284 * with its lock held. This class is essentially a reimplementation of
285 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
286 * only call it with our own locks held.
287 */
288 private class UnsynchronizedWakeLock {
289 int mFlags;
290 String mTag;
291 IBinder mToken;
292 int mCount = 0;
293 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500294 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
296 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
297 mFlags = flags;
298 mTag = tag;
299 mToken = new Binder();
300 mRefCounted = refCounted;
301 }
302
303 public void acquire() {
304 if (!mRefCounted || mCount++ == 0) {
305 long ident = Binder.clearCallingIdentity();
306 try {
307 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
308 MY_UID, mTag);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500309 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 } finally {
311 Binder.restoreCallingIdentity(ident);
312 }
313 }
314 }
315
316 public void release() {
317 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500318 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500319 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 }
321 if (mCount < 0) {
322 throw new RuntimeException("WakeLock under-locked " + mTag);
323 }
324 }
325
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500326 public boolean isHeld()
327 {
328 return mHeld;
329 }
330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 public String toString() {
332 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500333 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 }
335 }
336
337 private final class BatteryReceiver extends BroadcastReceiver {
338 @Override
339 public void onReceive(Context context, Intent intent) {
340 synchronized (mLocks) {
341 boolean wasPowered = mIsPowered;
342 mIsPowered = mBatteryService.isPowered();
343
344 if (mIsPowered != wasPowered) {
345 // update mStayOnWhilePluggedIn wake lock
346 updateWakeLockLocked();
347
348 // treat plugging and unplugging the devices as a user activity.
349 // users find it disconcerting when they unplug the device
350 // and it shuts off right away.
351 // temporarily set mUserActivityAllowed to true so this will work
352 // even when the keyguard is on.
353 synchronized (mLocks) {
Mike Lockwood200b30b2009-09-20 00:23:59 -0400354 forceUserActivityLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
356 }
357 }
358 }
359 }
360
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500361 private final class BootCompletedReceiver extends BroadcastReceiver {
362 @Override
363 public void onReceive(Context context, Intent intent) {
364 bootCompleted();
365 }
366 }
367
Mike Lockwoodb2865412010-02-02 22:40:33 -0500368 private final class DockReceiver extends BroadcastReceiver {
369 @Override
370 public void onReceive(Context context, Intent intent) {
371 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
372 Intent.EXTRA_DOCK_STATE_UNDOCKED);
373 dockStateChanged(state);
374 }
375 }
376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 /**
378 * Set the setting that determines whether the device stays on when plugged in.
379 * The argument is a bit string, with each bit specifying a power source that,
380 * when the device is connected to that source, causes the device to stay on.
381 * See {@link android.os.BatteryManager} for the list of power sources that
382 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
383 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
384 * @param val an {@code int} containing the bits that specify which power sources
385 * should cause the device to stay on.
386 */
387 public void setStayOnSetting(int val) {
388 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
389 Settings.System.putInt(mContext.getContentResolver(),
390 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
391 }
392
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800393 public void setMaximumScreenOffTimeount(int timeMs) {
394 mContext.enforceCallingOrSelfPermission(
395 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
396 synchronized (mLocks) {
397 mMaximumScreenOffTimeout = timeMs;
398 // recalculate everything
399 setScreenOffTimeoutsLocked();
400 }
401 }
402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 private class SettingsObserver implements Observer {
404 private int getInt(String name) {
405 return mSettings.getValues(name).getAsInteger(Settings.System.VALUE);
406 }
407
408 public void update(Observable o, Object arg) {
409 synchronized (mLocks) {
410 // STAY_ON_WHILE_PLUGGED_IN
411 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN);
412 updateWakeLockLocked();
413
414 // SCREEN_OFF_TIMEOUT
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800415 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416
417 // DIM_SCREEN
418 //mDimScreen = getInt(DIM_SCREEN) != 0;
419
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700420 // SCREEN_BRIGHTNESS_MODE
421 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE));
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 // recalculate everything
424 setScreenOffTimeoutsLocked();
425 }
426 }
427 }
428
429 PowerManagerService()
430 {
431 // Hack to get our uid... should have a func for this.
432 long token = Binder.clearCallingIdentity();
433 MY_UID = Binder.getCallingUid();
434 Binder.restoreCallingIdentity(token);
435
436 // XXX remove this when the kernel doesn't timeout wake locks
437 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
438
439 // assume nothing is on yet
440 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 // Add ourself to the Watchdog monitors.
443 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 }
445
446 private ContentQueryMap mSettings;
447
Mike Lockwood3a322132009-11-24 00:30:52 -0500448 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700449 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500450 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 mContext = context;
452 mActivityService = activity;
453 mBatteryStats = BatteryStatsService.getService();
454 mBatteryService = battery;
455
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500456 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
457 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
458 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
459 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 mHandlerThread = new HandlerThread("PowerManagerService") {
462 @Override
463 protected void onLooperPrepared() {
464 super.onLooperPrepared();
465 initInThread();
466 }
467 };
468 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 synchronized (mHandlerThread) {
471 while (!mInitComplete) {
472 try {
473 mHandlerThread.wait();
474 } catch (InterruptedException e) {
475 // Ignore
476 }
477 }
478 }
479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 void initInThread() {
482 mHandler = new Handler();
483
484 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700485 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
487 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
488 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
489 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
490 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
491 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500492 mProximityPartialLock = new UnsynchronizedWakeLock(
493 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494
495 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
496 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
497 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
498 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
499
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700500 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400501
502 // read settings for auto-brightness
503 mUseSoftwareAutoBrightness = resources.getBoolean(
504 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400505 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700506 mAutoBrightnessLevels = resources.getIntArray(
507 com.android.internal.R.array.config_autoBrightnessLevels);
508 mLcdBacklightValues = resources.getIntArray(
509 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
510 mButtonBacklightValues = resources.getIntArray(
511 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
512 mKeyboardBacklightValues = resources.getIntArray(
513 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500514 mLightSensorWarmupTime = resources.getInteger(
515 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700516 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700517
518 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
520 "(" + Settings.System.NAME + "=?) or ("
521 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700522 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700524 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
525 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 null);
527 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
528 SettingsObserver settingsObserver = new SettingsObserver();
529 mSettings.addObserver(settingsObserver);
530
531 // pretend that the settings changed so we will get their initial state
532 settingsObserver.update(mSettings, null);
533
534 // register for the battery changed notifications
535 IntentFilter filter = new IntentFilter();
536 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
537 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500538 filter = new IntentFilter();
539 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
540 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500541 filter = new IntentFilter();
542 filter.addAction(Intent.ACTION_DOCK_EVENT);
543 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544
Doug Zongker43866e02010-01-07 12:09:54 -0800545 // Listen for secure settings changes
546 mContext.getContentResolver().registerContentObserver(
547 Settings.Secure.CONTENT_URI, true,
548 new ContentObserver(new Handler()) {
549 public void onChange(boolean selfChange) {
550 updateSettingsValues();
551 }
552 });
553 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554
Mike Lockwood4984e732009-11-01 08:16:33 -0500555 if (mUseSoftwareAutoBrightness) {
Mike Lockwood6c97fca2009-10-20 08:10:00 -0400556 // turn the screen on
557 setPowerState(SCREEN_BRIGHT);
558 } else {
559 // turn everything on
560 setPowerState(ALL_BRIGHT);
561 }
Dan Murphy951764b2009-08-27 14:59:03 -0500562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 synchronized (mHandlerThread) {
564 mInitComplete = true;
565 mHandlerThread.notifyAll();
566 }
567 }
568
569 private class WakeLock implements IBinder.DeathRecipient
570 {
571 WakeLock(int f, IBinder b, String t, int u) {
572 super();
573 flags = f;
574 binder = b;
575 tag = t;
576 uid = u == MY_UID ? Process.SYSTEM_UID : u;
577 if (u != MY_UID || (
578 !"KEEP_SCREEN_ON_FLAG".equals(tag)
579 && !"KeyInputQueue".equals(tag))) {
580 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
581 ? BatteryStats.WAKE_TYPE_PARTIAL
582 : BatteryStats.WAKE_TYPE_FULL;
583 } else {
584 monitorType = -1;
585 }
586 try {
587 b.linkToDeath(this, 0);
588 } catch (RemoteException e) {
589 binderDied();
590 }
591 }
592 public void binderDied() {
593 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500594 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596 }
597 final int flags;
598 final IBinder binder;
599 final String tag;
600 final int uid;
601 final int monitorType;
602 boolean activated = true;
603 int minState;
604 }
605
606 private void updateWakeLockLocked() {
607 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
608 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
609 mStayOnWhilePluggedInScreenDimLock.acquire();
610 mStayOnWhilePluggedInPartialLock.acquire();
611 } else {
612 mStayOnWhilePluggedInScreenDimLock.release();
613 mStayOnWhilePluggedInPartialLock.release();
614 }
615 }
616
617 private boolean isScreenLock(int flags)
618 {
619 int n = flags & LOCK_MASK;
620 return n == PowerManager.FULL_WAKE_LOCK
621 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
622 || n == PowerManager.SCREEN_DIM_WAKE_LOCK;
623 }
624
625 public void acquireWakeLock(int flags, IBinder lock, String tag) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 int uid = Binder.getCallingUid();
Michael Chane96440f2009-05-06 10:27:36 -0700627 if (uid != Process.myUid()) {
628 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 long ident = Binder.clearCallingIdentity();
631 try {
632 synchronized (mLocks) {
633 acquireWakeLockLocked(flags, lock, uid, tag);
634 }
635 } finally {
636 Binder.restoreCallingIdentity(ident);
637 }
638 }
639
640 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, String tag) {
641 int acquireUid = -1;
642 String acquireName = null;
643 int acquireType = -1;
644
645 if (mSpew) {
646 Log.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
647 }
648
649 int index = mLocks.getIndex(lock);
650 WakeLock wl;
651 boolean newlock;
652 if (index < 0) {
653 wl = new WakeLock(flags, lock, tag, uid);
654 switch (wl.flags & LOCK_MASK)
655 {
656 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500657 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400658 wl.minState = SCREEN_BRIGHT;
659 } else {
660 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 break;
663 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
664 wl.minState = SCREEN_BRIGHT;
665 break;
666 case PowerManager.SCREEN_DIM_WAKE_LOCK:
667 wl.minState = SCREEN_DIM;
668 break;
669 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700670 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 break;
672 default:
673 // just log and bail. we're in the server, so don't
674 // throw an exception.
675 Log.e(TAG, "bad wakelock type for lock '" + tag + "' "
676 + " flags=" + flags);
677 return;
678 }
679 mLocks.addLock(wl);
680 newlock = true;
681 } else {
682 wl = mLocks.get(index);
683 newlock = false;
684 }
685 if (isScreenLock(flags)) {
686 // if this causes a wakeup, we reactivate all of the locks and
687 // set it to whatever they want. otherwise, we modulate that
688 // by the current state so we never turn it more on than
689 // it already is.
690 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
Michael Chane96440f2009-05-06 10:27:36 -0700691 int oldWakeLockState = mWakeLockState;
692 mWakeLockState = mLocks.reactivateScreenLocksLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 if (mSpew) {
694 Log.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
Michael Chane96440f2009-05-06 10:27:36 -0700695 + " mWakeLockState=0x"
696 + Integer.toHexString(mWakeLockState)
697 + " previous wakeLockState=0x" + Integer.toHexString(oldWakeLockState));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 } else {
700 if (mSpew) {
701 Log.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
702 + " mLocks.gatherState()=0x"
703 + Integer.toHexString(mLocks.gatherState())
704 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
705 }
706 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
707 }
708 setPowerState(mWakeLockState | mUserState);
709 }
710 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
711 if (newlock) {
712 mPartialCount++;
713 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716 }
717 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700718 } else if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500719 mProximityWakeLockCount++;
720 if (mProximityWakeLockCount == 1) {
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700721 enableProximityLockLocked();
722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
724 if (newlock) {
725 acquireUid = wl.uid;
726 acquireName = wl.tag;
727 acquireType = wl.monitorType;
728 }
729
730 if (acquireType >= 0) {
731 try {
732 mBatteryStats.noteStartWakelock(acquireUid, acquireName, acquireType);
733 } catch (RemoteException e) {
734 // Ignore
735 }
736 }
737 }
738
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500739 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700740 int uid = Binder.getCallingUid();
741 if (uid != Process.myUid()) {
742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744
745 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500746 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 }
748 }
749
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500750 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 int releaseUid;
752 String releaseName;
753 int releaseType;
754
755 WakeLock wl = mLocks.removeLock(lock);
756 if (wl == null) {
757 return;
758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 if (mSpew) {
761 Log.d(TAG, "releaseWakeLock flags=0x"
762 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
763 }
764
765 if (isScreenLock(wl.flags)) {
766 mWakeLockState = mLocks.gatherState();
767 // goes in the middle to reduce flicker
768 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
769 userActivity(SystemClock.uptimeMillis(), false);
770 }
771 setPowerState(mWakeLockState | mUserState);
772 }
773 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
774 mPartialCount--;
775 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 Power.releaseWakeLock(PARTIAL_NAME);
778 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700779 } else if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500780 mProximityWakeLockCount--;
781 if (mProximityWakeLockCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500782 if (mProximitySensorActive &&
783 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500784 // wait for proximity sensor to go negative before disabling sensor
785 if (mDebugProximitySensor) {
786 Log.d(TAG, "waiting for proximity sensor to go negative");
787 }
788 } else {
789 disableProximityLockLocked();
790 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 }
793 // Unlink the lock from the binder.
794 wl.binder.unlinkToDeath(wl, 0);
795 releaseUid = wl.uid;
796 releaseName = wl.tag;
797 releaseType = wl.monitorType;
798
799 if (releaseType >= 0) {
800 long origId = Binder.clearCallingIdentity();
801 try {
802 mBatteryStats.noteStopWakelock(releaseUid, releaseName, releaseType);
803 } catch (RemoteException e) {
804 // Ignore
805 } finally {
806 Binder.restoreCallingIdentity(origId);
807 }
808 }
809 }
810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 private class PokeLock implements IBinder.DeathRecipient
812 {
813 PokeLock(int p, IBinder b, String t) {
814 super();
815 this.pokey = p;
816 this.binder = b;
817 this.tag = t;
818 try {
819 b.linkToDeath(this, 0);
820 } catch (RemoteException e) {
821 binderDied();
822 }
823 }
824 public void binderDied() {
825 setPokeLock(0, this.binder, this.tag);
826 }
827 int pokey;
828 IBinder binder;
829 String tag;
830 boolean awakeOnSet;
831 }
832
833 public void setPokeLock(int pokey, IBinder token, String tag) {
834 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
835 if (token == null) {
836 Log.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
837 return;
838 }
839
840 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
841 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
842 + " and POKE_LOCK_MEDIUM_TIMEOUT");
843 }
844
845 synchronized (mLocks) {
846 if (pokey != 0) {
847 PokeLock p = mPokeLocks.get(token);
848 int oldPokey = 0;
849 if (p != null) {
850 oldPokey = p.pokey;
851 p.pokey = pokey;
852 } else {
853 p = new PokeLock(pokey, token, tag);
854 mPokeLocks.put(token, p);
855 }
856 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
857 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
858 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
859 p.awakeOnSet = true;
860 }
861 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700862 PokeLock rLock = mPokeLocks.remove(token);
863 if (rLock != null) {
864 token.unlinkToDeath(rLock, 0);
865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
867
868 int oldPokey = mPokey;
869 int cumulative = 0;
870 boolean oldAwakeOnSet = mPokeAwakeOnSet;
871 boolean awakeOnSet = false;
872 for (PokeLock p: mPokeLocks.values()) {
873 cumulative |= p.pokey;
874 if (p.awakeOnSet) {
875 awakeOnSet = true;
876 }
877 }
878 mPokey = cumulative;
879 mPokeAwakeOnSet = awakeOnSet;
880
881 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
882 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (oldCumulativeTimeout != newCumulativeTimeout) {
885 setScreenOffTimeoutsLocked();
886 // reset the countdown timer, but use the existing nextState so it doesn't
887 // change anything
888 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
889 }
890 }
891 }
892
893 private static String lockType(int type)
894 {
895 switch (type)
896 {
897 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700898 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700900 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700902 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700904 return "PARTIAL_WAKE_LOCK ";
905 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
906 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 default:
David Brown251faa62009-08-02 22:04:36 -0700908 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
910 }
911
912 private static String dumpPowerState(int state) {
913 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
914 ? "KEYBOARD_BRIGHT_BIT " : "")
915 + (((state & SCREEN_BRIGHT_BIT) != 0)
916 ? "SCREEN_BRIGHT_BIT " : "")
917 + (((state & SCREEN_ON_BIT) != 0)
918 ? "SCREEN_ON_BIT " : "")
919 + (((state & BATTERY_LOW_BIT) != 0)
920 ? "BATTERY_LOW_BIT " : "");
921 }
922
923 @Override
924 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
925 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
926 != PackageManager.PERMISSION_GRANTED) {
927 pw.println("Permission Denial: can't dump PowerManager from from pid="
928 + Binder.getCallingPid()
929 + ", uid=" + Binder.getCallingUid());
930 return;
931 }
932
933 long now = SystemClock.uptimeMillis();
934
935 pw.println("Power Manager State:");
936 pw.println(" mIsPowered=" + mIsPowered
937 + " mPowerState=" + mPowerState
938 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
939 + " ms");
940 pw.println(" mPartialCount=" + mPartialCount);
941 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
942 pw.println(" mUserState=" + dumpPowerState(mUserState));
943 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
944 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
945 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
946 + " " + ((mNextTimeout-now)/1000) + "s from now");
947 pw.println(" mDimScreen=" + mDimScreen
948 + " mStayOnConditions=" + mStayOnConditions);
Mike Lockwood435eb642009-12-03 08:40:18 -0500949 pw.println(" mScreenOffReason=" + mScreenOffReason
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 + " mUserState=" + mUserState);
Joe Onorato128e7292009-03-24 18:41:31 -0700951 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
952 + ',' + mBroadcastQueue[2] + "}");
953 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
954 + ',' + mBroadcastWhy[2] + "}");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
956 pw.println(" mKeyboardVisible=" + mKeyboardVisible
957 + " mUserActivityAllowed=" + mUserActivityAllowed);
958 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
959 + " mScreenOffDelay=" + mScreenOffDelay);
960 pw.println(" mPreventScreenOn=" + mPreventScreenOn
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500961 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
962 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800963 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
964 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500965 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
967 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
968 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
969 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500970 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500971 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
972 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700973 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
Mike Lockwood20f87d72009-11-05 16:08:51 -0500974 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
975 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700976 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500977 pw.println(" mLightSensorValue=" + mLightSensorValue
978 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
979 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
980 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
981 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400982 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700983 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 mScreenBrightness.dump(pw, " mScreenBrightness: ");
985 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
986 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 int N = mLocks.size();
989 pw.println();
990 pw.println("mLocks.size=" + N + ":");
991 for (int i=0; i<N; i++) {
992 WakeLock wl = mLocks.get(i);
993 String type = lockType(wl.flags & LOCK_MASK);
994 String acquireCausesWakeup = "";
995 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
996 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
997 }
998 String activated = "";
999 if (wl.activated) {
1000 activated = " activated";
1001 }
1002 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
1003 + activated + " (minState=" + wl.minState + ")");
1004 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 pw.println();
1007 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1008 for (PokeLock p: mPokeLocks.values()) {
1009 pw.println(" poke lock '" + p.tag + "':"
1010 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1011 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001012 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1013 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1015 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1016 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1017 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
1018 }
1019
1020 pw.println();
1021 }
1022
1023 private void setTimeoutLocked(long now, int nextState)
1024 {
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001025 if (mBootCompleted) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 mHandler.removeCallbacks(mTimeoutTask);
1027 mTimeoutTask.nextState = nextState;
1028 long when = now;
1029 switch (nextState)
1030 {
1031 case SCREEN_BRIGHT:
1032 when += mKeylightDelay;
1033 break;
1034 case SCREEN_DIM:
1035 if (mDimDelay >= 0) {
1036 when += mDimDelay;
1037 break;
1038 } else {
1039 Log.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1040 }
1041 case SCREEN_OFF:
1042 synchronized (mLocks) {
1043 when += mScreenOffDelay;
1044 }
1045 break;
1046 }
1047 if (mSpew) {
1048 Log.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
1049 + " when=" + when);
1050 }
1051 mHandler.postAtTime(mTimeoutTask, when);
1052 mNextTimeout = when; // for debugging
1053 }
1054 }
1055
1056 private void cancelTimerLocked()
1057 {
1058 mHandler.removeCallbacks(mTimeoutTask);
1059 mTimeoutTask.nextState = -1;
1060 }
1061
1062 private class TimeoutTask implements Runnable
1063 {
1064 int nextState; // access should be synchronized on mLocks
1065 public void run()
1066 {
1067 synchronized (mLocks) {
1068 if (mSpew) {
1069 Log.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
1070 }
1071
1072 if (nextState == -1) {
1073 return;
1074 }
1075
1076 mUserState = this.nextState;
1077 setPowerState(this.nextState | mWakeLockState);
1078
1079 long now = SystemClock.uptimeMillis();
1080
1081 switch (this.nextState)
1082 {
1083 case SCREEN_BRIGHT:
1084 if (mDimDelay >= 0) {
1085 setTimeoutLocked(now, SCREEN_DIM);
1086 break;
1087 }
1088 case SCREEN_DIM:
1089 setTimeoutLocked(now, SCREEN_OFF);
1090 break;
1091 }
1092 }
1093 }
1094 }
1095
1096 private void sendNotificationLocked(boolean on, int why)
1097 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001098 if (!on) {
1099 mStillNeedSleepNotification = false;
1100 }
1101
Joe Onorato128e7292009-03-24 18:41:31 -07001102 // Add to the queue.
1103 int index = 0;
1104 while (mBroadcastQueue[index] != -1) {
1105 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Joe Onorato128e7292009-03-24 18:41:31 -07001107 mBroadcastQueue[index] = on ? 1 : 0;
1108 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109
Joe Onorato128e7292009-03-24 18:41:31 -07001110 // If we added it position 2, then there is a pair that can be stripped.
1111 // If we added it position 1 and we're turning the screen off, we can strip
1112 // the pair and do nothing, because the screen is already off, and therefore
1113 // keyguard has already been enabled.
1114 // However, if we added it at position 1 and we're turning it on, then position
1115 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1116 // on, so have to run the queue then.
1117 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001118 // While we're collapsing them, if it's going off, and the new reason
1119 // is more significant than the first, then use the new one.
1120 if (!on && mBroadcastWhy[0] > why) {
1121 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001122 }
1123 mBroadcastQueue[0] = on ? 1 : 0;
1124 mBroadcastQueue[1] = -1;
1125 mBroadcastQueue[2] = -1;
1126 index = 0;
1127 }
1128 if (index == 1 && !on) {
1129 mBroadcastQueue[0] = -1;
1130 mBroadcastQueue[1] = -1;
1131 index = -1;
1132 // The wake lock was being held, but we're not actually going to do any
1133 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001134 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001136 }
1137
1138 // Now send the message.
1139 if (index >= 0) {
1140 // Acquire the broadcast wake lock before changing the power
1141 // state. It will be release after the broadcast is sent.
1142 // We always increment the ref count for each notification in the queue
1143 // and always decrement when that notification is handled.
1144 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001145 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001146 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148 }
1149
1150 private Runnable mNotificationTask = new Runnable()
1151 {
1152 public void run()
1153 {
Joe Onorato128e7292009-03-24 18:41:31 -07001154 while (true) {
1155 int value;
1156 int why;
1157 WindowManagerPolicy policy;
1158 synchronized (mLocks) {
1159 value = mBroadcastQueue[0];
1160 why = mBroadcastWhy[0];
1161 for (int i=0; i<2; i++) {
1162 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1163 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1164 }
1165 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
Joe Onorato128e7292009-03-24 18:41:31 -07001167 if (value == 1) {
1168 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001169
Joe Onorato128e7292009-03-24 18:41:31 -07001170 policy.screenTurnedOn();
1171 try {
1172 ActivityManagerNative.getDefault().wakingUp();
1173 } catch (RemoteException e) {
1174 // ignore it
1175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176
Joe Onorato128e7292009-03-24 18:41:31 -07001177 if (mSpew) {
1178 Log.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
1179 }
1180 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1181 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1182 mScreenOnBroadcastDone, mHandler, 0, null, null);
1183 } else {
1184 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001185 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001186 mBroadcastWakeLock.mCount);
1187 mBroadcastWakeLock.release();
1188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 }
Joe Onorato128e7292009-03-24 18:41:31 -07001191 else if (value == 0) {
1192 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193
Joe Onorato128e7292009-03-24 18:41:31 -07001194 policy.screenTurnedOff(why);
1195 try {
1196 ActivityManagerNative.getDefault().goingToSleep();
1197 } catch (RemoteException e) {
1198 // ignore it.
1199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200
Joe Onorato128e7292009-03-24 18:41:31 -07001201 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1202 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1203 mScreenOffBroadcastDone, mHandler, 0, null, null);
1204 } else {
1205 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001206 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001207 mBroadcastWakeLock.mCount);
1208 mBroadcastWakeLock.release();
1209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 }
Joe Onorato128e7292009-03-24 18:41:31 -07001212 else {
1213 // If we're in this case, then this handler is running for a previous
1214 // paired transaction. mBroadcastWakeLock will already have been released.
1215 break;
1216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218 }
1219 };
1220
1221 long mScreenOnStart;
1222 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1223 public void onReceive(Context context, Intent intent) {
1224 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001225 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1227 mBroadcastWakeLock.release();
1228 }
1229 }
1230 };
1231
1232 long mScreenOffStart;
1233 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1234 public void onReceive(Context context, Intent intent) {
1235 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001236 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1238 mBroadcastWakeLock.release();
1239 }
1240 }
1241 };
1242
1243 void logPointerUpEvent() {
1244 if (LOG_TOUCH_DOWNS) {
1245 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1246 mLastTouchDown = 0;
1247 }
1248 }
1249
1250 void logPointerDownEvent() {
1251 if (LOG_TOUCH_DOWNS) {
1252 // If we are not already timing a down/up sequence
1253 if (mLastTouchDown == 0) {
1254 mLastTouchDown = SystemClock.elapsedRealtime();
1255 mTouchCycles++;
1256 }
1257 }
1258 }
1259
1260 /**
1261 * Prevents the screen from turning on even if it *should* turn on due
1262 * to a subsequent full wake lock being acquired.
1263 * <p>
1264 * This is a temporary hack that allows an activity to "cover up" any
1265 * display glitches that happen during the activity's startup
1266 * sequence. (Specifically, this API was added to work around a
1267 * cosmetic bug in the "incoming call" sequence, where the lock screen
1268 * would flicker briefly before the incoming call UI became visible.)
1269 * TODO: There ought to be a more elegant way of doing this,
1270 * probably by having the PowerManager and ActivityManager
1271 * work together to let apps specify that the screen on/off
1272 * state should be synchronized with the Activity lifecycle.
1273 * <p>
1274 * Note that calling preventScreenOn(true) will NOT turn the screen
1275 * off if it's currently on. (This API only affects *future*
1276 * acquisitions of full wake locks.)
1277 * But calling preventScreenOn(false) WILL turn the screen on if
1278 * it's currently off because of a prior preventScreenOn(true) call.
1279 * <p>
1280 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1281 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1282 * call doesn't occur within 5 seconds, we'll turn the screen back on
1283 * ourselves (and log a warning about it); this prevents a buggy app
1284 * from disabling the screen forever.)
1285 * <p>
1286 * TODO: this feature should really be controlled by a new type of poke
1287 * lock (rather than an IPowerManager call).
1288 */
1289 public void preventScreenOn(boolean prevent) {
1290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1291
1292 synchronized (mLocks) {
1293 if (prevent) {
1294 // First of all, grab a partial wake lock to
1295 // make sure the CPU stays on during the entire
1296 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1297 mPreventScreenOnPartialLock.acquire();
1298
1299 // Post a forceReenableScreen() call (for 5 seconds in the
1300 // future) to make sure the matching preventScreenOn(false) call
1301 // has happened by then.
1302 mHandler.removeCallbacks(mForceReenableScreenTask);
1303 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1304
1305 // Finally, set the flag that prevents the screen from turning on.
1306 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001307 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 mPreventScreenOn = true;
1309 } else {
1310 // (Re)enable the screen.
1311 mPreventScreenOn = false;
1312
1313 // We're "undoing" a the prior preventScreenOn(true) call, so we
1314 // no longer need the 5-second safeguard.
1315 mHandler.removeCallbacks(mForceReenableScreenTask);
1316
1317 // Forcibly turn on the screen if it's supposed to be on. (This
1318 // handles the case where the screen is currently off because of
1319 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001320 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 if (mSpew) {
1322 Log.d(TAG,
1323 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1324 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001325 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 if (err != 0) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001327 Log.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
1329 }
1330
1331 // Release the partial wake lock that we held during the
1332 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1333 mPreventScreenOnPartialLock.release();
1334 }
1335 }
1336 }
1337
1338 public void setScreenBrightnessOverride(int brightness) {
1339 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1340
1341 synchronized (mLocks) {
1342 if (mScreenBrightnessOverride != brightness) {
1343 mScreenBrightnessOverride = brightness;
1344 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1345 }
1346 }
1347 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001348
1349 public void setButtonBrightnessOverride(int brightness) {
1350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1351
1352 synchronized (mLocks) {
1353 if (mButtonBrightnessOverride != brightness) {
1354 mButtonBrightnessOverride = brightness;
1355 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1356 }
1357 }
1358 }
1359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 /**
1361 * Sanity-check that gets called 5 seconds after any call to
1362 * preventScreenOn(true). This ensures that the original call
1363 * is followed promptly by a call to preventScreenOn(false).
1364 */
1365 private void forceReenableScreen() {
1366 // We shouldn't get here at all if mPreventScreenOn is false, since
1367 // we should have already removed any existing
1368 // mForceReenableScreenTask messages...
1369 if (!mPreventScreenOn) {
1370 Log.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
1371 return;
1372 }
1373
1374 // Uh oh. It's been 5 seconds since a call to
1375 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1376 // This means the app that called preventScreenOn(true) is either
1377 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1378 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1379 // crashed before doing so.)
1380
1381 // Log a warning, and forcibly turn the screen back on.
1382 Log.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
1383 + "Forcing the screen back on...");
1384 preventScreenOn(false);
1385 }
1386
1387 private Runnable mForceReenableScreenTask = new Runnable() {
1388 public void run() {
1389 forceReenableScreen();
1390 }
1391 };
1392
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001393 private int setScreenStateLocked(boolean on) {
1394 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001395 if (err == 0) {
1396 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1397 if (mUseSoftwareAutoBrightness) {
1398 enableLightSensor(on);
1399 if (!on) {
1400 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001401 mButtonLight.turnOff();
1402 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001403 // clear current value so we will update based on the new conditions
1404 // when the sensor is reenabled.
1405 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001406 // reset our highest light sensor value when the screen turns off
1407 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001408 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001409 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001410 }
1411 return err;
1412 }
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 private void setPowerState(int state)
1415 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001416 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418
Mike Lockwood435eb642009-12-03 08:40:18 -05001419 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 {
1421 synchronized (mLocks) {
1422 int err;
1423
1424 if (mSpew) {
1425 Log.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
1426 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001427 + " noChangeLights=" + noChangeLights
1428 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
1431 if (noChangeLights) {
1432 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1433 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001434 if (mProximitySensorActive) {
1435 // don't turn on the screen when the proximity sensor lock is held
1436 newState = (newState & ~SCREEN_BRIGHT);
1437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
1439 if (batteryIsLow()) {
1440 newState |= BATTERY_LOW_BIT;
1441 } else {
1442 newState &= ~BATTERY_LOW_BIT;
1443 }
1444 if (newState == mPowerState) {
1445 return;
1446 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001447
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001448 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 newState |= ALL_BRIGHT;
1450 }
1451
1452 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1453 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1454
Mike Lockwood51b84492009-11-16 21:51:18 -05001455 if (mSpew) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 Log.d(TAG, "setPowerState: mPowerState=" + mPowerState
1457 + " newState=" + newState + " noChangeLights=" + noChangeLights);
1458 Log.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
1459 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
1460 Log.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
1461 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
1462 Log.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
1463 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
1464 Log.d(TAG, " oldScreenOn=" + oldScreenOn
1465 + " newScreenOn=" + newScreenOn);
1466 Log.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
1467 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1468 }
1469
1470 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001471 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1473 }
1474
1475 if (oldScreenOn != newScreenOn) {
1476 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001477 // When the user presses the power button, we need to always send out the
1478 // notification that it's going to sleep so the keyguard goes on. But
1479 // we can't do that until the screen fades out, so we don't show the keyguard
1480 // too early.
1481 if (mStillNeedSleepNotification) {
1482 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1483 }
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 // Turn on the screen UNLESS there was a prior
1486 // preventScreenOn(true) request. (Note that the lifetime
1487 // of a single preventScreenOn() request is limited to 5
1488 // seconds to prevent a buggy app from disabling the
1489 // screen forever; see forceReenableScreen().)
1490 boolean reallyTurnScreenOn = true;
1491 if (mSpew) {
1492 Log.d(TAG, "- turning screen on... mPreventScreenOn = "
1493 + mPreventScreenOn);
1494 }
1495
1496 if (mPreventScreenOn) {
1497 if (mSpew) {
1498 Log.d(TAG, "- PREVENTING screen from really turning on!");
1499 }
1500 reallyTurnScreenOn = false;
1501 }
1502 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001503 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 long identity = Binder.clearCallingIdentity();
1505 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001506 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 mBatteryStats.noteScreenOn();
1508 } catch (RemoteException e) {
1509 Log.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
1510 } finally {
1511 Binder.restoreCallingIdentity(identity);
1512 }
1513 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001514 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 // But continue as if we really did turn the screen on...
1516 err = 0;
1517 }
1518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 mLastTouchDown = 0;
1520 mTotalTouchDownTime = 0;
1521 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001522 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 mTotalTouchDownTime, mTouchCycles);
1524 if (err == 0) {
1525 mPowerState |= SCREEN_ON_BIT;
1526 sendNotificationLocked(true, -1);
1527 }
1528 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001529 // cancel light sensor task
1530 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 mScreenOffTime = SystemClock.elapsedRealtime();
1532 long identity = Binder.clearCallingIdentity();
1533 try {
1534 mBatteryStats.noteScreenOff();
1535 } catch (RemoteException e) {
1536 Log.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
1537 } finally {
1538 Binder.restoreCallingIdentity(identity);
1539 }
1540 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001541 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001543 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 err = 0;
1546 mLastTouchDown = 0;
1547 }
1548 }
1549 }
1550 }
1551 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001552
Mike Lockwood435eb642009-12-03 08:40:18 -05001553 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001555 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001557 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001559 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001561 mScreenOffReason = reason;
1562 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
1564 return err;
1565 }
1566
1567 private boolean batteryIsLow() {
1568 return (!mIsPowered &&
1569 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1570 }
1571
The Android Open Source Project10592532009-03-18 17:39:46 -07001572 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001573 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001574 newState = applyButtonState(newState);
1575 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001576 final int realDifference = (newState ^ oldState);
1577 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001579 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 int offMask = 0;
1583 int dimMask = 0;
1584 int onMask = 0;
1585
1586 int preferredBrightness = getPreferredBrightness();
1587 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1590 if (ANIMATE_KEYBOARD_LIGHTS) {
1591 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1592 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001593 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001594 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001596 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001597 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1598 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 startAnimation = true;
1601 } else {
1602 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001603 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001605 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607 }
1608 }
1609
1610 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1611 if (ANIMATE_BUTTON_LIGHTS) {
1612 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1613 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001614 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001615 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001617 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001618 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1619 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621 startAnimation = true;
1622 } else {
1623 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001624 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001626 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628 }
1629 }
1630
1631 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1632 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001633 int nominalCurrentValue = -1;
1634 // If there was an actual difference in the light state, then
1635 // figure out the "ideal" current value based on the previous
1636 // state. Otherwise, this is a change due to the brightness
1637 // override, so we want to animate from whatever the current
1638 // value is.
1639 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1640 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1641 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1642 nominalCurrentValue = preferredBrightness;
1643 break;
1644 case SCREEN_ON_BIT:
1645 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1646 break;
1647 case 0:
1648 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1649 break;
1650 case SCREEN_BRIGHT_BIT:
1651 default:
1652 // not possible
1653 nominalCurrentValue = (int)mScreenBrightness.curValue;
1654 break;
1655 }
Joe Onorato128e7292009-03-24 18:41:31 -07001656 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001657 int brightness = preferredBrightness;
1658 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1660 // dim or turn off backlight, depending on if the screen is on
1661 // the scale is because the brightness ramp isn't linear and this biases
1662 // it so the later parts take longer.
1663 final float scale = 1.5f;
1664 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1665 if (ratio > 1.0f) ratio = 1.0f;
1666 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1668 // was bright
1669 steps = ANIM_STEPS;
1670 } else {
1671 // was dim
1672 steps = (int)(ANIM_STEPS*ratio*scale);
1673 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001674 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if ((oldState & SCREEN_ON_BIT) != 0) {
1677 // was bright
1678 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1679 } else {
1680 // was dim
1681 steps = (int)(ANIM_STEPS*ratio);
1682 }
1683 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1684 // If the "stay on while plugged in" option is
1685 // turned on, then the screen will often not
1686 // automatically turn off while plugged in. To
1687 // still have a sense of when it is inactive, we
1688 // will then count going dim as turning off.
1689 mScreenOffTime = SystemClock.elapsedRealtime();
1690 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001691 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001694 long identity = Binder.clearCallingIdentity();
1695 try {
1696 mBatteryStats.noteScreenBrightness(brightness);
1697 } catch (RemoteException e) {
1698 // Nothing interesting to do.
1699 } finally {
1700 Binder.restoreCallingIdentity(identity);
1701 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001702 if (mScreenBrightness.setTargetLocked(brightness,
1703 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1704 startAnimation = true;
1705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 } else {
1707 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1708 // dim or turn off backlight, depending on if the screen is on
1709 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001710 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001712 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
1714 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001715 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717 }
1718 }
1719
1720 if (startAnimation) {
1721 if (mSpew) {
1722 Log.i(TAG, "Scheduling light animator!");
1723 }
1724 mHandler.removeCallbacks(mLightAnimator);
1725 mHandler.post(mLightAnimator);
1726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 if (offMask != 0) {
1729 //Log.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001730 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732 if (dimMask != 0) {
1733 int brightness = Power.BRIGHTNESS_DIM;
1734 if ((newState & BATTERY_LOW_BIT) != 0 &&
1735 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1736 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1737 }
1738 //Log.i(TAG, "Setting brightess dim " + brightness + ": " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001739 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741 if (onMask != 0) {
1742 int brightness = getPreferredBrightness();
1743 if ((newState & BATTERY_LOW_BIT) != 0 &&
1744 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1745 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1746 }
1747 //Log.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001748 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751
The Android Open Source Project10592532009-03-18 17:39:46 -07001752 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001753 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001754 ? LightsService.BRIGHTNESS_MODE_SENSOR
1755 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001756 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001757 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001758 }
1759 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001760 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001761 }
1762 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001763 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
1766
1767 class BrightnessState {
1768 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 boolean initialized;
1771 int targetValue;
1772 float curValue;
1773 float delta;
1774 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 BrightnessState(int m) {
1777 mask = m;
1778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 public void dump(PrintWriter pw, String prefix) {
1781 pw.println(prefix + "animating=" + animating
1782 + " targetValue=" + targetValue
1783 + " curValue=" + curValue
1784 + " delta=" + delta);
1785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001786
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001787 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001788 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 if (!initialized) {
1790 initialized = true;
1791 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001792 } else if (targetValue == target) {
1793 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001796 delta = (targetValue -
1797 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1798 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001800 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 Log.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001802 + " target=" + targetValue + " delta=" + delta
1803 + " nominalCurrentValue=" + nominalCurrentValue
1804 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
1806 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001807 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 boolean stepLocked() {
1811 if (!animating) return false;
1812 if (false && mSpew) {
1813 Log.i(TAG, "Step target " + mask + ": cur=" + curValue
1814 + " target=" + targetValue + " delta=" + delta);
1815 }
1816 curValue += delta;
1817 int curIntValue = (int)curValue;
1818 boolean more = true;
1819 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001820 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 more = false;
1822 } else if (delta > 0) {
1823 if (curIntValue >= targetValue) {
1824 curValue = curIntValue = targetValue;
1825 more = false;
1826 }
1827 } else {
1828 if (curIntValue <= targetValue) {
1829 curValue = curIntValue = targetValue;
1830 more = false;
1831 }
1832 }
1833 //Log.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001834 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 animating = more;
1836 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001837 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001838 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 }
1841 return more;
1842 }
1843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 private class LightAnimator implements Runnable {
1846 public void run() {
1847 synchronized (mLocks) {
1848 long now = SystemClock.uptimeMillis();
1849 boolean more = mScreenBrightness.stepLocked();
1850 if (mKeyboardBrightness.stepLocked()) {
1851 more = true;
1852 }
1853 if (mButtonBrightness.stepLocked()) {
1854 more = true;
1855 }
1856 if (more) {
1857 mHandler.postAtTime(mLightAnimator, now+(1000/60));
1858 }
1859 }
1860 }
1861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 private int getPreferredBrightness() {
1864 try {
1865 if (mScreenBrightnessOverride >= 0) {
1866 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001867 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05001868 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001869 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
1871 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
1872 SCREEN_BRIGHTNESS);
1873 // Don't let applications turn the screen all the way off
1874 return Math.max(brightness, Power.BRIGHTNESS_DIM);
1875 } catch (SettingNotFoundException snfe) {
1876 return Power.BRIGHTNESS_ON;
1877 }
1878 }
1879
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001880 private int applyButtonState(int state) {
1881 int brightness = -1;
1882 if (mButtonBrightnessOverride >= 0) {
1883 brightness = mButtonBrightnessOverride;
1884 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
1885 brightness = mLightSensorButtonBrightness;
1886 }
1887 if (brightness > 0) {
1888 return state | BUTTON_BRIGHT_BIT;
1889 } else if (brightness == 0) {
1890 return state & ~BUTTON_BRIGHT_BIT;
1891 } else {
1892 return state;
1893 }
1894 }
1895
1896 private int applyKeyboardState(int state) {
1897 int brightness = -1;
1898 if (!mKeyboardVisible) {
1899 brightness = 0;
1900 } else if (mButtonBrightnessOverride >= 0) {
1901 brightness = mButtonBrightnessOverride;
1902 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
1903 brightness = mLightSensorKeyboardBrightness;
1904 }
1905 if (brightness > 0) {
1906 return state | KEYBOARD_BRIGHT_BIT;
1907 } else if (brightness == 0) {
1908 return state & ~KEYBOARD_BRIGHT_BIT;
1909 } else {
1910 return state;
1911 }
1912 }
1913
Charles Mendis322591c2009-10-29 11:06:59 -07001914 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 synchronized (mLocks) {
1916 return (mPowerState & SCREEN_ON_BIT) != 0;
1917 }
1918 }
1919
Charles Mendis322591c2009-10-29 11:06:59 -07001920 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 synchronized (mLocks) {
1922 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
1923 }
1924 }
1925
Mike Lockwood497087e32009-11-08 18:33:03 -05001926 private boolean isScreenTurningOffLocked() {
1927 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
1928 }
1929
Mike Lockwood200b30b2009-09-20 00:23:59 -04001930 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05001931 if (isScreenTurningOffLocked()) {
1932 // cancel animation so userActivity will succeed
1933 mScreenBrightness.animating = false;
1934 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04001935 boolean savedActivityAllowed = mUserActivityAllowed;
1936 mUserActivityAllowed = true;
1937 userActivity(SystemClock.uptimeMillis(), false);
1938 mUserActivityAllowed = savedActivityAllowed;
1939 }
1940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
1942 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1943 userActivity(time, noChangeLights, OTHER_EVENT, force);
1944 }
1945
1946 public void userActivity(long time, boolean noChangeLights) {
1947 userActivity(time, noChangeLights, OTHER_EVENT, false);
1948 }
1949
1950 public void userActivity(long time, boolean noChangeLights, int eventType) {
1951 userActivity(time, noChangeLights, eventType, false);
1952 }
1953
1954 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
1955 //mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1956
1957 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001958 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (false) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001960 Log.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
1962 return;
1963 }
1964
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07001965 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
1966 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
1967 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
1968 if (false) {
1969 Log.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
1970 }
1971 return;
1972 }
1973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 if (false) {
1975 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
1976 Log.d(TAG, "userActivity !!!");//, new RuntimeException());
1977 } else {
1978 Log.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
1979 }
1980 }
1981
1982 synchronized (mLocks) {
1983 if (mSpew) {
1984 Log.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
1985 + " mUserActivityAllowed=" + mUserActivityAllowed
1986 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07001987 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
1988 + " mProximitySensorActive=" + mProximitySensorActive
1989 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Mike Lockwood05067122009-10-27 23:07:25 -04001991 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05001992 if (isScreenTurningOffLocked()) {
Mike Lockwood05067122009-10-27 23:07:25 -04001993 Log.d(TAG, "ignoring user activity while turning off screen");
1994 return;
1995 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001996 // Disable proximity sensor if if user presses power key while we are in the
1997 // "waiting for proximity sensor to go negative" state.
1998 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
1999 mProximitySensorActive = false;
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 if (mLastEventTime <= time || force) {
2002 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002003 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002004 // Only turn on button backlights if a button was pressed
2005 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002006 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2008 } else {
2009 // don't clear button/keyboard backlights when the screen is touched.
2010 mUserState |= SCREEN_BRIGHT;
2011 }
2012
Dianne Hackborn617f8772009-03-31 15:04:46 -07002013 int uid = Binder.getCallingUid();
2014 long ident = Binder.clearCallingIdentity();
2015 try {
2016 mBatteryStats.noteUserActivity(uid, eventType);
2017 } catch (RemoteException e) {
2018 // Ignore
2019 } finally {
2020 Binder.restoreCallingIdentity(ident);
2021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022
Michael Chane96440f2009-05-06 10:27:36 -07002023 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002024 setPowerState(mUserState | mWakeLockState, noChangeLights,
2025 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 setTimeoutLocked(time, SCREEN_BRIGHT);
2027 }
2028 }
2029 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002030
2031 if (mPolicy != null) {
2032 mPolicy.userActivity();
2033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002036 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2037 try {
2038 int i;
2039 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2040 if (sensorValue < mAutoBrightnessLevels[i]) {
2041 break;
2042 }
2043 }
2044 return values[i];
2045 } catch (Exception e) {
2046 // guard against null pointer or index out of bounds errors
2047 Log.e(TAG, "getAutoBrightnessValue", e);
2048 return 255;
2049 }
2050 }
2051
Mike Lockwood20f87d72009-11-05 16:08:51 -05002052 private Runnable mProximityTask = new Runnable() {
2053 public void run() {
2054 synchronized (mLocks) {
2055 if (mProximityPendingValue != -1) {
2056 proximityChangedLocked(mProximityPendingValue == 1);
2057 mProximityPendingValue = -1;
2058 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002059 if (mProximityPartialLock.isHeld()) {
2060 mProximityPartialLock.release();
2061 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002062 }
2063 }
2064 };
2065
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002066 private Runnable mAutoBrightnessTask = new Runnable() {
2067 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002068 synchronized (mLocks) {
2069 int value = (int)mLightSensorPendingValue;
2070 if (value >= 0) {
2071 mLightSensorPendingValue = -1;
2072 lightSensorChangedLocked(value);
2073 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002074 }
2075 }
2076 };
2077
Mike Lockwoodb2865412010-02-02 22:40:33 -05002078 private void dockStateChanged(int state) {
2079 synchronized (mLocks) {
2080 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2081 if (mIsDocked) {
2082 mHighestLightSensorValue = -1;
2083 }
2084 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2085 // force lights recalculation
2086 int value = (int)mLightSensorValue;
2087 mLightSensorValue = -1;
2088 lightSensorChangedLocked(value);
2089 }
2090 }
2091 }
2092
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002093 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002094 if (mDebugLightSensor) {
2095 Log.d(TAG, "lightSensorChangedLocked " + value);
2096 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002097
Mike Lockwoodb2865412010-02-02 22:40:33 -05002098 // do not allow light sensor value to decrease
2099 if (mHighestLightSensorValue < value) {
2100 mHighestLightSensorValue = value;
2101 }
2102
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002103 if (mLightSensorValue != value) {
2104 mLightSensorValue = value;
2105 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002106 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2107 // we only do this if we are undocked, since lighting should be stable when
2108 // stationary in a dock.
2109 int lcdValue = getAutoBrightnessValue(
2110 (mIsDocked ? value : mHighestLightSensorValue),
2111 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002112 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002113 int keyboardValue;
2114 if (mKeyboardVisible) {
2115 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2116 } else {
2117 keyboardValue = 0;
2118 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002119 mLightSensorScreenBrightness = lcdValue;
2120 mLightSensorButtonBrightness = buttonValue;
2121 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002122
2123 if (mDebugLightSensor) {
2124 Log.d(TAG, "lcdValue " + lcdValue);
2125 Log.d(TAG, "buttonValue " + buttonValue);
2126 Log.d(TAG, "keyboardValue " + keyboardValue);
2127 }
2128
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002129 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002130 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002131 if (ANIMATE_SCREEN_LIGHTS) {
2132 if (mScreenBrightness.setTargetLocked(lcdValue,
2133 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2134 (int)mScreenBrightness.curValue)) {
2135 startAnimation = true;
2136 }
2137 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002138 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002139 ? LightsService.BRIGHTNESS_MODE_SENSOR
2140 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002141 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002142 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002143 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002144 if (mButtonBrightnessOverride < 0) {
2145 if (ANIMATE_BUTTON_LIGHTS) {
2146 if (mButtonBrightness.setTargetLocked(buttonValue,
2147 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2148 (int)mButtonBrightness.curValue)) {
2149 startAnimation = true;
2150 }
2151 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002152 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002153 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002154 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002155 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2156 if (ANIMATE_KEYBOARD_LIGHTS) {
2157 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2158 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2159 (int)mKeyboardBrightness.curValue)) {
2160 startAnimation = true;
2161 }
2162 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002163 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002164 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002165 }
2166 if (startAnimation) {
2167 if (mDebugLightSensor) {
2168 Log.i(TAG, "lightSensorChangedLocked scheduling light animator");
2169 }
2170 mHandler.removeCallbacks(mLightAnimator);
2171 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002172 }
2173 }
2174 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002175 }
2176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 /**
2178 * The user requested that we go to sleep (probably with the power button).
2179 * This overrides all wake locks that are held.
2180 */
2181 public void goToSleep(long time)
2182 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002183 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2184 }
2185
2186 /**
2187 * The user requested that we go to sleep (probably with the power button).
2188 * This overrides all wake locks that are held.
2189 */
2190 public void goToSleepWithReason(long time, int reason)
2191 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2193 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002194 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002199 * Reboot the device immediately, passing 'reason' (may be null)
2200 * to the underlying __reboot system call. Should not return.
2201 */
2202 public void reboot(String reason)
2203 {
2204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002205
San Mehat1e512792010-01-07 10:40:29 -08002206 /*
2207 * Manually shutdown the MountService to ensure media is
2208 * put into a safe state.
2209 */
2210 IMountService mSvc = IMountService.Stub.asInterface(
2211 ServiceManager.getService("mount"));
2212
2213 if (mSvc != null) {
2214 try {
2215 mSvc.shutdown();
2216 } catch (Exception e) {
2217 Log.e(TAG, "MountService shutdown failed", e);
2218 }
2219 } else {
2220 Log.w(TAG, "MountService unavailable for shutdown");
2221 }
San Mehat14e69af2010-01-06 14:58:18 -08002222
Doug Zongker50a21f42009-11-19 12:49:53 -08002223 try {
2224 Power.reboot(reason);
2225 } catch (IOException e) {
2226 Log.e(TAG, "reboot failed", e);
2227 }
2228 }
2229
Dan Egnor60d87622009-12-16 16:32:58 -08002230 /**
2231 * Crash the runtime (causing a complete restart of the Android framework).
2232 * Requires REBOOT permission. Mostly for testing. Should not return.
2233 */
2234 public void crash(final String message)
2235 {
2236 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2237 Thread t = new Thread("PowerManagerService.crash()") {
2238 public void run() { throw new RuntimeException(message); }
2239 };
2240 try {
2241 t.start();
2242 t.join();
2243 } catch (InterruptedException e) {
2244 Log.wtf(TAG, e);
2245 }
2246 }
2247
Mike Lockwood435eb642009-12-03 08:40:18 -05002248 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249
2250 if (mLastEventTime <= time) {
2251 mLastEventTime = time;
2252 // cancel all of the wake locks
2253 mWakeLockState = SCREEN_OFF;
2254 int N = mLocks.size();
2255 int numCleared = 0;
2256 for (int i=0; i<N; i++) {
2257 WakeLock wl = mLocks.get(i);
2258 if (isScreenLock(wl.flags)) {
2259 mLocks.get(i).activated = false;
2260 numCleared++;
2261 }
2262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002263 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002264 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002266 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 cancelTimerLocked();
2268 }
2269 }
2270
2271 public long timeSinceScreenOn() {
2272 synchronized (mLocks) {
2273 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2274 return 0;
2275 }
2276 return SystemClock.elapsedRealtime() - mScreenOffTime;
2277 }
2278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002281 synchronized (mLocks) {
2282 if (mSpew) {
2283 Log.d(TAG, "setKeyboardVisibility: " + visible);
2284 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002285 if (mKeyboardVisible != visible) {
2286 mKeyboardVisible = visible;
2287 // don't signal user activity if the screen is off; other code
2288 // will take care of turning on due to a true change to the lid
2289 // switch and synchronized with the lock screen.
2290 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002291 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002292 // force recompute of backlight values
2293 if (mLightSensorValue >= 0) {
2294 int value = (int)mLightSensorValue;
2295 mLightSensorValue = -1;
2296 lightSensorChangedLocked(value);
2297 }
2298 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002299 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2300 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002301 }
2302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
2304
2305 /**
2306 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002307 * When disabling user activity we also reset user power state so the keyguard can reset its
2308 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 */
2310 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002311 if (mSpew) {
2312 Log.d(TAG, "enableUserActivity " + enabled);
2313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 synchronized (mLocks) {
2315 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002316 if (!enabled) {
2317 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2318 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 }
2321 }
2322
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002323 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002324 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002325 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002326 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002327 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002328 // force recompute of backlight values
2329 if (mLightSensorValue >= 0) {
2330 int value = (int)mLightSensorValue;
2331 mLightSensorValue = -1;
2332 lightSensorChangedLocked(value);
2333 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002334 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002335 }
2336 }
2337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 /** Sets the screen off timeouts:
2339 * mKeylightDelay
2340 * mDimDelay
2341 * mScreenOffDelay
2342 * */
2343 private void setScreenOffTimeoutsLocked() {
2344 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002345 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 mDimDelay = -1;
2347 mScreenOffDelay = 0;
2348 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2349 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2350 mDimDelay = -1;
2351 mScreenOffDelay = 0;
2352 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002353 int totalDelay = mScreenOffTimeoutSetting;
2354 if (totalDelay > mMaximumScreenOffTimeout) {
2355 totalDelay = mMaximumScreenOffTimeout;
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2358 if (totalDelay < 0) {
2359 mScreenOffDelay = Integer.MAX_VALUE;
2360 } else if (mKeylightDelay < totalDelay) {
2361 // subtract the time that the keylight delay. This will give us the
2362 // remainder of the time that we need to sleep to get the accurate
2363 // screen off timeout.
2364 mScreenOffDelay = totalDelay - mKeylightDelay;
2365 } else {
2366 mScreenOffDelay = 0;
2367 }
2368 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2369 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2370 mScreenOffDelay = LONG_DIM_TIME;
2371 } else {
2372 mDimDelay = -1;
2373 }
2374 }
2375 if (mSpew) {
2376 Log.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
2377 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2378 + " mDimScreen=" + mDimScreen);
2379 }
2380 }
2381
2382 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002383 * Refreshes cached secure settings. Called once on startup, and
2384 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 */
Doug Zongker43866e02010-01-07 12:09:54 -08002386 private void updateSettingsValues() {
2387 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002389 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 SHORT_KEYLIGHT_DELAY_DEFAULT);
Doug Zongker43866e02010-01-07 12:09:54 -08002391 // Log.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 }
2393
2394 private class LockList extends ArrayList<WakeLock>
2395 {
2396 void addLock(WakeLock wl)
2397 {
2398 int index = getIndex(wl.binder);
2399 if (index < 0) {
2400 this.add(wl);
2401 }
2402 }
2403
2404 WakeLock removeLock(IBinder binder)
2405 {
2406 int index = getIndex(binder);
2407 if (index >= 0) {
2408 return this.remove(index);
2409 } else {
2410 return null;
2411 }
2412 }
2413
2414 int getIndex(IBinder binder)
2415 {
2416 int N = this.size();
2417 for (int i=0; i<N; i++) {
2418 if (this.get(i).binder == binder) {
2419 return i;
2420 }
2421 }
2422 return -1;
2423 }
2424
2425 int gatherState()
2426 {
2427 int result = 0;
2428 int N = this.size();
2429 for (int i=0; i<N; i++) {
2430 WakeLock wl = this.get(i);
2431 if (wl.activated) {
2432 if (isScreenLock(wl.flags)) {
2433 result |= wl.minState;
2434 }
2435 }
2436 }
2437 return result;
2438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002439
Michael Chane96440f2009-05-06 10:27:36 -07002440 int reactivateScreenLocksLocked()
2441 {
2442 int result = 0;
2443 int N = this.size();
2444 for (int i=0; i<N; i++) {
2445 WakeLock wl = this.get(i);
2446 if (isScreenLock(wl.flags)) {
2447 wl.activated = true;
2448 result |= wl.minState;
2449 }
2450 }
2451 return result;
2452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454
2455 void setPolicy(WindowManagerPolicy p) {
2456 synchronized (mLocks) {
2457 mPolicy = p;
2458 mLocks.notifyAll();
2459 }
2460 }
2461
2462 WindowManagerPolicy getPolicyLocked() {
2463 while (mPolicy == null || !mDoneBooting) {
2464 try {
2465 mLocks.wait();
2466 } catch (InterruptedException e) {
2467 // Ignore
2468 }
2469 }
2470 return mPolicy;
2471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002474 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2475 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2476 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002477 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002478 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002479 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002480 }
2481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 synchronized (mLocks) {
2483 Log.d(TAG, "system ready!");
2484 mDoneBooting = true;
Dianne Hackborn617f8772009-03-31 15:04:46 -07002485 long identity = Binder.clearCallingIdentity();
2486 try {
2487 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2488 mBatteryStats.noteScreenOn();
2489 } catch (RemoteException e) {
2490 // Nothing interesting to do.
2491 } finally {
2492 Binder.restoreCallingIdentity(identity);
2493 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002494 }
2495 }
2496
2497 void bootCompleted() {
2498 Log.d(TAG, "bootCompleted");
2499 synchronized (mLocks) {
2500 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2502 updateWakeLockLocked();
2503 mLocks.notifyAll();
2504 }
2505 }
2506
2507 public void monitor() {
2508 synchronized (mLocks) { }
2509 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002510
2511 public int getSupportedWakeLockFlags() {
2512 int result = PowerManager.PARTIAL_WAKE_LOCK
2513 | PowerManager.FULL_WAKE_LOCK
2514 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2515
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002516 if (mProximitySensor != null) {
2517 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2518 }
2519
2520 return result;
2521 }
2522
Mike Lockwood237a2992009-09-15 14:42:16 -04002523 public void setBacklightBrightness(int brightness) {
2524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2525 // Don't let applications turn the screen all the way off
2526 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002527 mLcdLight.setBrightness(brightness);
2528 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2529 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002530 long identity = Binder.clearCallingIdentity();
2531 try {
2532 mBatteryStats.noteScreenBrightness(brightness);
2533 } catch (RemoteException e) {
2534 Log.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2535 } finally {
2536 Binder.restoreCallingIdentity(identity);
2537 }
2538
2539 // update our animation state
2540 if (ANIMATE_SCREEN_LIGHTS) {
2541 mScreenBrightness.curValue = brightness;
2542 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002543 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002544 }
2545 if (ANIMATE_KEYBOARD_LIGHTS) {
2546 mKeyboardBrightness.curValue = brightness;
2547 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002548 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002549 }
2550 if (ANIMATE_BUTTON_LIGHTS) {
2551 mButtonBrightness.curValue = brightness;
2552 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002553 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002554 }
2555 }
2556
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002557 public void setAttentionLight(boolean on, int color) {
2558 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002559 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002560 }
2561
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002562 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002563 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002564 Log.d(TAG, "enableProximityLockLocked");
2565 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002566 if (!mProximitySensorEnabled) {
2567 // clear calling identity so sensor manager battery stats are accurate
2568 long identity = Binder.clearCallingIdentity();
2569 try {
2570 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2571 SensorManager.SENSOR_DELAY_NORMAL);
2572 mProximitySensorEnabled = true;
2573 } finally {
2574 Binder.restoreCallingIdentity(identity);
2575 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002576 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002577 }
2578
2579 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002580 if (mDebugProximitySensor) {
Mike Lockwood36fc3022009-08-25 16:49:06 -07002581 Log.d(TAG, "disableProximityLockLocked");
2582 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002583 if (mProximitySensorEnabled) {
2584 // clear calling identity so sensor manager battery stats are accurate
2585 long identity = Binder.clearCallingIdentity();
2586 try {
2587 mSensorManager.unregisterListener(mProximityListener);
2588 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002589 if (mProximityPartialLock.isHeld()) {
2590 mProximityPartialLock.release();
2591 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002592 mProximitySensorEnabled = false;
2593 } finally {
2594 Binder.restoreCallingIdentity(identity);
2595 }
2596 if (mProximitySensorActive) {
2597 mProximitySensorActive = false;
2598 forceUserActivityLocked();
2599 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002600 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002601 }
2602
Mike Lockwood20f87d72009-11-05 16:08:51 -05002603 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002604 if (mDebugProximitySensor) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002605 Log.d(TAG, "proximityChangedLocked, active: " + active);
2606 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002607 if (!mProximitySensorEnabled) {
2608 Log.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002609 return;
2610 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002611 if (active) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002612 goToSleepLocked(SystemClock.uptimeMillis(),
2613 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002614 mProximitySensorActive = true;
2615 } else {
2616 // proximity sensor negative events trigger as user activity.
2617 // temporarily set mUserActivityAllowed to true so this will work
2618 // even when the keyguard is on.
2619 mProximitySensorActive = false;
2620 forceUserActivityLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002621
2622 if (mProximityWakeLockCount == 0) {
2623 // disable sensor if we have no listeners left after proximity negative
2624 disableProximityLockLocked();
2625 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002626 }
2627 }
2628
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002629 private void enableLightSensor(boolean enable) {
2630 if (mDebugLightSensor) {
2631 Log.d(TAG, "enableLightSensor " + enable);
2632 }
2633 if (mSensorManager != null && mLightSensorEnabled != enable) {
2634 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002635 // clear calling identity so sensor manager battery stats are accurate
2636 long identity = Binder.clearCallingIdentity();
2637 try {
2638 if (enable) {
2639 mSensorManager.registerListener(mLightListener, mLightSensor,
2640 SensorManager.SENSOR_DELAY_NORMAL);
2641 } else {
2642 mSensorManager.unregisterListener(mLightListener);
2643 mHandler.removeCallbacks(mAutoBrightnessTask);
2644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002647 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002648 }
2649 }
2650
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002651 SensorEventListener mProximityListener = new SensorEventListener() {
2652 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002653 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002654 synchronized (mLocks) {
2655 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002656 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2657 mLastProximityEventTime = milliseconds;
2658 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002659 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002660
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002661 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002662 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2663 distance < mProximitySensor.getMaximumRange());
2664
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002665 if (mDebugProximitySensor) {
2666 Log.d(TAG, "mProximityListener.onSensorChanged active: " + active);
2667 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002668 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2669 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2670 mProximityPendingValue = (active ? 1 : 0);
2671 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002672 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002673 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002674 // process the value immediately
2675 mProximityPendingValue = -1;
2676 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002677 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002678
2679 // update mProximityPartialLock state
2680 boolean held = mProximityPartialLock.isHeld();
2681 if (!held && proximityTaskQueued) {
2682 // hold wakelock until mProximityTask runs
2683 mProximityPartialLock.acquire();
2684 } else if (held && !proximityTaskQueued) {
2685 mProximityPartialLock.release();
2686 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002687 }
2688 }
2689
2690 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2691 // ignore
2692 }
2693 };
2694
2695 SensorEventListener mLightListener = new SensorEventListener() {
2696 public void onSensorChanged(SensorEvent event) {
2697 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002698 // ignore light sensor while screen is turning off
2699 if (isScreenTurningOffLocked()) {
2700 return;
2701 }
2702
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002703 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002704 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002705 if (mDebugLightSensor) {
2706 Log.d(TAG, "onSensorChanged: light value: " + value);
2707 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002708 mHandler.removeCallbacks(mAutoBrightnessTask);
2709 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002710 if (mLightSensorValue == -1 ||
2711 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2712 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002713 lightSensorChangedLocked(value);
2714 } else {
2715 // delay processing to debounce the sensor
2716 mLightSensorPendingValue = value;
2717 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2718 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002719 } else {
2720 mLightSensorPendingValue = -1;
2721 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002722 }
2723 }
2724
2725 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2726 // ignore
2727 }
2728 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729}