blob: 496c665e2c9ca7bda1c589c2625dc345d2cface7 [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;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070040import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.BatteryStats;
42import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080043import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.LocalPowerManager;
49import android.os.Power;
50import android.os.PowerManager;
51import android.os.Process;
52import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080053import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings.SettingNotFoundException;
57import android.provider.Settings;
58import android.util.EventLog;
59import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.WindowManagerPolicy;
62import static android.provider.Settings.System.DIM_SCREEN;
63import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050064import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070065import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
67import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
68
69import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080070import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.io.PrintWriter;
72import java.util.ArrayList;
73import java.util.HashMap;
74import java.util.Observable;
75import java.util.Observer;
76
Mike Lockwoodbc706a02009-07-27 13:50:57 -070077class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040078 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80 private static final String TAG = "PowerManagerService";
81 static final String PARTIAL_NAME = "PowerManagerService";
82
83 private static final boolean LOG_PARTIAL_WL = false;
84
85 // Indicates whether touch-down cycles should be logged as part of the
86 // LOG_POWER_SCREEN_STATE log events
87 private static final boolean LOG_TOUCH_DOWNS = true;
88
89 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
90 | PowerManager.SCREEN_DIM_WAKE_LOCK
91 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070092 | PowerManager.FULL_WAKE_LOCK
93 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
95 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080096 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
98 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
99 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
100 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
101
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700102 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500103 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700104
Mike Lockwood20f87d72009-11-05 16:08:51 -0500105 // For debouncing the proximity sensor.
106 private static final int PROXIMITY_SENSOR_DELAY = 1000;
107
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400108 // trigger proximity if distance is less than 5 cm
109 private static final float PROXIMITY_THRESHOLD = 5.0f;
110
Doug Zongker43866e02010-01-07 12:09:54 -0800111 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
113
Amith Yamasani8b619832010-09-22 16:11:59 -0700114 // Default timeout for screen off, if not found in settings database = 15 seconds.
115 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 // flags for setPowerState
118 private static final int SCREEN_ON_BIT = 0x00000001;
119 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
120 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
121 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
122 private static final int BATTERY_LOW_BIT = 0x00000010;
123
124 // values for setPowerState
125
126 // SCREEN_OFF == everything off
127 private static final int SCREEN_OFF = 0x00000000;
128
129 // SCREEN_DIM == screen on, screen backlight dim
130 private static final int SCREEN_DIM = SCREEN_ON_BIT;
131
132 // SCREEN_BRIGHT == screen on, screen backlight bright
133 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
134
135 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
136 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
137
138 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
139 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
140
141 // used for noChangeLights in setPowerState()
142 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
143
144 static final boolean ANIMATE_SCREEN_LIGHTS = true;
145 static final boolean ANIMATE_BUTTON_LIGHTS = false;
146 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400149 // Slower animation for autobrightness changes
150 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 // These magic numbers are the initial state of the LEDs at boot. Ideally
153 // we should read them from the driver, but our current hardware returns 0
154 // for the initial value. Oops!
155 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
156 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
157 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700160 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500163 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500165 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
166 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private int mPartialCount = 0;
168 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500169 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
170 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
171 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private int mUserState;
173 private boolean mKeyboardVisible = false;
174 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500175 private int mProximityWakeLockCount = 0;
176 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700177 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500178 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
179 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800180 private int mScreenOffTimeoutSetting;
181 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private int mKeylightDelay;
183 private int mDimDelay;
184 private int mScreenOffDelay;
185 private int mWakeLockState;
186 private long mLastEventTime = 0;
187 private long mScreenOffTime;
188 private volatile WindowManagerPolicy mPolicy;
189 private final LockList mLocks = new LockList();
190 private Intent mScreenOffIntent;
191 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500192 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500194 private LightsService.Light mLcdLight;
195 private LightsService.Light mButtonLight;
196 private LightsService.Light mKeyboardLight;
197 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private UnsynchronizedWakeLock mBroadcastWakeLock;
199 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
200 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
201 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500202 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private HandlerThread mHandlerThread;
204 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500205 private final TimeoutTask mTimeoutTask = new TimeoutTask();
206 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700208 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700210 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700212 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700213 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 private boolean mIsPowered = false;
215 private IActivityManager mActivityService;
216 private IBatteryStats mBatteryStats;
217 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700218 private SensorManager mSensorManager;
219 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400220 private Sensor mLightSensor;
221 private boolean mLightSensorEnabled;
222 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400223 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500224 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700225 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500226 private int mLightSensorScreenBrightness = -1;
227 private int mLightSensorButtonBrightness = -1;
228 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500230 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private long mNextTimeout;
232 private volatile int mPokey = 0;
233 private volatile boolean mPokeAwakeOnSet = false;
234 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500235 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500236 // mLastScreenOnTime is the time the screen was last turned on
237 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 private boolean mPreventScreenOn;
239 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500240 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400241 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700242 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700243 private int[] mAutoBrightnessLevels;
244 private int[] mLcdBacklightValues;
245 private int[] mButtonBacklightValues;
246 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500247 private int mLightSensorWarmupTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
249 // Used when logging number and duration of touch-down cycles
250 private long mTotalTouchDownTime;
251 private long mLastTouchDown;
252 private int mTouchCycles;
253
254 // could be either static or controllable at runtime
255 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400256 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400257 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700258
259 private native void nativeInit();
260 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
262 /*
263 static PrintStream mLog;
264 static {
265 try {
266 mLog = new PrintStream("/data/power.log");
267 }
268 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800269 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 }
271 }
272 static class Log {
273 static void d(String tag, String s) {
274 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800275 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277 static void i(String tag, String s) {
278 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800279 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 }
281 static void w(String tag, String s) {
282 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 static void e(String tag, String s) {
286 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800287 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 }
289 }
290 */
291
292 /**
293 * This class works around a deadlock between the lock in PowerManager.WakeLock
294 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
295 * mToken object so it can be accessed from any thread, but it calls into here
296 * with its lock held. This class is essentially a reimplementation of
297 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
298 * only call it with our own locks held.
299 */
300 private class UnsynchronizedWakeLock {
301 int mFlags;
302 String mTag;
303 IBinder mToken;
304 int mCount = 0;
305 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500306 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307
308 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
309 mFlags = flags;
310 mTag = tag;
311 mToken = new Binder();
312 mRefCounted = refCounted;
313 }
314
315 public void acquire() {
316 if (!mRefCounted || mCount++ == 0) {
317 long ident = Binder.clearCallingIdentity();
318 try {
319 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700320 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500321 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 } finally {
323 Binder.restoreCallingIdentity(ident);
324 }
325 }
326 }
327
328 public void release() {
329 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500330 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500331 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333 if (mCount < 0) {
334 throw new RuntimeException("WakeLock under-locked " + mTag);
335 }
336 }
337
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500338 public boolean isHeld()
339 {
340 return mHeld;
341 }
342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 public String toString() {
344 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500345 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
347 }
348
349 private final class BatteryReceiver extends BroadcastReceiver {
350 @Override
351 public void onReceive(Context context, Intent intent) {
352 synchronized (mLocks) {
353 boolean wasPowered = mIsPowered;
354 mIsPowered = mBatteryService.isPowered();
355
356 if (mIsPowered != wasPowered) {
357 // update mStayOnWhilePluggedIn wake lock
358 updateWakeLockLocked();
359
360 // treat plugging and unplugging the devices as a user activity.
361 // users find it disconcerting when they unplug the device
362 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500363 // to avoid turning on the screen when unplugging, we only trigger
364 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 // temporarily set mUserActivityAllowed to true so this will work
366 // even when the keyguard is on.
367 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500368 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
369 forceUserActivityLocked();
370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372 }
373 }
374 }
375 }
376
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500377 private final class BootCompletedReceiver extends BroadcastReceiver {
378 @Override
379 public void onReceive(Context context, Intent intent) {
380 bootCompleted();
381 }
382 }
383
Mike Lockwoodb2865412010-02-02 22:40:33 -0500384 private final class DockReceiver extends BroadcastReceiver {
385 @Override
386 public void onReceive(Context context, Intent intent) {
387 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
388 Intent.EXTRA_DOCK_STATE_UNDOCKED);
389 dockStateChanged(state);
390 }
391 }
392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 /**
394 * Set the setting that determines whether the device stays on when plugged in.
395 * The argument is a bit string, with each bit specifying a power source that,
396 * when the device is connected to that source, causes the device to stay on.
397 * See {@link android.os.BatteryManager} for the list of power sources that
398 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
399 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
400 * @param val an {@code int} containing the bits that specify which power sources
401 * should cause the device to stay on.
402 */
403 public void setStayOnSetting(int val) {
404 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
405 Settings.System.putInt(mContext.getContentResolver(),
406 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
407 }
408
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800409 public void setMaximumScreenOffTimeount(int timeMs) {
410 mContext.enforceCallingOrSelfPermission(
411 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
412 synchronized (mLocks) {
413 mMaximumScreenOffTimeout = timeMs;
414 // recalculate everything
415 setScreenOffTimeoutsLocked();
416 }
417 }
418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700420 private int getInt(String name, int defValue) {
421 ContentValues values = mSettings.getValues(name);
422 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
423 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 }
425
426 public void update(Observable o, Object arg) {
427 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700428 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
429 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
430 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 updateWakeLockLocked();
432
Amith Yamasani8b619832010-09-22 16:11:59 -0700433 // SCREEN_OFF_TIMEOUT, default to 15 seconds
434 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
436 // DIM_SCREEN
437 //mDimScreen = getInt(DIM_SCREEN) != 0;
438
Amith Yamasani8b619832010-09-22 16:11:59 -0700439 // SCREEN_BRIGHTNESS_MODE, default to manual
440 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
441 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 // recalculate everything
444 setScreenOffTimeoutsLocked();
445 }
446 }
447 }
448
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700449 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 // Hack to get our uid... should have a func for this.
451 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700452 MY_UID = Process.myUid();
453 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 Binder.restoreCallingIdentity(token);
455
456 // XXX remove this when the kernel doesn't timeout wake locks
457 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
458
459 // assume nothing is on yet
460 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 // Add ourself to the Watchdog monitors.
463 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
465
466 private ContentQueryMap mSettings;
467
Mike Lockwood3a322132009-11-24 00:30:52 -0500468 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700469 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500470 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 mContext = context;
472 mActivityService = activity;
473 mBatteryStats = BatteryStatsService.getService();
474 mBatteryService = battery;
475
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500476 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
477 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
478 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
479 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 mHandlerThread = new HandlerThread("PowerManagerService") {
482 @Override
483 protected void onLooperPrepared() {
484 super.onLooperPrepared();
485 initInThread();
486 }
487 };
488 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 synchronized (mHandlerThread) {
491 while (!mInitComplete) {
492 try {
493 mHandlerThread.wait();
494 } catch (InterruptedException e) {
495 // Ignore
496 }
497 }
498 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700499
500 nativeInit();
501 synchronized (mLocks) {
502 updateNativePowerStateLocked();
503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 void initInThread() {
507 mHandler = new Handler();
508
509 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700510 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
512 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
513 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
514 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
515 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
516 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500517 mProximityPartialLock = new UnsynchronizedWakeLock(
518 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519
520 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
521 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
522 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
523 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
524
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700525 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400526
527 // read settings for auto-brightness
528 mUseSoftwareAutoBrightness = resources.getBoolean(
529 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400530 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700531 mAutoBrightnessLevels = resources.getIntArray(
532 com.android.internal.R.array.config_autoBrightnessLevels);
533 mLcdBacklightValues = resources.getIntArray(
534 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
535 mButtonBacklightValues = resources.getIntArray(
536 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
537 mKeyboardBacklightValues = resources.getIntArray(
538 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500539 mLightSensorWarmupTime = resources.getInteger(
540 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700541 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700542
543 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
545 "(" + Settings.System.NAME + "=?) or ("
546 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700547 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700549 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
550 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 null);
552 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
553 SettingsObserver settingsObserver = new SettingsObserver();
554 mSettings.addObserver(settingsObserver);
555
556 // pretend that the settings changed so we will get their initial state
557 settingsObserver.update(mSettings, null);
558
559 // register for the battery changed notifications
560 IntentFilter filter = new IntentFilter();
561 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
562 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500563 filter = new IntentFilter();
564 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
565 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500566 filter = new IntentFilter();
567 filter.addAction(Intent.ACTION_DOCK_EVENT);
568 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569
Doug Zongker43866e02010-01-07 12:09:54 -0800570 // Listen for secure settings changes
571 mContext.getContentResolver().registerContentObserver(
572 Settings.Secure.CONTENT_URI, true,
573 new ContentObserver(new Handler()) {
574 public void onChange(boolean selfChange) {
575 updateSettingsValues();
576 }
577 });
578 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 synchronized (mHandlerThread) {
581 mInitComplete = true;
582 mHandlerThread.notifyAll();
583 }
584 }
585
586 private class WakeLock implements IBinder.DeathRecipient
587 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700588 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 super();
590 flags = f;
591 binder = b;
592 tag = t;
593 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700594 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 if (u != MY_UID || (
596 !"KEEP_SCREEN_ON_FLAG".equals(tag)
597 && !"KeyInputQueue".equals(tag))) {
598 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
599 ? BatteryStats.WAKE_TYPE_PARTIAL
600 : BatteryStats.WAKE_TYPE_FULL;
601 } else {
602 monitorType = -1;
603 }
604 try {
605 b.linkToDeath(this, 0);
606 } catch (RemoteException e) {
607 binderDied();
608 }
609 }
610 public void binderDied() {
611 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500612 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 }
614 }
615 final int flags;
616 final IBinder binder;
617 final String tag;
618 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400619 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700621 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 boolean activated = true;
623 int minState;
624 }
625
626 private void updateWakeLockLocked() {
627 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
628 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
629 mStayOnWhilePluggedInScreenDimLock.acquire();
630 mStayOnWhilePluggedInPartialLock.acquire();
631 } else {
632 mStayOnWhilePluggedInScreenDimLock.release();
633 mStayOnWhilePluggedInPartialLock.release();
634 }
635 }
636
637 private boolean isScreenLock(int flags)
638 {
639 int n = flags & LOCK_MASK;
640 return n == PowerManager.FULL_WAKE_LOCK
641 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400642 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
643 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700646 void enforceWakeSourcePermission(int uid, int pid) {
647 if (uid == Process.myUid()) {
648 return;
649 }
650 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
651 pid, uid, null);
652 }
653
654 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700656 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700657 if (uid != Process.myUid()) {
658 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
659 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700660 if (ws != null) {
661 enforceWakeSourcePermission(uid, pid);
662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 long ident = Binder.clearCallingIdentity();
664 try {
665 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700666 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
668 } finally {
669 Binder.restoreCallingIdentity(ident);
670 }
671 }
672
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700673 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700674 if (wl.monitorType >= 0) {
675 long origId = Binder.clearCallingIdentity();
676 try {
677 if (ws != null) {
678 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
679 wl.monitorType);
680 } else {
681 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
682 }
683 } catch (RemoteException e) {
684 // Ignore
685 } finally {
686 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700687 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700688 }
689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700691 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700692 if (wl.monitorType >= 0) {
693 long origId = Binder.clearCallingIdentity();
694 try {
695 if (ws != null) {
696 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
697 wl.monitorType);
698 } else {
699 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
700 }
701 } catch (RemoteException e) {
702 // Ignore
703 } finally {
704 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700705 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700706 }
707 }
708
709 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
710 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800712 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700715 if (ws != null && ws.size() == 0) {
716 ws = null;
717 }
718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 int index = mLocks.getIndex(lock);
720 WakeLock wl;
721 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700722 boolean diffsource;
723 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700725 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 switch (wl.flags & LOCK_MASK)
727 {
728 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500729 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400730 wl.minState = SCREEN_BRIGHT;
731 } else {
732 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 break;
735 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
736 wl.minState = SCREEN_BRIGHT;
737 break;
738 case PowerManager.SCREEN_DIM_WAKE_LOCK:
739 wl.minState = SCREEN_DIM;
740 break;
741 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700742 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 break;
744 default:
745 // just log and bail. we're in the server, so don't
746 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800747 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 + " flags=" + flags);
749 return;
750 }
751 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700752 if (ws != null) {
753 wl.ws = new WorkSource(ws);
754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700756 diffsource = false;
757 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 } else {
759 wl = mLocks.get(index);
760 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700761 oldsource = wl.ws;
762 if (oldsource != null) {
763 if (ws == null) {
764 wl.ws = null;
765 diffsource = true;
766 } else {
767 diffsource = oldsource.diff(ws);
768 }
769 } else if (ws != null) {
770 diffsource = true;
771 } else {
772 diffsource = false;
773 }
774 if (diffsource) {
775 wl.ws = new WorkSource(ws);
776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778 if (isScreenLock(flags)) {
779 // if this causes a wakeup, we reactivate all of the locks and
780 // set it to whatever they want. otherwise, we modulate that
781 // by the current state so we never turn it more on than
782 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400783 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
784 mProximityWakeLockCount++;
785 if (mProximityWakeLockCount == 1) {
786 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400789 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
790 int oldWakeLockState = mWakeLockState;
791 mWakeLockState = mLocks.reactivateScreenLocksLocked();
792 if (mSpew) {
793 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
794 + " mWakeLockState=0x"
795 + Integer.toHexString(mWakeLockState)
796 + " previous wakeLockState=0x"
797 + Integer.toHexString(oldWakeLockState));
798 }
799 } else {
800 if (mSpew) {
801 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
802 + " mLocks.gatherState()=0x"
803 + Integer.toHexString(mLocks.gatherState())
804 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
805 }
806 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400808 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 }
811 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
812 if (newlock) {
813 mPartialCount++;
814 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817 }
818 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700821 if (diffsource) {
822 // If the lock sources have changed, need to first release the
823 // old ones.
824 noteStopWakeLocked(wl, oldsource);
825 }
826 if (newlock || diffsource) {
827 noteStartWakeLocked(wl, ws);
828 }
829 }
830
831 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
832 int uid = Binder.getCallingUid();
833 int pid = Binder.getCallingPid();
834 if (ws != null && ws.size() == 0) {
835 ws = null;
836 }
837 if (ws != null) {
838 enforceWakeSourcePermission(uid, pid);
839 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700840 synchronized (mLocks) {
841 int index = mLocks.getIndex(lock);
842 if (index < 0) {
843 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700845 WakeLock wl = mLocks.get(index);
846 WorkSource oldsource = wl.ws;
847 wl.ws = ws != null ? new WorkSource(ws) : null;
848 noteStopWakeLocked(wl, oldsource);
849 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 }
852
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500853 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700854 int uid = Binder.getCallingUid();
855 if (uid != Process.myUid()) {
856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858
859 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500860 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862 }
863
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500864 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 WakeLock wl = mLocks.removeLock(lock);
866 if (wl == null) {
867 return;
868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
873 }
874
875 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400876 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
877 mProximityWakeLockCount--;
878 if (mProximityWakeLockCount == 0) {
879 if (mProximitySensorActive &&
880 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
881 // wait for proximity sensor to go negative before disabling sensor
882 if (mDebugProximitySensor) {
883 Slog.d(TAG, "waiting for proximity sensor to go negative");
884 }
885 } else {
886 disableProximityLockLocked();
887 }
888 }
889 } else {
890 mWakeLockState = mLocks.gatherState();
891 // goes in the middle to reduce flicker
892 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
893 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
894 }
895 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
899 mPartialCount--;
900 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800901 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 Power.releaseWakeLock(PARTIAL_NAME);
903 }
904 }
905 // Unlink the lock from the binder.
906 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907
Dianne Hackborn70be1672010-09-14 11:13:03 -0700908 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 private class PokeLock implements IBinder.DeathRecipient
912 {
913 PokeLock(int p, IBinder b, String t) {
914 super();
915 this.pokey = p;
916 this.binder = b;
917 this.tag = t;
918 try {
919 b.linkToDeath(this, 0);
920 } catch (RemoteException e) {
921 binderDied();
922 }
923 }
924 public void binderDied() {
925 setPokeLock(0, this.binder, this.tag);
926 }
927 int pokey;
928 IBinder binder;
929 String tag;
930 boolean awakeOnSet;
931 }
932
933 public void setPokeLock(int pokey, IBinder token, String tag) {
934 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
935 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800936 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 return;
938 }
939
940 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
941 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
942 + " and POKE_LOCK_MEDIUM_TIMEOUT");
943 }
944
945 synchronized (mLocks) {
946 if (pokey != 0) {
947 PokeLock p = mPokeLocks.get(token);
948 int oldPokey = 0;
949 if (p != null) {
950 oldPokey = p.pokey;
951 p.pokey = pokey;
952 } else {
953 p = new PokeLock(pokey, token, tag);
954 mPokeLocks.put(token, p);
955 }
956 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
957 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
958 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
959 p.awakeOnSet = true;
960 }
961 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700962 PokeLock rLock = mPokeLocks.remove(token);
963 if (rLock != null) {
964 token.unlinkToDeath(rLock, 0);
965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967
968 int oldPokey = mPokey;
969 int cumulative = 0;
970 boolean oldAwakeOnSet = mPokeAwakeOnSet;
971 boolean awakeOnSet = false;
972 for (PokeLock p: mPokeLocks.values()) {
973 cumulative |= p.pokey;
974 if (p.awakeOnSet) {
975 awakeOnSet = true;
976 }
977 }
978 mPokey = cumulative;
979 mPokeAwakeOnSet = awakeOnSet;
980
981 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
982 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 if (oldCumulativeTimeout != newCumulativeTimeout) {
985 setScreenOffTimeoutsLocked();
986 // reset the countdown timer, but use the existing nextState so it doesn't
987 // change anything
988 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
989 }
990 }
991 }
992
993 private static String lockType(int type)
994 {
995 switch (type)
996 {
997 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -0700998 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001000 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001002 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001004 return "PARTIAL_WAKE_LOCK ";
1005 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1006 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 default:
David Brown251faa62009-08-02 22:04:36 -07001008 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
1010 }
1011
1012 private static String dumpPowerState(int state) {
1013 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1014 ? "KEYBOARD_BRIGHT_BIT " : "")
1015 + (((state & SCREEN_BRIGHT_BIT) != 0)
1016 ? "SCREEN_BRIGHT_BIT " : "")
1017 + (((state & SCREEN_ON_BIT) != 0)
1018 ? "SCREEN_ON_BIT " : "")
1019 + (((state & BATTERY_LOW_BIT) != 0)
1020 ? "BATTERY_LOW_BIT " : "");
1021 }
1022
1023 @Override
1024 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1025 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1026 != PackageManager.PERMISSION_GRANTED) {
1027 pw.println("Permission Denial: can't dump PowerManager from from pid="
1028 + Binder.getCallingPid()
1029 + ", uid=" + Binder.getCallingUid());
1030 return;
1031 }
1032
1033 long now = SystemClock.uptimeMillis();
1034
Mike Lockwoodca44df82010-02-25 13:48:49 -05001035 synchronized (mLocks) {
1036 pw.println("Power Manager State:");
1037 pw.println(" mIsPowered=" + mIsPowered
1038 + " mPowerState=" + mPowerState
1039 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1040 + " ms");
1041 pw.println(" mPartialCount=" + mPartialCount);
1042 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1043 pw.println(" mUserState=" + dumpPowerState(mUserState));
1044 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1045 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1046 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1047 + " " + ((mNextTimeout-now)/1000) + "s from now");
1048 pw.println(" mDimScreen=" + mDimScreen
1049 + " mStayOnConditions=" + mStayOnConditions);
1050 pw.println(" mScreenOffReason=" + mScreenOffReason
1051 + " mUserState=" + mUserState);
1052 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1053 + ',' + mBroadcastQueue[2] + "}");
1054 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1055 + ',' + mBroadcastWhy[2] + "}");
1056 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1057 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1058 + " mUserActivityAllowed=" + mUserActivityAllowed);
1059 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1060 + " mScreenOffDelay=" + mScreenOffDelay);
1061 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1062 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1063 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1064 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1065 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1066 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1067 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1068 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1069 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1070 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1071 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1072 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1073 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1074 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1075 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1076 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1077 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1078 pw.println(" mLightSensorValue=" + mLightSensorValue
1079 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
1080 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1081 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1082 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1083 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1084 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1085 mScreenBrightness.dump(pw, " mScreenBrightness: ");
1086 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
1087 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001088
Mike Lockwoodca44df82010-02-25 13:48:49 -05001089 int N = mLocks.size();
1090 pw.println();
1091 pw.println("mLocks.size=" + N + ":");
1092 for (int i=0; i<N; i++) {
1093 WakeLock wl = mLocks.get(i);
1094 String type = lockType(wl.flags & LOCK_MASK);
1095 String acquireCausesWakeup = "";
1096 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1097 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1098 }
1099 String activated = "";
1100 if (wl.activated) {
1101 activated = " activated";
1102 }
1103 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001104 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1105 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001107
1108 pw.println();
1109 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1110 for (PokeLock p: mPokeLocks.values()) {
1111 pw.println(" poke lock '" + p.tag + "':"
1112 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1113 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1114 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1115 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1116 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1117 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1118 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1119 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001121
Mike Lockwoodca44df82010-02-25 13:48:49 -05001122 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125
Joe Onorato7999bff2010-07-24 11:50:05 -04001126 private void setTimeoutLocked(long now, int nextState) {
1127 setTimeoutLocked(now, -1, nextState);
1128 }
1129
1130 // If they gave a timeoutOverride it is the number of seconds
1131 // to screen-off. Figure out where in the countdown cycle we
1132 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001133 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1134 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001135 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001136 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001137 long when = 0;
1138 if (timeoutOverride <= 0) {
1139 switch (nextState)
1140 {
1141 case SCREEN_BRIGHT:
1142 when = now + mKeylightDelay;
1143 break;
1144 case SCREEN_DIM:
1145 if (mDimDelay >= 0) {
1146 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001147 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001148 } else {
1149 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1150 }
1151 case SCREEN_OFF:
1152 synchronized (mLocks) {
1153 when = now + mScreenOffDelay;
1154 }
1155 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001156 default:
1157 when = now;
1158 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001160 } else {
1161 override: {
1162 if (timeoutOverride <= mScreenOffDelay) {
1163 when = now + timeoutOverride;
1164 nextState = SCREEN_OFF;
1165 break override;
1166 }
1167 timeoutOverride -= mScreenOffDelay;
1168
1169 if (mDimDelay >= 0) {
1170 if (timeoutOverride <= mDimDelay) {
1171 when = now + timeoutOverride;
1172 nextState = SCREEN_DIM;
1173 break override;
1174 }
1175 timeoutOverride -= mDimDelay;
1176 }
1177
1178 when = now + timeoutOverride;
1179 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001181 }
1182 if (mSpew) {
1183 Slog.d(TAG, "setTimeoutLocked now=" + now
1184 + " timeoutOverride=" + timeoutOverride
1185 + " nextState=" + nextState + " when=" + when);
1186 }
Joe Onorato797e6882010-08-26 14:46:01 -04001187
1188 mHandler.removeCallbacks(mTimeoutTask);
1189 mTimeoutTask.nextState = nextState;
1190 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1191 ? (originalTimeoutOverride - timeoutOverride)
1192 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001193 mHandler.postAtTime(mTimeoutTask, when);
1194 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 }
1198
1199 private void cancelTimerLocked()
1200 {
1201 mHandler.removeCallbacks(mTimeoutTask);
1202 mTimeoutTask.nextState = -1;
1203 }
1204
1205 private class TimeoutTask implements Runnable
1206 {
1207 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001208 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 public void run()
1210 {
1211 synchronized (mLocks) {
1212 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001213 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215
1216 if (nextState == -1) {
1217 return;
1218 }
1219
1220 mUserState = this.nextState;
1221 setPowerState(this.nextState | mWakeLockState);
1222
1223 long now = SystemClock.uptimeMillis();
1224
1225 switch (this.nextState)
1226 {
1227 case SCREEN_BRIGHT:
1228 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001229 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 break;
1231 }
1232 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001233 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 break;
1235 }
1236 }
1237 }
1238 }
1239
1240 private void sendNotificationLocked(boolean on, int why)
1241 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001242 if (!on) {
1243 mStillNeedSleepNotification = false;
1244 }
1245
Joe Onorato128e7292009-03-24 18:41:31 -07001246 // Add to the queue.
1247 int index = 0;
1248 while (mBroadcastQueue[index] != -1) {
1249 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
Joe Onorato128e7292009-03-24 18:41:31 -07001251 mBroadcastQueue[index] = on ? 1 : 0;
1252 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253
Joe Onorato128e7292009-03-24 18:41:31 -07001254 // If we added it position 2, then there is a pair that can be stripped.
1255 // If we added it position 1 and we're turning the screen off, we can strip
1256 // the pair and do nothing, because the screen is already off, and therefore
1257 // keyguard has already been enabled.
1258 // However, if we added it at position 1 and we're turning it on, then position
1259 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1260 // on, so have to run the queue then.
1261 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001262 // While we're collapsing them, if it's going off, and the new reason
1263 // is more significant than the first, then use the new one.
1264 if (!on && mBroadcastWhy[0] > why) {
1265 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001266 }
1267 mBroadcastQueue[0] = on ? 1 : 0;
1268 mBroadcastQueue[1] = -1;
1269 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001270 mBroadcastWakeLock.release();
1271 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001272 index = 0;
1273 }
1274 if (index == 1 && !on) {
1275 mBroadcastQueue[0] = -1;
1276 mBroadcastQueue[1] = -1;
1277 index = -1;
1278 // The wake lock was being held, but we're not actually going to do any
1279 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001280 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001282 }
1283
1284 // Now send the message.
1285 if (index >= 0) {
1286 // Acquire the broadcast wake lock before changing the power
1287 // state. It will be release after the broadcast is sent.
1288 // We always increment the ref count for each notification in the queue
1289 // and always decrement when that notification is handled.
1290 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001291 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001292 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 }
1294 }
1295
1296 private Runnable mNotificationTask = new Runnable()
1297 {
1298 public void run()
1299 {
Joe Onorato128e7292009-03-24 18:41:31 -07001300 while (true) {
1301 int value;
1302 int why;
1303 WindowManagerPolicy policy;
1304 synchronized (mLocks) {
1305 value = mBroadcastQueue[0];
1306 why = mBroadcastWhy[0];
1307 for (int i=0; i<2; i++) {
1308 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1309 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1310 }
1311 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
Joe Onorato128e7292009-03-24 18:41:31 -07001313 if (value == 1) {
1314 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001315
Joe Onorato128e7292009-03-24 18:41:31 -07001316 policy.screenTurnedOn();
1317 try {
1318 ActivityManagerNative.getDefault().wakingUp();
1319 } catch (RemoteException e) {
1320 // ignore it
1321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322
Joe Onorato128e7292009-03-24 18:41:31 -07001323 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001324 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001325 }
1326 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1327 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1328 mScreenOnBroadcastDone, mHandler, 0, null, null);
1329 } else {
1330 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001331 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001332 mBroadcastWakeLock.mCount);
1333 mBroadcastWakeLock.release();
1334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 }
Joe Onorato128e7292009-03-24 18:41:31 -07001337 else if (value == 0) {
1338 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001339
Joe Onorato128e7292009-03-24 18:41:31 -07001340 policy.screenTurnedOff(why);
1341 try {
1342 ActivityManagerNative.getDefault().goingToSleep();
1343 } catch (RemoteException e) {
1344 // ignore it.
1345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346
Joe Onorato128e7292009-03-24 18:41:31 -07001347 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1348 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1349 mScreenOffBroadcastDone, mHandler, 0, null, null);
1350 } else {
1351 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001352 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001353 mBroadcastWakeLock.mCount);
1354 mBroadcastWakeLock.release();
1355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 }
Joe Onorato128e7292009-03-24 18:41:31 -07001358 else {
1359 // If we're in this case, then this handler is running for a previous
1360 // paired transaction. mBroadcastWakeLock will already have been released.
1361 break;
1362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 }
1365 };
1366
1367 long mScreenOnStart;
1368 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1369 public void onReceive(Context context, Intent intent) {
1370 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001371 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1373 mBroadcastWakeLock.release();
1374 }
1375 }
1376 };
1377
1378 long mScreenOffStart;
1379 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1380 public void onReceive(Context context, Intent intent) {
1381 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001382 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1384 mBroadcastWakeLock.release();
1385 }
1386 }
1387 };
1388
1389 void logPointerUpEvent() {
1390 if (LOG_TOUCH_DOWNS) {
1391 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1392 mLastTouchDown = 0;
1393 }
1394 }
1395
1396 void logPointerDownEvent() {
1397 if (LOG_TOUCH_DOWNS) {
1398 // If we are not already timing a down/up sequence
1399 if (mLastTouchDown == 0) {
1400 mLastTouchDown = SystemClock.elapsedRealtime();
1401 mTouchCycles++;
1402 }
1403 }
1404 }
1405
1406 /**
1407 * Prevents the screen from turning on even if it *should* turn on due
1408 * to a subsequent full wake lock being acquired.
1409 * <p>
1410 * This is a temporary hack that allows an activity to "cover up" any
1411 * display glitches that happen during the activity's startup
1412 * sequence. (Specifically, this API was added to work around a
1413 * cosmetic bug in the "incoming call" sequence, where the lock screen
1414 * would flicker briefly before the incoming call UI became visible.)
1415 * TODO: There ought to be a more elegant way of doing this,
1416 * probably by having the PowerManager and ActivityManager
1417 * work together to let apps specify that the screen on/off
1418 * state should be synchronized with the Activity lifecycle.
1419 * <p>
1420 * Note that calling preventScreenOn(true) will NOT turn the screen
1421 * off if it's currently on. (This API only affects *future*
1422 * acquisitions of full wake locks.)
1423 * But calling preventScreenOn(false) WILL turn the screen on if
1424 * it's currently off because of a prior preventScreenOn(true) call.
1425 * <p>
1426 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1427 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1428 * call doesn't occur within 5 seconds, we'll turn the screen back on
1429 * ourselves (and log a warning about it); this prevents a buggy app
1430 * from disabling the screen forever.)
1431 * <p>
1432 * TODO: this feature should really be controlled by a new type of poke
1433 * lock (rather than an IPowerManager call).
1434 */
1435 public void preventScreenOn(boolean prevent) {
1436 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1437
1438 synchronized (mLocks) {
1439 if (prevent) {
1440 // First of all, grab a partial wake lock to
1441 // make sure the CPU stays on during the entire
1442 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1443 mPreventScreenOnPartialLock.acquire();
1444
1445 // Post a forceReenableScreen() call (for 5 seconds in the
1446 // future) to make sure the matching preventScreenOn(false) call
1447 // has happened by then.
1448 mHandler.removeCallbacks(mForceReenableScreenTask);
1449 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1450
1451 // Finally, set the flag that prevents the screen from turning on.
1452 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001453 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 mPreventScreenOn = true;
1455 } else {
1456 // (Re)enable the screen.
1457 mPreventScreenOn = false;
1458
1459 // We're "undoing" a the prior preventScreenOn(true) call, so we
1460 // no longer need the 5-second safeguard.
1461 mHandler.removeCallbacks(mForceReenableScreenTask);
1462
1463 // Forcibly turn on the screen if it's supposed to be on. (This
1464 // handles the case where the screen is currently off because of
1465 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001466 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001468 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1470 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001471 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001473 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476
1477 // Release the partial wake lock that we held during the
1478 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1479 mPreventScreenOnPartialLock.release();
1480 }
1481 }
1482 }
1483
1484 public void setScreenBrightnessOverride(int brightness) {
1485 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1486
Mike Lockwoodf527c712010-06-10 14:12:33 -04001487 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 synchronized (mLocks) {
1489 if (mScreenBrightnessOverride != brightness) {
1490 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001491 if (isScreenOn()) {
1492 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495 }
1496 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001497
1498 public void setButtonBrightnessOverride(int brightness) {
1499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1500
Mike Lockwoodf527c712010-06-10 14:12:33 -04001501 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001502 synchronized (mLocks) {
1503 if (mButtonBrightnessOverride != brightness) {
1504 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001505 if (isScreenOn()) {
1506 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1507 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001508 }
1509 }
1510 }
1511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 /**
1513 * Sanity-check that gets called 5 seconds after any call to
1514 * preventScreenOn(true). This ensures that the original call
1515 * is followed promptly by a call to preventScreenOn(false).
1516 */
1517 private void forceReenableScreen() {
1518 // We shouldn't get here at all if mPreventScreenOn is false, since
1519 // we should have already removed any existing
1520 // mForceReenableScreenTask messages...
1521 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001522 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 return;
1524 }
1525
1526 // Uh oh. It's been 5 seconds since a call to
1527 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1528 // This means the app that called preventScreenOn(true) is either
1529 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1530 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1531 // crashed before doing so.)
1532
1533 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001534 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 + "Forcing the screen back on...");
1536 preventScreenOn(false);
1537 }
1538
1539 private Runnable mForceReenableScreenTask = new Runnable() {
1540 public void run() {
1541 forceReenableScreen();
1542 }
1543 };
1544
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001545 private int setScreenStateLocked(boolean on) {
1546 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001547 if (err == 0) {
1548 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1549 if (mUseSoftwareAutoBrightness) {
1550 enableLightSensor(on);
1551 if (!on) {
1552 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001553 mButtonLight.turnOff();
1554 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001555 // clear current value so we will update based on the new conditions
1556 // when the sensor is reenabled.
1557 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001558 // reset our highest light sensor value when the screen turns off
1559 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001560 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001561 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001562 }
1563 return err;
1564 }
1565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 private void setPowerState(int state)
1567 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001568 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 }
1570
Mike Lockwood435eb642009-12-03 08:40:18 -05001571 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 {
1573 synchronized (mLocks) {
1574 int err;
1575
1576 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001577 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001579 + " noChangeLights=" + noChangeLights
1580 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
1582
1583 if (noChangeLights) {
1584 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1585 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001586 if (mProximitySensorActive) {
1587 // don't turn on the screen when the proximity sensor lock is held
1588 newState = (newState & ~SCREEN_BRIGHT);
1589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590
1591 if (batteryIsLow()) {
1592 newState |= BATTERY_LOW_BIT;
1593 } else {
1594 newState &= ~BATTERY_LOW_BIT;
1595 }
1596 if (newState == mPowerState) {
1597 return;
1598 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001599
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001600 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 newState |= ALL_BRIGHT;
1602 }
1603
1604 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1605 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1606
Mike Lockwood51b84492009-11-16 21:51:18 -05001607 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001608 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001610 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001612 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001614 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001618 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1620 }
1621
1622 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001623 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1625 }
1626
1627 if (oldScreenOn != newScreenOn) {
1628 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001629 // When the user presses the power button, we need to always send out the
1630 // notification that it's going to sleep so the keyguard goes on. But
1631 // we can't do that until the screen fades out, so we don't show the keyguard
1632 // too early.
1633 if (mStillNeedSleepNotification) {
1634 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1635 }
1636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 // Turn on the screen UNLESS there was a prior
1638 // preventScreenOn(true) request. (Note that the lifetime
1639 // of a single preventScreenOn() request is limited to 5
1640 // seconds to prevent a buggy app from disabling the
1641 // screen forever; see forceReenableScreen().)
1642 boolean reallyTurnScreenOn = true;
1643 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001644 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 + mPreventScreenOn);
1646 }
1647
1648 if (mPreventScreenOn) {
1649 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652 reallyTurnScreenOn = false;
1653 }
1654 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001655 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 long identity = Binder.clearCallingIdentity();
1657 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001658 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 mBatteryStats.noteScreenOn();
1660 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001661 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 } finally {
1663 Binder.restoreCallingIdentity(identity);
1664 }
1665 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001666 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 // But continue as if we really did turn the screen on...
1668 err = 0;
1669 }
1670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 mLastTouchDown = 0;
1672 mTotalTouchDownTime = 0;
1673 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001674 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 mTotalTouchDownTime, mTouchCycles);
1676 if (err == 0) {
1677 mPowerState |= SCREEN_ON_BIT;
1678 sendNotificationLocked(true, -1);
1679 }
1680 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001681 // cancel light sensor task
1682 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 mScreenOffTime = SystemClock.elapsedRealtime();
1684 long identity = Binder.clearCallingIdentity();
1685 try {
1686 mBatteryStats.noteScreenOff();
1687 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 } finally {
1690 Binder.restoreCallingIdentity(identity);
1691 }
1692 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001693 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001695 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 err = 0;
1698 mLastTouchDown = 0;
1699 }
1700 }
1701 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001702
1703 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001706
1707 private void updateNativePowerStateLocked() {
1708 nativeSetPowerState(
1709 (mPowerState & SCREEN_ON_BIT) != 0,
1710 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001712
Mike Lockwood435eb642009-12-03 08:40:18 -05001713 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001715 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001717 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001719 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001721 mScreenOffReason = reason;
1722 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724 return err;
1725 }
1726
1727 private boolean batteryIsLow() {
1728 return (!mIsPowered &&
1729 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1730 }
1731
The Android Open Source Project10592532009-03-18 17:39:46 -07001732 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001733 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001734 newState = applyButtonState(newState);
1735 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001736 final int realDifference = (newState ^ oldState);
1737 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001739 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 int offMask = 0;
1743 int dimMask = 0;
1744 int onMask = 0;
1745
1746 int preferredBrightness = getPreferredBrightness();
1747 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1750 if (ANIMATE_KEYBOARD_LIGHTS) {
1751 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1752 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001753 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001754 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001756 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001757 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1758 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
1760 startAnimation = true;
1761 } else {
1762 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001763 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001765 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 }
1768 }
1769
1770 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1771 if (ANIMATE_BUTTON_LIGHTS) {
1772 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1773 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001774 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001775 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001777 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001778 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1779 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781 startAnimation = true;
1782 } else {
1783 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001784 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001786 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788 }
1789 }
1790
1791 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1792 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001793 int nominalCurrentValue = -1;
1794 // If there was an actual difference in the light state, then
1795 // figure out the "ideal" current value based on the previous
1796 // state. Otherwise, this is a change due to the brightness
1797 // override, so we want to animate from whatever the current
1798 // value is.
1799 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1800 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1801 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1802 nominalCurrentValue = preferredBrightness;
1803 break;
1804 case SCREEN_ON_BIT:
1805 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1806 break;
1807 case 0:
1808 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1809 break;
1810 case SCREEN_BRIGHT_BIT:
1811 default:
1812 // not possible
1813 nominalCurrentValue = (int)mScreenBrightness.curValue;
1814 break;
1815 }
Joe Onorato128e7292009-03-24 18:41:31 -07001816 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001817 int brightness = preferredBrightness;
1818 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1820 // dim or turn off backlight, depending on if the screen is on
1821 // the scale is because the brightness ramp isn't linear and this biases
1822 // it so the later parts take longer.
1823 final float scale = 1.5f;
1824 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1825 if (ratio > 1.0f) ratio = 1.0f;
1826 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1828 // was bright
1829 steps = ANIM_STEPS;
1830 } else {
1831 // was dim
1832 steps = (int)(ANIM_STEPS*ratio*scale);
1833 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001834 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 if ((oldState & SCREEN_ON_BIT) != 0) {
1837 // was bright
1838 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1839 } else {
1840 // was dim
1841 steps = (int)(ANIM_STEPS*ratio);
1842 }
1843 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1844 // If the "stay on while plugged in" option is
1845 // turned on, then the screen will often not
1846 // automatically turn off while plugged in. To
1847 // still have a sense of when it is inactive, we
1848 // will then count going dim as turning off.
1849 mScreenOffTime = SystemClock.elapsedRealtime();
1850 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001851 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001854 long identity = Binder.clearCallingIdentity();
1855 try {
1856 mBatteryStats.noteScreenBrightness(brightness);
1857 } catch (RemoteException e) {
1858 // Nothing interesting to do.
1859 } finally {
1860 Binder.restoreCallingIdentity(identity);
1861 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001862 if (mScreenBrightness.setTargetLocked(brightness,
1863 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1864 startAnimation = true;
1865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 } else {
1867 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1868 // dim or turn off backlight, depending on if the screen is on
1869 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001870 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001872 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001875 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877 }
1878 }
1879
1880 if (startAnimation) {
1881 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001882 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884 mHandler.removeCallbacks(mLightAnimator);
1885 mHandler.post(mLightAnimator);
1886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001889 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001890 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892 if (dimMask != 0) {
1893 int brightness = Power.BRIGHTNESS_DIM;
1894 if ((newState & BATTERY_LOW_BIT) != 0 &&
1895 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1896 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1897 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001898 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001899 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901 if (onMask != 0) {
1902 int brightness = getPreferredBrightness();
1903 if ((newState & BATTERY_LOW_BIT) != 0 &&
1904 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1905 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1906 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001907 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001908 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911
The Android Open Source Project10592532009-03-18 17:39:46 -07001912 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001913 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001914 ? LightsService.BRIGHTNESS_MODE_SENSOR
1915 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001916 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001917 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001918 }
1919 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001920 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001921 }
1922 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001923 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 }
1926
1927 class BrightnessState {
1928 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 boolean initialized;
1931 int targetValue;
1932 float curValue;
1933 float delta;
1934 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 BrightnessState(int m) {
1937 mask = m;
1938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 public void dump(PrintWriter pw, String prefix) {
1941 pw.println(prefix + "animating=" + animating
1942 + " targetValue=" + targetValue
1943 + " curValue=" + curValue
1944 + " delta=" + delta);
1945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001946
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001947 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001948 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 if (!initialized) {
1950 initialized = true;
1951 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001952 } else if (targetValue == target) {
1953 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001956 delta = (targetValue -
1957 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1958 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001960 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001961 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001962 + " target=" + targetValue + " delta=" + delta
1963 + " nominalCurrentValue=" + nominalCurrentValue
1964 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001967 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 boolean stepLocked() {
1971 if (!animating) return false;
1972 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001973 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 + " target=" + targetValue + " delta=" + delta);
1975 }
1976 curValue += delta;
1977 int curIntValue = (int)curValue;
1978 boolean more = true;
1979 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001980 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 more = false;
1982 } else if (delta > 0) {
1983 if (curIntValue >= targetValue) {
1984 curValue = curIntValue = targetValue;
1985 more = false;
1986 }
1987 } else {
1988 if (curIntValue <= targetValue) {
1989 curValue = curIntValue = targetValue;
1990 more = false;
1991 }
1992 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001993 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001994 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 animating = more;
1996 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001997 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001998 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000 }
2001 return more;
2002 }
2003 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 private class LightAnimator implements Runnable {
2006 public void run() {
2007 synchronized (mLocks) {
2008 long now = SystemClock.uptimeMillis();
2009 boolean more = mScreenBrightness.stepLocked();
2010 if (mKeyboardBrightness.stepLocked()) {
2011 more = true;
2012 }
2013 if (mButtonBrightness.stepLocked()) {
2014 more = true;
2015 }
2016 if (more) {
2017 mHandler.postAtTime(mLightAnimator, now+(1000/60));
2018 }
2019 }
2020 }
2021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 private int getPreferredBrightness() {
2024 try {
2025 if (mScreenBrightnessOverride >= 0) {
2026 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002027 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002028 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002029 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2032 SCREEN_BRIGHTNESS);
2033 // Don't let applications turn the screen all the way off
2034 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2035 } catch (SettingNotFoundException snfe) {
2036 return Power.BRIGHTNESS_ON;
2037 }
2038 }
2039
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002040 private int applyButtonState(int state) {
2041 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002042 if ((state & BATTERY_LOW_BIT) != 0) {
2043 // do not override brightness if the battery is low
2044 return state;
2045 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002046 if (mButtonBrightnessOverride >= 0) {
2047 brightness = mButtonBrightnessOverride;
2048 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2049 brightness = mLightSensorButtonBrightness;
2050 }
2051 if (brightness > 0) {
2052 return state | BUTTON_BRIGHT_BIT;
2053 } else if (brightness == 0) {
2054 return state & ~BUTTON_BRIGHT_BIT;
2055 } else {
2056 return state;
2057 }
2058 }
2059
2060 private int applyKeyboardState(int state) {
2061 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002062 if ((state & BATTERY_LOW_BIT) != 0) {
2063 // do not override brightness if the battery is low
2064 return state;
2065 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002066 if (!mKeyboardVisible) {
2067 brightness = 0;
2068 } else if (mButtonBrightnessOverride >= 0) {
2069 brightness = mButtonBrightnessOverride;
2070 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2071 brightness = mLightSensorKeyboardBrightness;
2072 }
2073 if (brightness > 0) {
2074 return state | KEYBOARD_BRIGHT_BIT;
2075 } else if (brightness == 0) {
2076 return state & ~KEYBOARD_BRIGHT_BIT;
2077 } else {
2078 return state;
2079 }
2080 }
2081
Charles Mendis322591c2009-10-29 11:06:59 -07002082 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 synchronized (mLocks) {
2084 return (mPowerState & SCREEN_ON_BIT) != 0;
2085 }
2086 }
2087
Charles Mendis322591c2009-10-29 11:06:59 -07002088 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 synchronized (mLocks) {
2090 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2091 }
2092 }
2093
Mike Lockwood497087e32009-11-08 18:33:03 -05002094 private boolean isScreenTurningOffLocked() {
2095 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2096 }
2097
Mike Lockwood200b30b2009-09-20 00:23:59 -04002098 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002099 if (isScreenTurningOffLocked()) {
2100 // cancel animation so userActivity will succeed
2101 mScreenBrightness.animating = false;
2102 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002103 boolean savedActivityAllowed = mUserActivityAllowed;
2104 mUserActivityAllowed = true;
2105 userActivity(SystemClock.uptimeMillis(), false);
2106 mUserActivityAllowed = savedActivityAllowed;
2107 }
2108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002111 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
2113
2114 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato0c32c092010-09-29 10:20:59 -07002115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002116 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118
2119 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002120 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122
2123 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002124 userActivity(time, -1, noChangeLights, eventType, force);
2125 }
2126
2127 /*
2128 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2129 * on with user activity. Don't use this function.
2130 */
2131 public void clearUserActivityTimeout(long now, long timeout) {
2132 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2133 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2134 userActivity(now, timeout, false, OTHER_EVENT, false);
2135 }
2136
2137 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2138 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139
2140 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002141 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002143 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 }
2145 return;
2146 }
2147
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002148 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2149 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2150 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2151 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002152 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002153 }
2154 return;
2155 }
2156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 if (false) {
2158 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002159 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002161 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163 }
2164
2165 synchronized (mLocks) {
2166 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002167 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 + " mUserActivityAllowed=" + mUserActivityAllowed
2169 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002170 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2171 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002172 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002173 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
Mike Lockwood05067122009-10-27 23:07:25 -04002175 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002176 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002177 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002178 return;
2179 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002180 // Disable proximity sensor if if user presses power key while we are in the
2181 // "waiting for proximity sensor to go negative" state.
2182 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2183 mProximitySensorActive = false;
2184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 if (mLastEventTime <= time || force) {
2186 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002187 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002188 // Only turn on button backlights if a button was pressed
2189 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002190 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2192 } else {
2193 // don't clear button/keyboard backlights when the screen is touched.
2194 mUserState |= SCREEN_BRIGHT;
2195 }
2196
Dianne Hackborn617f8772009-03-31 15:04:46 -07002197 int uid = Binder.getCallingUid();
2198 long ident = Binder.clearCallingIdentity();
2199 try {
2200 mBatteryStats.noteUserActivity(uid, eventType);
2201 } catch (RemoteException e) {
2202 // Ignore
2203 } finally {
2204 Binder.restoreCallingIdentity(ident);
2205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002206
Michael Chane96440f2009-05-06 10:27:36 -07002207 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002208 setPowerState(mUserState | mWakeLockState, noChangeLights,
2209 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002210 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 }
2212 }
2213 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002214
2215 if (mPolicy != null) {
2216 mPolicy.userActivity();
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002220 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2221 try {
2222 int i;
2223 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2224 if (sensorValue < mAutoBrightnessLevels[i]) {
2225 break;
2226 }
2227 }
2228 return values[i];
2229 } catch (Exception e) {
2230 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002231 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002232 return 255;
2233 }
2234 }
2235
Mike Lockwood20f87d72009-11-05 16:08:51 -05002236 private Runnable mProximityTask = new Runnable() {
2237 public void run() {
2238 synchronized (mLocks) {
2239 if (mProximityPendingValue != -1) {
2240 proximityChangedLocked(mProximityPendingValue == 1);
2241 mProximityPendingValue = -1;
2242 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002243 if (mProximityPartialLock.isHeld()) {
2244 mProximityPartialLock.release();
2245 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002246 }
2247 }
2248 };
2249
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002250 private Runnable mAutoBrightnessTask = new Runnable() {
2251 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002252 synchronized (mLocks) {
2253 int value = (int)mLightSensorPendingValue;
2254 if (value >= 0) {
2255 mLightSensorPendingValue = -1;
2256 lightSensorChangedLocked(value);
2257 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002258 }
2259 }
2260 };
2261
Mike Lockwoodb2865412010-02-02 22:40:33 -05002262 private void dockStateChanged(int state) {
2263 synchronized (mLocks) {
2264 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2265 if (mIsDocked) {
2266 mHighestLightSensorValue = -1;
2267 }
2268 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2269 // force lights recalculation
2270 int value = (int)mLightSensorValue;
2271 mLightSensorValue = -1;
2272 lightSensorChangedLocked(value);
2273 }
2274 }
2275 }
2276
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002277 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002278 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002279 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002280 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002281
Mike Lockwoodb2865412010-02-02 22:40:33 -05002282 // do not allow light sensor value to decrease
2283 if (mHighestLightSensorValue < value) {
2284 mHighestLightSensorValue = value;
2285 }
2286
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002287 if (mLightSensorValue != value) {
2288 mLightSensorValue = value;
2289 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002290 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2291 // we only do this if we are undocked, since lighting should be stable when
2292 // stationary in a dock.
2293 int lcdValue = getAutoBrightnessValue(
2294 (mIsDocked ? value : mHighestLightSensorValue),
2295 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002296 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002297 int keyboardValue;
2298 if (mKeyboardVisible) {
2299 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2300 } else {
2301 keyboardValue = 0;
2302 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002303 mLightSensorScreenBrightness = lcdValue;
2304 mLightSensorButtonBrightness = buttonValue;
2305 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002306
2307 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002308 Slog.d(TAG, "lcdValue " + lcdValue);
2309 Slog.d(TAG, "buttonValue " + buttonValue);
2310 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002311 }
2312
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002313 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002314 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002315 if (ANIMATE_SCREEN_LIGHTS) {
2316 if (mScreenBrightness.setTargetLocked(lcdValue,
2317 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2318 (int)mScreenBrightness.curValue)) {
2319 startAnimation = true;
2320 }
2321 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002322 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002323 ? LightsService.BRIGHTNESS_MODE_SENSOR
2324 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002325 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002326 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002327 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002328 if (mButtonBrightnessOverride < 0) {
2329 if (ANIMATE_BUTTON_LIGHTS) {
2330 if (mButtonBrightness.setTargetLocked(buttonValue,
2331 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2332 (int)mButtonBrightness.curValue)) {
2333 startAnimation = true;
2334 }
2335 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002336 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002337 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002338 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002339 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2340 if (ANIMATE_KEYBOARD_LIGHTS) {
2341 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2342 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2343 (int)mKeyboardBrightness.curValue)) {
2344 startAnimation = true;
2345 }
2346 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002347 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002348 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002349 }
2350 if (startAnimation) {
2351 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002352 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002353 }
2354 mHandler.removeCallbacks(mLightAnimator);
2355 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002356 }
2357 }
2358 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002359 }
2360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 /**
2362 * The user requested that we go to sleep (probably with the power button).
2363 * This overrides all wake locks that are held.
2364 */
2365 public void goToSleep(long time)
2366 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002367 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2368 }
2369
2370 /**
2371 * The user requested that we go to sleep (probably with the power button).
2372 * This overrides all wake locks that are held.
2373 */
2374 public void goToSleepWithReason(long time, int reason)
2375 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2377 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002378 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002383 * Reboot the device immediately, passing 'reason' (may be null)
2384 * to the underlying __reboot system call. Should not return.
2385 */
2386 public void reboot(String reason)
2387 {
2388 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002389
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002390 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2391 throw new IllegalStateException("Too early to call reboot()");
2392 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002393
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002394 final String finalReason = reason;
2395 Runnable runnable = new Runnable() {
2396 public void run() {
2397 synchronized (this) {
2398 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002399 }
2400
San Mehat1e512792010-01-07 10:40:29 -08002401 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002402 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002403 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002404 mHandler.post(runnable);
2405
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002406 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002407 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002408 while (true) {
2409 try {
2410 runnable.wait();
2411 } catch (InterruptedException e) {
2412 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002413 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002414 }
2415 }
2416
Dan Egnor60d87622009-12-16 16:32:58 -08002417 /**
2418 * Crash the runtime (causing a complete restart of the Android framework).
2419 * Requires REBOOT permission. Mostly for testing. Should not return.
2420 */
2421 public void crash(final String message)
2422 {
2423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2424 Thread t = new Thread("PowerManagerService.crash()") {
2425 public void run() { throw new RuntimeException(message); }
2426 };
2427 try {
2428 t.start();
2429 t.join();
2430 } catch (InterruptedException e) {
2431 Log.wtf(TAG, e);
2432 }
2433 }
2434
Mike Lockwood435eb642009-12-03 08:40:18 -05002435 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436
2437 if (mLastEventTime <= time) {
2438 mLastEventTime = time;
2439 // cancel all of the wake locks
2440 mWakeLockState = SCREEN_OFF;
2441 int N = mLocks.size();
2442 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002443 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 for (int i=0; i<N; i++) {
2445 WakeLock wl = mLocks.get(i);
2446 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002447 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2448 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2449 proxLock = true;
2450 } else {
2451 mLocks.get(i).activated = false;
2452 numCleared++;
2453 }
2454 }
2455 }
2456 if (!proxLock) {
2457 mProxIgnoredBecauseScreenTurnedOff = true;
2458 if (mDebugProximitySensor) {
2459 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 }
2461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002462 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002463 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002465 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 cancelTimerLocked();
2467 }
2468 }
2469
2470 public long timeSinceScreenOn() {
2471 synchronized (mLocks) {
2472 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2473 return 0;
2474 }
2475 return SystemClock.elapsedRealtime() - mScreenOffTime;
2476 }
2477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002480 synchronized (mLocks) {
2481 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002482 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002483 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002484 if (mKeyboardVisible != visible) {
2485 mKeyboardVisible = visible;
2486 // don't signal user activity if the screen is off; other code
2487 // will take care of turning on due to a true change to the lid
2488 // switch and synchronized with the lock screen.
2489 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002490 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002491 // force recompute of backlight values
2492 if (mLightSensorValue >= 0) {
2493 int value = (int)mLightSensorValue;
2494 mLightSensorValue = -1;
2495 lightSensorChangedLocked(value);
2496 }
2497 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002498 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2499 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002500 }
2501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503
2504 /**
2505 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002506 * When disabling user activity we also reset user power state so the keyguard can reset its
2507 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 */
2509 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002510 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002511 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 synchronized (mLocks) {
2514 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002515 if (!enabled) {
2516 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2517 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 }
2520 }
2521
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002522 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002523 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002524 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002525 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002526 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002527 // force recompute of backlight values
2528 if (mLightSensorValue >= 0) {
2529 int value = (int)mLightSensorValue;
2530 mLightSensorValue = -1;
2531 lightSensorChangedLocked(value);
2532 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002533 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002534 }
2535 }
2536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 /** Sets the screen off timeouts:
2538 * mKeylightDelay
2539 * mDimDelay
2540 * mScreenOffDelay
2541 * */
2542 private void setScreenOffTimeoutsLocked() {
2543 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002544 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 mDimDelay = -1;
2546 mScreenOffDelay = 0;
2547 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2548 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2549 mDimDelay = -1;
2550 mScreenOffDelay = 0;
2551 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002552 int totalDelay = mScreenOffTimeoutSetting;
2553 if (totalDelay > mMaximumScreenOffTimeout) {
2554 totalDelay = mMaximumScreenOffTimeout;
2555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2557 if (totalDelay < 0) {
2558 mScreenOffDelay = Integer.MAX_VALUE;
2559 } else if (mKeylightDelay < totalDelay) {
2560 // subtract the time that the keylight delay. This will give us the
2561 // remainder of the time that we need to sleep to get the accurate
2562 // screen off timeout.
2563 mScreenOffDelay = totalDelay - mKeylightDelay;
2564 } else {
2565 mScreenOffDelay = 0;
2566 }
2567 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2568 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2569 mScreenOffDelay = LONG_DIM_TIME;
2570 } else {
2571 mDimDelay = -1;
2572 }
2573 }
2574 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002575 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2577 + " mDimScreen=" + mDimScreen);
2578 }
2579 }
2580
2581 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002582 * Refreshes cached secure settings. Called once on startup, and
2583 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 */
Doug Zongker43866e02010-01-07 12:09:54 -08002585 private void updateSettingsValues() {
2586 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002588 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002590 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592
2593 private class LockList extends ArrayList<WakeLock>
2594 {
2595 void addLock(WakeLock wl)
2596 {
2597 int index = getIndex(wl.binder);
2598 if (index < 0) {
2599 this.add(wl);
2600 }
2601 }
2602
2603 WakeLock removeLock(IBinder binder)
2604 {
2605 int index = getIndex(binder);
2606 if (index >= 0) {
2607 return this.remove(index);
2608 } else {
2609 return null;
2610 }
2611 }
2612
2613 int getIndex(IBinder binder)
2614 {
2615 int N = this.size();
2616 for (int i=0; i<N; i++) {
2617 if (this.get(i).binder == binder) {
2618 return i;
2619 }
2620 }
2621 return -1;
2622 }
2623
2624 int gatherState()
2625 {
2626 int result = 0;
2627 int N = this.size();
2628 for (int i=0; i<N; i++) {
2629 WakeLock wl = this.get(i);
2630 if (wl.activated) {
2631 if (isScreenLock(wl.flags)) {
2632 result |= wl.minState;
2633 }
2634 }
2635 }
2636 return result;
2637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002638
Michael Chane96440f2009-05-06 10:27:36 -07002639 int reactivateScreenLocksLocked()
2640 {
2641 int result = 0;
2642 int N = this.size();
2643 for (int i=0; i<N; i++) {
2644 WakeLock wl = this.get(i);
2645 if (isScreenLock(wl.flags)) {
2646 wl.activated = true;
2647 result |= wl.minState;
2648 }
2649 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002650 if (mDebugProximitySensor) {
2651 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2652 + mProxIgnoredBecauseScreenTurnedOff);
2653 }
2654 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002655 return result;
2656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 }
2658
2659 void setPolicy(WindowManagerPolicy p) {
2660 synchronized (mLocks) {
2661 mPolicy = p;
2662 mLocks.notifyAll();
2663 }
2664 }
2665
2666 WindowManagerPolicy getPolicyLocked() {
2667 while (mPolicy == null || !mDoneBooting) {
2668 try {
2669 mLocks.wait();
2670 } catch (InterruptedException e) {
2671 // Ignore
2672 }
2673 }
2674 return mPolicy;
2675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002678 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2679 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2680 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002681 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002682 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002683 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002684 }
2685
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002686 // wait until sensors are enabled before turning on screen.
2687 // some devices will not activate the light sensor properly on boot
2688 // unless we do this.
2689 if (mUseSoftwareAutoBrightness) {
2690 // turn the screen on
2691 setPowerState(SCREEN_BRIGHT);
2692 } else {
2693 // turn everything on
2694 setPowerState(ALL_BRIGHT);
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002698 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002700
Dianne Hackborn617f8772009-03-31 15:04:46 -07002701 long identity = Binder.clearCallingIdentity();
2702 try {
2703 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2704 mBatteryStats.noteScreenOn();
2705 } catch (RemoteException e) {
2706 // Nothing interesting to do.
2707 } finally {
2708 Binder.restoreCallingIdentity(identity);
2709 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002710 }
2711 }
2712
2713 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002714 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002715 synchronized (mLocks) {
2716 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2718 updateWakeLockLocked();
2719 mLocks.notifyAll();
2720 }
2721 }
2722
2723 public void monitor() {
2724 synchronized (mLocks) { }
2725 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002726
2727 public int getSupportedWakeLockFlags() {
2728 int result = PowerManager.PARTIAL_WAKE_LOCK
2729 | PowerManager.FULL_WAKE_LOCK
2730 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2731
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002732 if (mProximitySensor != null) {
2733 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2734 }
2735
2736 return result;
2737 }
2738
Mike Lockwood237a2992009-09-15 14:42:16 -04002739 public void setBacklightBrightness(int brightness) {
2740 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2741 // Don't let applications turn the screen all the way off
2742 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002743 mLcdLight.setBrightness(brightness);
2744 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2745 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002746 long identity = Binder.clearCallingIdentity();
2747 try {
2748 mBatteryStats.noteScreenBrightness(brightness);
2749 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002750 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002751 } finally {
2752 Binder.restoreCallingIdentity(identity);
2753 }
2754
2755 // update our animation state
2756 if (ANIMATE_SCREEN_LIGHTS) {
2757 mScreenBrightness.curValue = brightness;
2758 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002759 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002760 }
2761 if (ANIMATE_KEYBOARD_LIGHTS) {
2762 mKeyboardBrightness.curValue = brightness;
2763 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002764 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002765 }
2766 if (ANIMATE_BUTTON_LIGHTS) {
2767 mButtonBrightness.curValue = brightness;
2768 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002769 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002770 }
2771 }
2772
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002773 public void setAttentionLight(boolean on, int color) {
2774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002775 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002776 }
2777
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002778 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002779 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002780 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002781 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002782 if (!mProximitySensorEnabled) {
2783 // clear calling identity so sensor manager battery stats are accurate
2784 long identity = Binder.clearCallingIdentity();
2785 try {
2786 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2787 SensorManager.SENSOR_DELAY_NORMAL);
2788 mProximitySensorEnabled = true;
2789 } finally {
2790 Binder.restoreCallingIdentity(identity);
2791 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002792 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002793 }
2794
2795 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002796 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002797 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002798 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002799 if (mProximitySensorEnabled) {
2800 // clear calling identity so sensor manager battery stats are accurate
2801 long identity = Binder.clearCallingIdentity();
2802 try {
2803 mSensorManager.unregisterListener(mProximityListener);
2804 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002805 if (mProximityPartialLock.isHeld()) {
2806 mProximityPartialLock.release();
2807 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002808 mProximitySensorEnabled = false;
2809 } finally {
2810 Binder.restoreCallingIdentity(identity);
2811 }
2812 if (mProximitySensorActive) {
2813 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002814 if (mDebugProximitySensor) {
2815 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2816 + mProxIgnoredBecauseScreenTurnedOff);
2817 }
2818 if (!mProxIgnoredBecauseScreenTurnedOff) {
2819 forceUserActivityLocked();
2820 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002821 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002822 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002823 }
2824
Mike Lockwood20f87d72009-11-05 16:08:51 -05002825 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002826 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002827 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002828 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002829 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002830 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002831 return;
2832 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002833 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002834 if (mDebugProximitySensor) {
2835 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2836 + mProxIgnoredBecauseScreenTurnedOff);
2837 }
2838 if (!mProxIgnoredBecauseScreenTurnedOff) {
2839 goToSleepLocked(SystemClock.uptimeMillis(),
2840 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2841 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002842 mProximitySensorActive = true;
2843 } else {
2844 // proximity sensor negative events trigger as user activity.
2845 // temporarily set mUserActivityAllowed to true so this will work
2846 // even when the keyguard is on.
2847 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002848 if (mDebugProximitySensor) {
2849 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2850 + mProxIgnoredBecauseScreenTurnedOff);
2851 }
2852 if (!mProxIgnoredBecauseScreenTurnedOff) {
2853 forceUserActivityLocked();
2854 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002855
2856 if (mProximityWakeLockCount == 0) {
2857 // disable sensor if we have no listeners left after proximity negative
2858 disableProximityLockLocked();
2859 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002860 }
2861 }
2862
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002863 private void enableLightSensor(boolean enable) {
2864 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002865 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002866 }
2867 if (mSensorManager != null && mLightSensorEnabled != enable) {
2868 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002869 // clear calling identity so sensor manager battery stats are accurate
2870 long identity = Binder.clearCallingIdentity();
2871 try {
2872 if (enable) {
2873 mSensorManager.registerListener(mLightListener, mLightSensor,
2874 SensorManager.SENSOR_DELAY_NORMAL);
2875 } else {
2876 mSensorManager.unregisterListener(mLightListener);
2877 mHandler.removeCallbacks(mAutoBrightnessTask);
2878 }
2879 } finally {
2880 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002881 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002882 }
2883 }
2884
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002885 SensorEventListener mProximityListener = new SensorEventListener() {
2886 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002887 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002888 synchronized (mLocks) {
2889 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002890 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2891 mLastProximityEventTime = milliseconds;
2892 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002893 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002894
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002895 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002896 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2897 distance < mProximitySensor.getMaximumRange());
2898
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002899 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002900 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002901 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002902 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2903 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2904 mProximityPendingValue = (active ? 1 : 0);
2905 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002906 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002907 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002908 // process the value immediately
2909 mProximityPendingValue = -1;
2910 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002911 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002912
2913 // update mProximityPartialLock state
2914 boolean held = mProximityPartialLock.isHeld();
2915 if (!held && proximityTaskQueued) {
2916 // hold wakelock until mProximityTask runs
2917 mProximityPartialLock.acquire();
2918 } else if (held && !proximityTaskQueued) {
2919 mProximityPartialLock.release();
2920 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002921 }
2922 }
2923
2924 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2925 // ignore
2926 }
2927 };
2928
2929 SensorEventListener mLightListener = new SensorEventListener() {
2930 public void onSensorChanged(SensorEvent event) {
2931 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002932 // ignore light sensor while screen is turning off
2933 if (isScreenTurningOffLocked()) {
2934 return;
2935 }
2936
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002937 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002938 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002939 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002940 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002941 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002942 mHandler.removeCallbacks(mAutoBrightnessTask);
2943 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002944 if (mLightSensorValue == -1 ||
2945 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2946 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002947 lightSensorChangedLocked(value);
2948 } else {
2949 // delay processing to debounce the sensor
2950 mLightSensorPendingValue = value;
2951 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2952 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002953 } else {
2954 mLightSensorPendingValue = -1;
2955 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002956 }
2957 }
2958
2959 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2960 // ignore
2961 }
2962 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963}