blob: 88a4c9069707c5d508683fc4bd1cec2b8610c3df [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;
Joe Onorato6d747652010-10-11 15:15:31 -0700248 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700249 private int mWarningSpewThrottleCount;
250 private long mWarningSpewThrottleTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 // Used when logging number and duration of touch-down cycles
253 private long mTotalTouchDownTime;
254 private long mLastTouchDown;
255 private int mTouchCycles;
256
257 // could be either static or controllable at runtime
258 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400259 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400260 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700261
262 private native void nativeInit();
263 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
265 /*
266 static PrintStream mLog;
267 static {
268 try {
269 mLog = new PrintStream("/data/power.log");
270 }
271 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800272 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
274 }
275 static class Log {
276 static void d(String tag, String s) {
277 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800278 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280 static void i(String tag, String s) {
281 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800282 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284 static void w(String tag, String s) {
285 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800286 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 static void e(String tag, String s) {
289 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800290 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292 }
293 */
294
295 /**
296 * This class works around a deadlock between the lock in PowerManager.WakeLock
297 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
298 * mToken object so it can be accessed from any thread, but it calls into here
299 * with its lock held. This class is essentially a reimplementation of
300 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
301 * only call it with our own locks held.
302 */
303 private class UnsynchronizedWakeLock {
304 int mFlags;
305 String mTag;
306 IBinder mToken;
307 int mCount = 0;
308 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500309 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310
311 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
312 mFlags = flags;
313 mTag = tag;
314 mToken = new Binder();
315 mRefCounted = refCounted;
316 }
317
318 public void acquire() {
319 if (!mRefCounted || mCount++ == 0) {
320 long ident = Binder.clearCallingIdentity();
321 try {
322 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700323 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500324 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 } finally {
326 Binder.restoreCallingIdentity(ident);
327 }
328 }
329 }
330
331 public void release() {
332 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500333 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500334 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336 if (mCount < 0) {
337 throw new RuntimeException("WakeLock under-locked " + mTag);
338 }
339 }
340
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500341 public boolean isHeld()
342 {
343 return mHeld;
344 }
345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 public String toString() {
347 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500348 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350 }
351
352 private final class BatteryReceiver extends BroadcastReceiver {
353 @Override
354 public void onReceive(Context context, Intent intent) {
355 synchronized (mLocks) {
356 boolean wasPowered = mIsPowered;
357 mIsPowered = mBatteryService.isPowered();
358
359 if (mIsPowered != wasPowered) {
360 // update mStayOnWhilePluggedIn wake lock
361 updateWakeLockLocked();
362
363 // treat plugging and unplugging the devices as a user activity.
364 // users find it disconcerting when they unplug the device
365 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500366 // to avoid turning on the screen when unplugging, we only trigger
367 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 // temporarily set mUserActivityAllowed to true so this will work
369 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700370 // However, you can also set config_unplugTurnsOnScreen to have it
371 // turn on. Some devices want this because they don't have a
372 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700374 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
375 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500376 forceUserActivityLocked();
377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379 }
380 }
381 }
382 }
383
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500384 private final class BootCompletedReceiver extends BroadcastReceiver {
385 @Override
386 public void onReceive(Context context, Intent intent) {
387 bootCompleted();
388 }
389 }
390
Mike Lockwoodb2865412010-02-02 22:40:33 -0500391 private final class DockReceiver extends BroadcastReceiver {
392 @Override
393 public void onReceive(Context context, Intent intent) {
394 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
395 Intent.EXTRA_DOCK_STATE_UNDOCKED);
396 dockStateChanged(state);
397 }
398 }
399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 /**
401 * Set the setting that determines whether the device stays on when plugged in.
402 * The argument is a bit string, with each bit specifying a power source that,
403 * when the device is connected to that source, causes the device to stay on.
404 * See {@link android.os.BatteryManager} for the list of power sources that
405 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
406 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
407 * @param val an {@code int} containing the bits that specify which power sources
408 * should cause the device to stay on.
409 */
410 public void setStayOnSetting(int val) {
411 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
412 Settings.System.putInt(mContext.getContentResolver(),
413 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
414 }
415
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800416 public void setMaximumScreenOffTimeount(int timeMs) {
417 mContext.enforceCallingOrSelfPermission(
418 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
419 synchronized (mLocks) {
420 mMaximumScreenOffTimeout = timeMs;
421 // recalculate everything
422 setScreenOffTimeoutsLocked();
423 }
424 }
425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700427 private int getInt(String name, int defValue) {
428 ContentValues values = mSettings.getValues(name);
429 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
430 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 }
432
433 public void update(Observable o, Object arg) {
434 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700435 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
436 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
437 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 updateWakeLockLocked();
439
Amith Yamasani8b619832010-09-22 16:11:59 -0700440 // SCREEN_OFF_TIMEOUT, default to 15 seconds
441 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442
443 // DIM_SCREEN
444 //mDimScreen = getInt(DIM_SCREEN) != 0;
445
Amith Yamasani8b619832010-09-22 16:11:59 -0700446 // SCREEN_BRIGHTNESS_MODE, default to manual
447 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
448 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 // recalculate everything
451 setScreenOffTimeoutsLocked();
452 }
453 }
454 }
455
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700456 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 // Hack to get our uid... should have a func for this.
458 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700459 MY_UID = Process.myUid();
460 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 Binder.restoreCallingIdentity(token);
462
463 // XXX remove this when the kernel doesn't timeout wake locks
464 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
465
466 // assume nothing is on yet
467 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 // Add ourself to the Watchdog monitors.
470 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
472
473 private ContentQueryMap mSettings;
474
Mike Lockwood3a322132009-11-24 00:30:52 -0500475 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700476 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500477 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 mContext = context;
479 mActivityService = activity;
480 mBatteryStats = BatteryStatsService.getService();
481 mBatteryService = battery;
482
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500483 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
484 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
485 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
486 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 mHandlerThread = new HandlerThread("PowerManagerService") {
489 @Override
490 protected void onLooperPrepared() {
491 super.onLooperPrepared();
492 initInThread();
493 }
494 };
495 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 synchronized (mHandlerThread) {
498 while (!mInitComplete) {
499 try {
500 mHandlerThread.wait();
501 } catch (InterruptedException e) {
502 // Ignore
503 }
504 }
505 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700506
507 nativeInit();
508 synchronized (mLocks) {
509 updateNativePowerStateLocked();
510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 void initInThread() {
514 mHandler = new Handler();
515
516 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700517 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
519 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
520 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
521 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
522 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
523 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500524 mProximityPartialLock = new UnsynchronizedWakeLock(
525 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
528 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
529 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
530 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
531
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700532 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400533
Joe Onorato6d747652010-10-11 15:15:31 -0700534 mUnplugTurnsOnScreen = resources.getBoolean(
535 com.android.internal.R.bool.config_unplugTurnsOnScreen);
536
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400537 // read settings for auto-brightness
538 mUseSoftwareAutoBrightness = resources.getBoolean(
539 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400540 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700541 mAutoBrightnessLevels = resources.getIntArray(
542 com.android.internal.R.array.config_autoBrightnessLevels);
543 mLcdBacklightValues = resources.getIntArray(
544 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
545 mButtonBacklightValues = resources.getIntArray(
546 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
547 mKeyboardBacklightValues = resources.getIntArray(
548 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500549 mLightSensorWarmupTime = resources.getInteger(
550 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700551 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700552
553 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
555 "(" + Settings.System.NAME + "=?) or ("
556 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700557 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700559 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
560 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 null);
562 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
563 SettingsObserver settingsObserver = new SettingsObserver();
564 mSettings.addObserver(settingsObserver);
565
566 // pretend that the settings changed so we will get their initial state
567 settingsObserver.update(mSettings, null);
568
569 // register for the battery changed notifications
570 IntentFilter filter = new IntentFilter();
571 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
572 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500573 filter = new IntentFilter();
574 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
575 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500576 filter = new IntentFilter();
577 filter.addAction(Intent.ACTION_DOCK_EVENT);
578 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579
Doug Zongker43866e02010-01-07 12:09:54 -0800580 // Listen for secure settings changes
581 mContext.getContentResolver().registerContentObserver(
582 Settings.Secure.CONTENT_URI, true,
583 new ContentObserver(new Handler()) {
584 public void onChange(boolean selfChange) {
585 updateSettingsValues();
586 }
587 });
588 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 synchronized (mHandlerThread) {
591 mInitComplete = true;
592 mHandlerThread.notifyAll();
593 }
594 }
595
596 private class WakeLock implements IBinder.DeathRecipient
597 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700598 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 super();
600 flags = f;
601 binder = b;
602 tag = t;
603 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700604 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 if (u != MY_UID || (
606 !"KEEP_SCREEN_ON_FLAG".equals(tag)
607 && !"KeyInputQueue".equals(tag))) {
608 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
609 ? BatteryStats.WAKE_TYPE_PARTIAL
610 : BatteryStats.WAKE_TYPE_FULL;
611 } else {
612 monitorType = -1;
613 }
614 try {
615 b.linkToDeath(this, 0);
616 } catch (RemoteException e) {
617 binderDied();
618 }
619 }
620 public void binderDied() {
621 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500622 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 }
624 }
625 final int flags;
626 final IBinder binder;
627 final String tag;
628 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400629 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700631 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 boolean activated = true;
633 int minState;
634 }
635
636 private void updateWakeLockLocked() {
637 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
638 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
639 mStayOnWhilePluggedInScreenDimLock.acquire();
640 mStayOnWhilePluggedInPartialLock.acquire();
641 } else {
642 mStayOnWhilePluggedInScreenDimLock.release();
643 mStayOnWhilePluggedInPartialLock.release();
644 }
645 }
646
647 private boolean isScreenLock(int flags)
648 {
649 int n = flags & LOCK_MASK;
650 return n == PowerManager.FULL_WAKE_LOCK
651 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400652 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
653 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700656 void enforceWakeSourcePermission(int uid, int pid) {
657 if (uid == Process.myUid()) {
658 return;
659 }
660 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
661 pid, uid, null);
662 }
663
664 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700666 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700667 if (uid != Process.myUid()) {
668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
669 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700670 if (ws != null) {
671 enforceWakeSourcePermission(uid, pid);
672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 long ident = Binder.clearCallingIdentity();
674 try {
675 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700676 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
678 } finally {
679 Binder.restoreCallingIdentity(ident);
680 }
681 }
682
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700683 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700684 if (wl.monitorType >= 0) {
685 long origId = Binder.clearCallingIdentity();
686 try {
687 if (ws != null) {
688 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
689 wl.monitorType);
690 } else {
691 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
692 }
693 } catch (RemoteException e) {
694 // Ignore
695 } finally {
696 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700697 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700698 }
699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700701 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700702 if (wl.monitorType >= 0) {
703 long origId = Binder.clearCallingIdentity();
704 try {
705 if (ws != null) {
706 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
707 wl.monitorType);
708 } else {
709 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
710 }
711 } catch (RemoteException e) {
712 // Ignore
713 } finally {
714 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700715 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700716 }
717 }
718
719 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
720 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800722 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
724
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700725 if (ws != null && ws.size() == 0) {
726 ws = null;
727 }
728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 int index = mLocks.getIndex(lock);
730 WakeLock wl;
731 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700732 boolean diffsource;
733 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700735 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 switch (wl.flags & LOCK_MASK)
737 {
738 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500739 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400740 wl.minState = SCREEN_BRIGHT;
741 } else {
742 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 break;
745 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
746 wl.minState = SCREEN_BRIGHT;
747 break;
748 case PowerManager.SCREEN_DIM_WAKE_LOCK:
749 wl.minState = SCREEN_DIM;
750 break;
751 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700752 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 break;
754 default:
755 // just log and bail. we're in the server, so don't
756 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800757 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 + " flags=" + flags);
759 return;
760 }
761 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700762 if (ws != null) {
763 wl.ws = new WorkSource(ws);
764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700766 diffsource = false;
767 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 } else {
769 wl = mLocks.get(index);
770 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700771 oldsource = wl.ws;
772 if (oldsource != null) {
773 if (ws == null) {
774 wl.ws = null;
775 diffsource = true;
776 } else {
777 diffsource = oldsource.diff(ws);
778 }
779 } else if (ws != null) {
780 diffsource = true;
781 } else {
782 diffsource = false;
783 }
784 if (diffsource) {
785 wl.ws = new WorkSource(ws);
786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
788 if (isScreenLock(flags)) {
789 // if this causes a wakeup, we reactivate all of the locks and
790 // set it to whatever they want. otherwise, we modulate that
791 // by the current state so we never turn it more on than
792 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400793 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
794 mProximityWakeLockCount++;
795 if (mProximityWakeLockCount == 1) {
796 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400799 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
800 int oldWakeLockState = mWakeLockState;
801 mWakeLockState = mLocks.reactivateScreenLocksLocked();
802 if (mSpew) {
803 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
804 + " mWakeLockState=0x"
805 + Integer.toHexString(mWakeLockState)
806 + " previous wakeLockState=0x"
807 + Integer.toHexString(oldWakeLockState));
808 }
809 } else {
810 if (mSpew) {
811 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
812 + " mLocks.gatherState()=0x"
813 + Integer.toHexString(mLocks.gatherState())
814 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
815 }
816 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400818 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
822 if (newlock) {
823 mPartialCount++;
824 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800825 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700831 if (diffsource) {
832 // If the lock sources have changed, need to first release the
833 // old ones.
834 noteStopWakeLocked(wl, oldsource);
835 }
836 if (newlock || diffsource) {
837 noteStartWakeLocked(wl, ws);
838 }
839 }
840
841 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
842 int uid = Binder.getCallingUid();
843 int pid = Binder.getCallingPid();
844 if (ws != null && ws.size() == 0) {
845 ws = null;
846 }
847 if (ws != null) {
848 enforceWakeSourcePermission(uid, pid);
849 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700850 synchronized (mLocks) {
851 int index = mLocks.getIndex(lock);
852 if (index < 0) {
853 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700855 WakeLock wl = mLocks.get(index);
856 WorkSource oldsource = wl.ws;
857 wl.ws = ws != null ? new WorkSource(ws) : null;
858 noteStopWakeLocked(wl, oldsource);
859 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861 }
862
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500863 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700864 int uid = Binder.getCallingUid();
865 if (uid != Process.myUid()) {
866 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868
869 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500870 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
872 }
873
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500874 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 WakeLock wl = mLocks.removeLock(lock);
876 if (wl == null) {
877 return;
878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
883 }
884
885 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400886 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
887 mProximityWakeLockCount--;
888 if (mProximityWakeLockCount == 0) {
889 if (mProximitySensorActive &&
890 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
891 // wait for proximity sensor to go negative before disabling sensor
892 if (mDebugProximitySensor) {
893 Slog.d(TAG, "waiting for proximity sensor to go negative");
894 }
895 } else {
896 disableProximityLockLocked();
897 }
898 }
899 } else {
900 mWakeLockState = mLocks.gatherState();
901 // goes in the middle to reduce flicker
902 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
903 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
904 }
905 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
909 mPartialCount--;
910 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800911 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 Power.releaseWakeLock(PARTIAL_NAME);
913 }
914 }
915 // Unlink the lock from the binder.
916 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
Dianne Hackborn70be1672010-09-14 11:13:03 -0700918 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 private class PokeLock implements IBinder.DeathRecipient
922 {
923 PokeLock(int p, IBinder b, String t) {
924 super();
925 this.pokey = p;
926 this.binder = b;
927 this.tag = t;
928 try {
929 b.linkToDeath(this, 0);
930 } catch (RemoteException e) {
931 binderDied();
932 }
933 }
934 public void binderDied() {
935 setPokeLock(0, this.binder, this.tag);
936 }
937 int pokey;
938 IBinder binder;
939 String tag;
940 boolean awakeOnSet;
941 }
942
943 public void setPokeLock(int pokey, IBinder token, String tag) {
944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
945 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800946 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 return;
948 }
949
950 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
951 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
952 + " and POKE_LOCK_MEDIUM_TIMEOUT");
953 }
954
955 synchronized (mLocks) {
956 if (pokey != 0) {
957 PokeLock p = mPokeLocks.get(token);
958 int oldPokey = 0;
959 if (p != null) {
960 oldPokey = p.pokey;
961 p.pokey = pokey;
962 } else {
963 p = new PokeLock(pokey, token, tag);
964 mPokeLocks.put(token, p);
965 }
966 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
967 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
968 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
969 p.awakeOnSet = true;
970 }
971 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700972 PokeLock rLock = mPokeLocks.remove(token);
973 if (rLock != null) {
974 token.unlinkToDeath(rLock, 0);
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977
978 int oldPokey = mPokey;
979 int cumulative = 0;
980 boolean oldAwakeOnSet = mPokeAwakeOnSet;
981 boolean awakeOnSet = false;
982 for (PokeLock p: mPokeLocks.values()) {
983 cumulative |= p.pokey;
984 if (p.awakeOnSet) {
985 awakeOnSet = true;
986 }
987 }
988 mPokey = cumulative;
989 mPokeAwakeOnSet = awakeOnSet;
990
991 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
992 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 if (oldCumulativeTimeout != newCumulativeTimeout) {
995 setScreenOffTimeoutsLocked();
996 // reset the countdown timer, but use the existing nextState so it doesn't
997 // change anything
998 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
999 }
1000 }
1001 }
1002
1003 private static String lockType(int type)
1004 {
1005 switch (type)
1006 {
1007 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001008 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001010 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001012 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001014 return "PARTIAL_WAKE_LOCK ";
1015 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1016 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 default:
David Brown251faa62009-08-02 22:04:36 -07001018 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
1020 }
1021
1022 private static String dumpPowerState(int state) {
1023 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1024 ? "KEYBOARD_BRIGHT_BIT " : "")
1025 + (((state & SCREEN_BRIGHT_BIT) != 0)
1026 ? "SCREEN_BRIGHT_BIT " : "")
1027 + (((state & SCREEN_ON_BIT) != 0)
1028 ? "SCREEN_ON_BIT " : "")
1029 + (((state & BATTERY_LOW_BIT) != 0)
1030 ? "BATTERY_LOW_BIT " : "");
1031 }
1032
1033 @Override
1034 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1035 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1036 != PackageManager.PERMISSION_GRANTED) {
1037 pw.println("Permission Denial: can't dump PowerManager from from pid="
1038 + Binder.getCallingPid()
1039 + ", uid=" + Binder.getCallingUid());
1040 return;
1041 }
1042
1043 long now = SystemClock.uptimeMillis();
1044
Mike Lockwoodca44df82010-02-25 13:48:49 -05001045 synchronized (mLocks) {
1046 pw.println("Power Manager State:");
1047 pw.println(" mIsPowered=" + mIsPowered
1048 + " mPowerState=" + mPowerState
1049 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1050 + " ms");
1051 pw.println(" mPartialCount=" + mPartialCount);
1052 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1053 pw.println(" mUserState=" + dumpPowerState(mUserState));
1054 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1055 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1056 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1057 + " " + ((mNextTimeout-now)/1000) + "s from now");
1058 pw.println(" mDimScreen=" + mDimScreen
1059 + " mStayOnConditions=" + mStayOnConditions);
1060 pw.println(" mScreenOffReason=" + mScreenOffReason
1061 + " mUserState=" + mUserState);
1062 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1063 + ',' + mBroadcastQueue[2] + "}");
1064 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1065 + ',' + mBroadcastWhy[2] + "}");
1066 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1067 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1068 + " mUserActivityAllowed=" + mUserActivityAllowed);
1069 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1070 + " mScreenOffDelay=" + mScreenOffDelay);
1071 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1072 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1073 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1074 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1075 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1076 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1077 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1078 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1079 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1080 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1081 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1082 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1083 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1084 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1085 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1086 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1087 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1088 pw.println(" mLightSensorValue=" + mLightSensorValue
1089 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
1090 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1091 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1092 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1093 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1094 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1095 mScreenBrightness.dump(pw, " mScreenBrightness: ");
1096 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
1097 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001098
Mike Lockwoodca44df82010-02-25 13:48:49 -05001099 int N = mLocks.size();
1100 pw.println();
1101 pw.println("mLocks.size=" + N + ":");
1102 for (int i=0; i<N; i++) {
1103 WakeLock wl = mLocks.get(i);
1104 String type = lockType(wl.flags & LOCK_MASK);
1105 String acquireCausesWakeup = "";
1106 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1107 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1108 }
1109 String activated = "";
1110 if (wl.activated) {
1111 activated = " activated";
1112 }
1113 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001114 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1115 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001117
1118 pw.println();
1119 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1120 for (PokeLock p: mPokeLocks.values()) {
1121 pw.println(" poke lock '" + p.tag + "':"
1122 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1123 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1124 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1125 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1126 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1127 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1128 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1129 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001131
Mike Lockwoodca44df82010-02-25 13:48:49 -05001132 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135
Joe Onorato7999bff2010-07-24 11:50:05 -04001136 private void setTimeoutLocked(long now, int nextState) {
1137 setTimeoutLocked(now, -1, nextState);
1138 }
1139
1140 // If they gave a timeoutOverride it is the number of seconds
1141 // to screen-off. Figure out where in the countdown cycle we
1142 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001143 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1144 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001145 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001146 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001147 long when = 0;
1148 if (timeoutOverride <= 0) {
1149 switch (nextState)
1150 {
1151 case SCREEN_BRIGHT:
1152 when = now + mKeylightDelay;
1153 break;
1154 case SCREEN_DIM:
1155 if (mDimDelay >= 0) {
1156 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001157 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001158 } else {
1159 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1160 }
1161 case SCREEN_OFF:
1162 synchronized (mLocks) {
1163 when = now + mScreenOffDelay;
1164 }
1165 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001166 default:
1167 when = now;
1168 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001170 } else {
1171 override: {
1172 if (timeoutOverride <= mScreenOffDelay) {
1173 when = now + timeoutOverride;
1174 nextState = SCREEN_OFF;
1175 break override;
1176 }
1177 timeoutOverride -= mScreenOffDelay;
1178
1179 if (mDimDelay >= 0) {
1180 if (timeoutOverride <= mDimDelay) {
1181 when = now + timeoutOverride;
1182 nextState = SCREEN_DIM;
1183 break override;
1184 }
1185 timeoutOverride -= mDimDelay;
1186 }
1187
1188 when = now + timeoutOverride;
1189 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001191 }
1192 if (mSpew) {
1193 Slog.d(TAG, "setTimeoutLocked now=" + now
1194 + " timeoutOverride=" + timeoutOverride
1195 + " nextState=" + nextState + " when=" + when);
1196 }
Joe Onorato797e6882010-08-26 14:46:01 -04001197
1198 mHandler.removeCallbacks(mTimeoutTask);
1199 mTimeoutTask.nextState = nextState;
1200 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1201 ? (originalTimeoutOverride - timeoutOverride)
1202 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001203 mHandler.postAtTime(mTimeoutTask, when);
1204 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207 }
1208
1209 private void cancelTimerLocked()
1210 {
1211 mHandler.removeCallbacks(mTimeoutTask);
1212 mTimeoutTask.nextState = -1;
1213 }
1214
1215 private class TimeoutTask implements Runnable
1216 {
1217 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001218 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 public void run()
1220 {
1221 synchronized (mLocks) {
1222 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001223 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225
1226 if (nextState == -1) {
1227 return;
1228 }
1229
1230 mUserState = this.nextState;
1231 setPowerState(this.nextState | mWakeLockState);
1232
1233 long now = SystemClock.uptimeMillis();
1234
1235 switch (this.nextState)
1236 {
1237 case SCREEN_BRIGHT:
1238 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001239 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 break;
1241 }
1242 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001243 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 break;
1245 }
1246 }
1247 }
1248 }
1249
1250 private void sendNotificationLocked(boolean on, int why)
1251 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001252 if (!on) {
1253 mStillNeedSleepNotification = false;
1254 }
1255
Joe Onorato128e7292009-03-24 18:41:31 -07001256 // Add to the queue.
1257 int index = 0;
1258 while (mBroadcastQueue[index] != -1) {
1259 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
Joe Onorato128e7292009-03-24 18:41:31 -07001261 mBroadcastQueue[index] = on ? 1 : 0;
1262 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263
Joe Onorato128e7292009-03-24 18:41:31 -07001264 // If we added it position 2, then there is a pair that can be stripped.
1265 // If we added it position 1 and we're turning the screen off, we can strip
1266 // the pair and do nothing, because the screen is already off, and therefore
1267 // keyguard has already been enabled.
1268 // However, if we added it at position 1 and we're turning it on, then position
1269 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1270 // on, so have to run the queue then.
1271 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001272 // While we're collapsing them, if it's going off, and the new reason
1273 // is more significant than the first, then use the new one.
1274 if (!on && mBroadcastWhy[0] > why) {
1275 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001276 }
1277 mBroadcastQueue[0] = on ? 1 : 0;
1278 mBroadcastQueue[1] = -1;
1279 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001280 mBroadcastWakeLock.release();
1281 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001282 index = 0;
1283 }
1284 if (index == 1 && !on) {
1285 mBroadcastQueue[0] = -1;
1286 mBroadcastQueue[1] = -1;
1287 index = -1;
1288 // The wake lock was being held, but we're not actually going to do any
1289 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001290 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001292 }
1293
1294 // Now send the message.
1295 if (index >= 0) {
1296 // Acquire the broadcast wake lock before changing the power
1297 // state. It will be release after the broadcast is sent.
1298 // We always increment the ref count for each notification in the queue
1299 // and always decrement when that notification is handled.
1300 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001301 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001302 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 }
1305
1306 private Runnable mNotificationTask = new Runnable()
1307 {
1308 public void run()
1309 {
Joe Onorato128e7292009-03-24 18:41:31 -07001310 while (true) {
1311 int value;
1312 int why;
1313 WindowManagerPolicy policy;
1314 synchronized (mLocks) {
1315 value = mBroadcastQueue[0];
1316 why = mBroadcastWhy[0];
1317 for (int i=0; i<2; i++) {
1318 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1319 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1320 }
1321 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
Joe Onorato128e7292009-03-24 18:41:31 -07001323 if (value == 1) {
1324 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001325
Joe Onorato128e7292009-03-24 18:41:31 -07001326 policy.screenTurnedOn();
1327 try {
1328 ActivityManagerNative.getDefault().wakingUp();
1329 } catch (RemoteException e) {
1330 // ignore it
1331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332
Joe Onorato128e7292009-03-24 18:41:31 -07001333 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001335 }
1336 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1337 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1338 mScreenOnBroadcastDone, mHandler, 0, null, null);
1339 } else {
1340 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001341 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001342 mBroadcastWakeLock.mCount);
1343 mBroadcastWakeLock.release();
1344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346 }
Joe Onorato128e7292009-03-24 18:41:31 -07001347 else if (value == 0) {
1348 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001349
Joe Onorato128e7292009-03-24 18:41:31 -07001350 policy.screenTurnedOff(why);
1351 try {
1352 ActivityManagerNative.getDefault().goingToSleep();
1353 } catch (RemoteException e) {
1354 // ignore it.
1355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356
Joe Onorato128e7292009-03-24 18:41:31 -07001357 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1358 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1359 mScreenOffBroadcastDone, mHandler, 0, null, null);
1360 } else {
1361 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001362 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001363 mBroadcastWakeLock.mCount);
1364 mBroadcastWakeLock.release();
1365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
1367 }
Joe Onorato128e7292009-03-24 18:41:31 -07001368 else {
1369 // If we're in this case, then this handler is running for a previous
1370 // paired transaction. mBroadcastWakeLock will already have been released.
1371 break;
1372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 }
1375 };
1376
1377 long mScreenOnStart;
1378 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1379 public void onReceive(Context context, Intent intent) {
1380 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001381 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1383 mBroadcastWakeLock.release();
1384 }
1385 }
1386 };
1387
1388 long mScreenOffStart;
1389 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1390 public void onReceive(Context context, Intent intent) {
1391 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001392 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1394 mBroadcastWakeLock.release();
1395 }
1396 }
1397 };
1398
1399 void logPointerUpEvent() {
1400 if (LOG_TOUCH_DOWNS) {
1401 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1402 mLastTouchDown = 0;
1403 }
1404 }
1405
1406 void logPointerDownEvent() {
1407 if (LOG_TOUCH_DOWNS) {
1408 // If we are not already timing a down/up sequence
1409 if (mLastTouchDown == 0) {
1410 mLastTouchDown = SystemClock.elapsedRealtime();
1411 mTouchCycles++;
1412 }
1413 }
1414 }
1415
1416 /**
1417 * Prevents the screen from turning on even if it *should* turn on due
1418 * to a subsequent full wake lock being acquired.
1419 * <p>
1420 * This is a temporary hack that allows an activity to "cover up" any
1421 * display glitches that happen during the activity's startup
1422 * sequence. (Specifically, this API was added to work around a
1423 * cosmetic bug in the "incoming call" sequence, where the lock screen
1424 * would flicker briefly before the incoming call UI became visible.)
1425 * TODO: There ought to be a more elegant way of doing this,
1426 * probably by having the PowerManager and ActivityManager
1427 * work together to let apps specify that the screen on/off
1428 * state should be synchronized with the Activity lifecycle.
1429 * <p>
1430 * Note that calling preventScreenOn(true) will NOT turn the screen
1431 * off if it's currently on. (This API only affects *future*
1432 * acquisitions of full wake locks.)
1433 * But calling preventScreenOn(false) WILL turn the screen on if
1434 * it's currently off because of a prior preventScreenOn(true) call.
1435 * <p>
1436 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1437 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1438 * call doesn't occur within 5 seconds, we'll turn the screen back on
1439 * ourselves (and log a warning about it); this prevents a buggy app
1440 * from disabling the screen forever.)
1441 * <p>
1442 * TODO: this feature should really be controlled by a new type of poke
1443 * lock (rather than an IPowerManager call).
1444 */
1445 public void preventScreenOn(boolean prevent) {
1446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1447
1448 synchronized (mLocks) {
1449 if (prevent) {
1450 // First of all, grab a partial wake lock to
1451 // make sure the CPU stays on during the entire
1452 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1453 mPreventScreenOnPartialLock.acquire();
1454
1455 // Post a forceReenableScreen() call (for 5 seconds in the
1456 // future) to make sure the matching preventScreenOn(false) call
1457 // has happened by then.
1458 mHandler.removeCallbacks(mForceReenableScreenTask);
1459 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1460
1461 // Finally, set the flag that prevents the screen from turning on.
1462 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001463 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 mPreventScreenOn = true;
1465 } else {
1466 // (Re)enable the screen.
1467 mPreventScreenOn = false;
1468
1469 // We're "undoing" a the prior preventScreenOn(true) call, so we
1470 // no longer need the 5-second safeguard.
1471 mHandler.removeCallbacks(mForceReenableScreenTask);
1472
1473 // Forcibly turn on the screen if it's supposed to be on. (This
1474 // handles the case where the screen is currently off because of
1475 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001476 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1480 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001481 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001483 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485 }
1486
1487 // Release the partial wake lock that we held during the
1488 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1489 mPreventScreenOnPartialLock.release();
1490 }
1491 }
1492 }
1493
1494 public void setScreenBrightnessOverride(int brightness) {
1495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1496
Mike Lockwoodf527c712010-06-10 14:12:33 -04001497 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 synchronized (mLocks) {
1499 if (mScreenBrightnessOverride != brightness) {
1500 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001501 if (isScreenOn()) {
1502 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505 }
1506 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001507
1508 public void setButtonBrightnessOverride(int brightness) {
1509 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1510
Mike Lockwoodf527c712010-06-10 14:12:33 -04001511 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001512 synchronized (mLocks) {
1513 if (mButtonBrightnessOverride != brightness) {
1514 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001515 if (isScreenOn()) {
1516 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1517 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001518 }
1519 }
1520 }
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 /**
1523 * Sanity-check that gets called 5 seconds after any call to
1524 * preventScreenOn(true). This ensures that the original call
1525 * is followed promptly by a call to preventScreenOn(false).
1526 */
1527 private void forceReenableScreen() {
1528 // We shouldn't get here at all if mPreventScreenOn is false, since
1529 // we should have already removed any existing
1530 // mForceReenableScreenTask messages...
1531 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 return;
1534 }
1535
1536 // Uh oh. It's been 5 seconds since a call to
1537 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1538 // This means the app that called preventScreenOn(true) is either
1539 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1540 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1541 // crashed before doing so.)
1542
1543 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001544 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 + "Forcing the screen back on...");
1546 preventScreenOn(false);
1547 }
1548
1549 private Runnable mForceReenableScreenTask = new Runnable() {
1550 public void run() {
1551 forceReenableScreen();
1552 }
1553 };
1554
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001555 private int setScreenStateLocked(boolean on) {
1556 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001557 if (err == 0) {
1558 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1559 if (mUseSoftwareAutoBrightness) {
1560 enableLightSensor(on);
1561 if (!on) {
1562 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001563 mButtonLight.turnOff();
1564 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001565 // clear current value so we will update based on the new conditions
1566 // when the sensor is reenabled.
1567 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001568 // reset our highest light sensor value when the screen turns off
1569 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001570 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001571 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001572 }
1573 return err;
1574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 private void setPowerState(int state)
1577 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001578 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
Mike Lockwood435eb642009-12-03 08:40:18 -05001581 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 {
1583 synchronized (mLocks) {
1584 int err;
1585
1586 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001587 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001589 + " noChangeLights=" + noChangeLights
1590 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 }
1592
1593 if (noChangeLights) {
1594 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1595 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001596 if (mProximitySensorActive) {
1597 // don't turn on the screen when the proximity sensor lock is held
1598 newState = (newState & ~SCREEN_BRIGHT);
1599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600
1601 if (batteryIsLow()) {
1602 newState |= BATTERY_LOW_BIT;
1603 } else {
1604 newState &= ~BATTERY_LOW_BIT;
1605 }
1606 if (newState == mPowerState) {
1607 return;
1608 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001609
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001610 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 newState |= ALL_BRIGHT;
1612 }
1613
1614 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1615 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1616
Mike Lockwood51b84492009-11-16 21:51:18 -05001617 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001618 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001622 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001626 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001628 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1630 }
1631
1632 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001633 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1635 }
1636
1637 if (oldScreenOn != newScreenOn) {
1638 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001639 // When the user presses the power button, we need to always send out the
1640 // notification that it's going to sleep so the keyguard goes on. But
1641 // we can't do that until the screen fades out, so we don't show the keyguard
1642 // too early.
1643 if (mStillNeedSleepNotification) {
1644 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1645 }
1646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 // Turn on the screen UNLESS there was a prior
1648 // preventScreenOn(true) request. (Note that the lifetime
1649 // of a single preventScreenOn() request is limited to 5
1650 // seconds to prevent a buggy app from disabling the
1651 // screen forever; see forceReenableScreen().)
1652 boolean reallyTurnScreenOn = true;
1653 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001654 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 + mPreventScreenOn);
1656 }
1657
1658 if (mPreventScreenOn) {
1659 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001660 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662 reallyTurnScreenOn = false;
1663 }
1664 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001665 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 long identity = Binder.clearCallingIdentity();
1667 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001668 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 mBatteryStats.noteScreenOn();
1670 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001671 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 } finally {
1673 Binder.restoreCallingIdentity(identity);
1674 }
1675 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001676 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 // But continue as if we really did turn the screen on...
1678 err = 0;
1679 }
1680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 mLastTouchDown = 0;
1682 mTotalTouchDownTime = 0;
1683 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001684 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mTotalTouchDownTime, mTouchCycles);
1686 if (err == 0) {
1687 mPowerState |= SCREEN_ON_BIT;
1688 sendNotificationLocked(true, -1);
1689 }
1690 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001691 // cancel light sensor task
1692 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 mScreenOffTime = SystemClock.elapsedRealtime();
1694 long identity = Binder.clearCallingIdentity();
1695 try {
1696 mBatteryStats.noteScreenOff();
1697 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001698 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 } finally {
1700 Binder.restoreCallingIdentity(identity);
1701 }
1702 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001703 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001705 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 err = 0;
1708 mLastTouchDown = 0;
1709 }
1710 }
1711 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001712
1713 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001716
1717 private void updateNativePowerStateLocked() {
1718 nativeSetPowerState(
1719 (mPowerState & SCREEN_ON_BIT) != 0,
1720 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001722
Mike Lockwood435eb642009-12-03 08:40:18 -05001723 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001725 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001727 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001729 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001731 mScreenOffReason = reason;
1732 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734 return err;
1735 }
1736
1737 private boolean batteryIsLow() {
1738 return (!mIsPowered &&
1739 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1740 }
1741
The Android Open Source Project10592532009-03-18 17:39:46 -07001742 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001743 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001744 newState = applyButtonState(newState);
1745 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001746 final int realDifference = (newState ^ oldState);
1747 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001749 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 int offMask = 0;
1753 int dimMask = 0;
1754 int onMask = 0;
1755
1756 int preferredBrightness = getPreferredBrightness();
1757 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1760 if (ANIMATE_KEYBOARD_LIGHTS) {
1761 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1762 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001763 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001764 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001766 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001767 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1768 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
1770 startAnimation = true;
1771 } else {
1772 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001773 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001775 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
1777 }
1778 }
1779
1780 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1781 if (ANIMATE_BUTTON_LIGHTS) {
1782 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1783 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001784 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001785 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001787 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001788 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1789 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 startAnimation = true;
1792 } else {
1793 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001794 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001796 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
1799 }
1800
1801 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1802 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001803 int nominalCurrentValue = -1;
1804 // If there was an actual difference in the light state, then
1805 // figure out the "ideal" current value based on the previous
1806 // state. Otherwise, this is a change due to the brightness
1807 // override, so we want to animate from whatever the current
1808 // value is.
1809 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1810 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1811 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1812 nominalCurrentValue = preferredBrightness;
1813 break;
1814 case SCREEN_ON_BIT:
1815 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1816 break;
1817 case 0:
1818 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1819 break;
1820 case SCREEN_BRIGHT_BIT:
1821 default:
1822 // not possible
1823 nominalCurrentValue = (int)mScreenBrightness.curValue;
1824 break;
1825 }
Joe Onorato128e7292009-03-24 18:41:31 -07001826 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001827 int brightness = preferredBrightness;
1828 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1830 // dim or turn off backlight, depending on if the screen is on
1831 // the scale is because the brightness ramp isn't linear and this biases
1832 // it so the later parts take longer.
1833 final float scale = 1.5f;
1834 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1835 if (ratio > 1.0f) ratio = 1.0f;
1836 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1838 // was bright
1839 steps = ANIM_STEPS;
1840 } else {
1841 // was dim
1842 steps = (int)(ANIM_STEPS*ratio*scale);
1843 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001844 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 if ((oldState & SCREEN_ON_BIT) != 0) {
1847 // was bright
1848 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1849 } else {
1850 // was dim
1851 steps = (int)(ANIM_STEPS*ratio);
1852 }
1853 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1854 // If the "stay on while plugged in" option is
1855 // turned on, then the screen will often not
1856 // automatically turn off while plugged in. To
1857 // still have a sense of when it is inactive, we
1858 // will then count going dim as turning off.
1859 mScreenOffTime = SystemClock.elapsedRealtime();
1860 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001861 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001864 long identity = Binder.clearCallingIdentity();
1865 try {
1866 mBatteryStats.noteScreenBrightness(brightness);
1867 } catch (RemoteException e) {
1868 // Nothing interesting to do.
1869 } finally {
1870 Binder.restoreCallingIdentity(identity);
1871 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001872 if (mScreenBrightness.setTargetLocked(brightness,
1873 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1874 startAnimation = true;
1875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 } else {
1877 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1878 // dim or turn off backlight, depending on if the screen is on
1879 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001880 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001882 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001885 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 }
1888 }
1889
1890 if (startAnimation) {
1891 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001892 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 mHandler.removeCallbacks(mLightAnimator);
1895 mHandler.post(mLightAnimator);
1896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001899 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001900 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902 if (dimMask != 0) {
1903 int brightness = Power.BRIGHTNESS_DIM;
1904 if ((newState & BATTERY_LOW_BIT) != 0 &&
1905 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1906 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1907 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001908 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001909 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911 if (onMask != 0) {
1912 int brightness = getPreferredBrightness();
1913 if ((newState & BATTERY_LOW_BIT) != 0 &&
1914 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1915 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1916 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001917 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001918 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921
The Android Open Source Project10592532009-03-18 17:39:46 -07001922 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001923 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001924 ? LightsService.BRIGHTNESS_MODE_SENSOR
1925 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001926 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001927 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001928 }
1929 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001930 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001931 }
1932 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001933 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936
1937 class BrightnessState {
1938 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 boolean initialized;
1941 int targetValue;
1942 float curValue;
1943 float delta;
1944 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 BrightnessState(int m) {
1947 mask = m;
1948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 public void dump(PrintWriter pw, String prefix) {
1951 pw.println(prefix + "animating=" + animating
1952 + " targetValue=" + targetValue
1953 + " curValue=" + curValue
1954 + " delta=" + delta);
1955 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001956
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001957 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001958 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 if (!initialized) {
1960 initialized = true;
1961 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001962 } else if (targetValue == target) {
1963 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001966 delta = (targetValue -
1967 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1968 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001970 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001971 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001972 + " target=" + targetValue + " delta=" + delta
1973 + " nominalCurrentValue=" + nominalCurrentValue
1974 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001977 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 boolean stepLocked() {
1981 if (!animating) return false;
1982 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 + " target=" + targetValue + " delta=" + delta);
1985 }
1986 curValue += delta;
1987 int curIntValue = (int)curValue;
1988 boolean more = true;
1989 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001990 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 more = false;
1992 } else if (delta > 0) {
1993 if (curIntValue >= targetValue) {
1994 curValue = curIntValue = targetValue;
1995 more = false;
1996 }
1997 } else {
1998 if (curIntValue <= targetValue) {
1999 curValue = curIntValue = targetValue;
2000 more = false;
2001 }
2002 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08002003 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002004 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 animating = more;
2006 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002007 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002008 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 }
2010 }
2011 return more;
2012 }
2013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 private class LightAnimator implements Runnable {
2016 public void run() {
2017 synchronized (mLocks) {
2018 long now = SystemClock.uptimeMillis();
2019 boolean more = mScreenBrightness.stepLocked();
2020 if (mKeyboardBrightness.stepLocked()) {
2021 more = true;
2022 }
2023 if (mButtonBrightness.stepLocked()) {
2024 more = true;
2025 }
2026 if (more) {
2027 mHandler.postAtTime(mLightAnimator, now+(1000/60));
2028 }
2029 }
2030 }
2031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 private int getPreferredBrightness() {
2034 try {
2035 if (mScreenBrightnessOverride >= 0) {
2036 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002037 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002038 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002039 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2042 SCREEN_BRIGHTNESS);
2043 // Don't let applications turn the screen all the way off
2044 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2045 } catch (SettingNotFoundException snfe) {
2046 return Power.BRIGHTNESS_ON;
2047 }
2048 }
2049
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002050 private int applyButtonState(int state) {
2051 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002052 if ((state & BATTERY_LOW_BIT) != 0) {
2053 // do not override brightness if the battery is low
2054 return state;
2055 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002056 if (mButtonBrightnessOverride >= 0) {
2057 brightness = mButtonBrightnessOverride;
2058 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2059 brightness = mLightSensorButtonBrightness;
2060 }
2061 if (brightness > 0) {
2062 return state | BUTTON_BRIGHT_BIT;
2063 } else if (brightness == 0) {
2064 return state & ~BUTTON_BRIGHT_BIT;
2065 } else {
2066 return state;
2067 }
2068 }
2069
2070 private int applyKeyboardState(int state) {
2071 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002072 if ((state & BATTERY_LOW_BIT) != 0) {
2073 // do not override brightness if the battery is low
2074 return state;
2075 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002076 if (!mKeyboardVisible) {
2077 brightness = 0;
2078 } else if (mButtonBrightnessOverride >= 0) {
2079 brightness = mButtonBrightnessOverride;
2080 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2081 brightness = mLightSensorKeyboardBrightness;
2082 }
2083 if (brightness > 0) {
2084 return state | KEYBOARD_BRIGHT_BIT;
2085 } else if (brightness == 0) {
2086 return state & ~KEYBOARD_BRIGHT_BIT;
2087 } else {
2088 return state;
2089 }
2090 }
2091
Charles Mendis322591c2009-10-29 11:06:59 -07002092 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 synchronized (mLocks) {
2094 return (mPowerState & SCREEN_ON_BIT) != 0;
2095 }
2096 }
2097
Charles Mendis322591c2009-10-29 11:06:59 -07002098 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 synchronized (mLocks) {
2100 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2101 }
2102 }
2103
Mike Lockwood497087e32009-11-08 18:33:03 -05002104 private boolean isScreenTurningOffLocked() {
2105 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2106 }
2107
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002108 private boolean shouldLog(long time) {
2109 synchronized (mLocks) {
2110 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2111 mWarningSpewThrottleTime = time;
2112 mWarningSpewThrottleCount = 0;
2113 return true;
2114 } else if (mWarningSpewThrottleCount < 30) {
2115 mWarningSpewThrottleCount++;
2116 return true;
2117 } else {
2118 return false;
2119 }
2120 }
2121 }
2122
Mike Lockwood200b30b2009-09-20 00:23:59 -04002123 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002124 if (isScreenTurningOffLocked()) {
2125 // cancel animation so userActivity will succeed
2126 mScreenBrightness.animating = false;
2127 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002128 boolean savedActivityAllowed = mUserActivityAllowed;
2129 mUserActivityAllowed = true;
2130 userActivity(SystemClock.uptimeMillis(), false);
2131 mUserActivityAllowed = savedActivityAllowed;
2132 }
2133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2135 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002136 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
2138
2139 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002140 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2141 != PackageManager.PERMISSION_GRANTED) {
2142 if (shouldLog(time)) {
2143 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2144 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2145 }
2146 return;
2147 }
2148
Joe Onorato7999bff2010-07-24 11:50:05 -04002149 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
2151
2152 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002153 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155
2156 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002157 userActivity(time, -1, noChangeLights, eventType, force);
2158 }
2159
2160 /*
2161 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2162 * on with user activity. Don't use this function.
2163 */
2164 public void clearUserActivityTimeout(long now, long timeout) {
2165 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2166 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2167 userActivity(now, timeout, false, OTHER_EVENT, false);
2168 }
2169
2170 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2171 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172
2173 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002174 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002176 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
2178 return;
2179 }
2180
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002181 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2182 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2183 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2184 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002185 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002186 }
2187 return;
2188 }
2189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 if (false) {
2191 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196 }
2197
2198 synchronized (mLocks) {
2199 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002200 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 + " mUserActivityAllowed=" + mUserActivityAllowed
2202 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002203 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2204 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002205 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002206 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 }
Mike Lockwood05067122009-10-27 23:07:25 -04002208 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002209 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002210 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002211 return;
2212 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002213 // Disable proximity sensor if if user presses power key while we are in the
2214 // "waiting for proximity sensor to go negative" state.
2215 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2216 mProximitySensorActive = false;
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 if (mLastEventTime <= time || force) {
2219 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002220 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002221 // Only turn on button backlights if a button was pressed
2222 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002223 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2225 } else {
2226 // don't clear button/keyboard backlights when the screen is touched.
2227 mUserState |= SCREEN_BRIGHT;
2228 }
2229
Dianne Hackborn617f8772009-03-31 15:04:46 -07002230 int uid = Binder.getCallingUid();
2231 long ident = Binder.clearCallingIdentity();
2232 try {
2233 mBatteryStats.noteUserActivity(uid, eventType);
2234 } catch (RemoteException e) {
2235 // Ignore
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002239
Michael Chane96440f2009-05-06 10:27:36 -07002240 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002241 setPowerState(mUserState | mWakeLockState, noChangeLights,
2242 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002243 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245 }
2246 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002247
2248 if (mPolicy != null) {
2249 mPolicy.userActivity();
2250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 }
2252
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002253 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2254 try {
2255 int i;
2256 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2257 if (sensorValue < mAutoBrightnessLevels[i]) {
2258 break;
2259 }
2260 }
2261 return values[i];
2262 } catch (Exception e) {
2263 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002264 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002265 return 255;
2266 }
2267 }
2268
Mike Lockwood20f87d72009-11-05 16:08:51 -05002269 private Runnable mProximityTask = new Runnable() {
2270 public void run() {
2271 synchronized (mLocks) {
2272 if (mProximityPendingValue != -1) {
2273 proximityChangedLocked(mProximityPendingValue == 1);
2274 mProximityPendingValue = -1;
2275 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002276 if (mProximityPartialLock.isHeld()) {
2277 mProximityPartialLock.release();
2278 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002279 }
2280 }
2281 };
2282
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002283 private Runnable mAutoBrightnessTask = new Runnable() {
2284 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002285 synchronized (mLocks) {
2286 int value = (int)mLightSensorPendingValue;
2287 if (value >= 0) {
2288 mLightSensorPendingValue = -1;
2289 lightSensorChangedLocked(value);
2290 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002291 }
2292 }
2293 };
2294
Mike Lockwoodb2865412010-02-02 22:40:33 -05002295 private void dockStateChanged(int state) {
2296 synchronized (mLocks) {
2297 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2298 if (mIsDocked) {
2299 mHighestLightSensorValue = -1;
2300 }
2301 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2302 // force lights recalculation
2303 int value = (int)mLightSensorValue;
2304 mLightSensorValue = -1;
2305 lightSensorChangedLocked(value);
2306 }
2307 }
2308 }
2309
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002310 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002311 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002312 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002313 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002314
Mike Lockwoodb2865412010-02-02 22:40:33 -05002315 // do not allow light sensor value to decrease
2316 if (mHighestLightSensorValue < value) {
2317 mHighestLightSensorValue = value;
2318 }
2319
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002320 if (mLightSensorValue != value) {
2321 mLightSensorValue = value;
2322 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002323 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2324 // we only do this if we are undocked, since lighting should be stable when
2325 // stationary in a dock.
2326 int lcdValue = getAutoBrightnessValue(
2327 (mIsDocked ? value : mHighestLightSensorValue),
2328 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002329 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002330 int keyboardValue;
2331 if (mKeyboardVisible) {
2332 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2333 } else {
2334 keyboardValue = 0;
2335 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002336 mLightSensorScreenBrightness = lcdValue;
2337 mLightSensorButtonBrightness = buttonValue;
2338 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002339
2340 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002341 Slog.d(TAG, "lcdValue " + lcdValue);
2342 Slog.d(TAG, "buttonValue " + buttonValue);
2343 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002344 }
2345
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002346 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002347 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002348 if (ANIMATE_SCREEN_LIGHTS) {
2349 if (mScreenBrightness.setTargetLocked(lcdValue,
2350 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2351 (int)mScreenBrightness.curValue)) {
2352 startAnimation = true;
2353 }
2354 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002355 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002356 ? LightsService.BRIGHTNESS_MODE_SENSOR
2357 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002358 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002359 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002360 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002361 if (mButtonBrightnessOverride < 0) {
2362 if (ANIMATE_BUTTON_LIGHTS) {
2363 if (mButtonBrightness.setTargetLocked(buttonValue,
2364 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2365 (int)mButtonBrightness.curValue)) {
2366 startAnimation = true;
2367 }
2368 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002369 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002370 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002371 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002372 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2373 if (ANIMATE_KEYBOARD_LIGHTS) {
2374 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2375 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2376 (int)mKeyboardBrightness.curValue)) {
2377 startAnimation = true;
2378 }
2379 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002380 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002381 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002382 }
2383 if (startAnimation) {
2384 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002385 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002386 }
2387 mHandler.removeCallbacks(mLightAnimator);
2388 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002389 }
2390 }
2391 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002392 }
2393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 /**
2395 * The user requested that we go to sleep (probably with the power button).
2396 * This overrides all wake locks that are held.
2397 */
2398 public void goToSleep(long time)
2399 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002400 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2401 }
2402
2403 /**
2404 * The user requested that we go to sleep (probably with the power button).
2405 * This overrides all wake locks that are held.
2406 */
2407 public void goToSleepWithReason(long time, int reason)
2408 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2410 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002411 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 }
2413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002416 * Reboot the device immediately, passing 'reason' (may be null)
2417 * to the underlying __reboot system call. Should not return.
2418 */
2419 public void reboot(String reason)
2420 {
2421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002422
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002423 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2424 throw new IllegalStateException("Too early to call reboot()");
2425 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002426
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002427 final String finalReason = reason;
2428 Runnable runnable = new Runnable() {
2429 public void run() {
2430 synchronized (this) {
2431 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002432 }
2433
San Mehat1e512792010-01-07 10:40:29 -08002434 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002435 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002436 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002437 mHandler.post(runnable);
2438
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002439 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002440 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002441 while (true) {
2442 try {
2443 runnable.wait();
2444 } catch (InterruptedException e) {
2445 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002446 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002447 }
2448 }
2449
Dan Egnor60d87622009-12-16 16:32:58 -08002450 /**
2451 * Crash the runtime (causing a complete restart of the Android framework).
2452 * Requires REBOOT permission. Mostly for testing. Should not return.
2453 */
2454 public void crash(final String message)
2455 {
2456 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2457 Thread t = new Thread("PowerManagerService.crash()") {
2458 public void run() { throw new RuntimeException(message); }
2459 };
2460 try {
2461 t.start();
2462 t.join();
2463 } catch (InterruptedException e) {
2464 Log.wtf(TAG, e);
2465 }
2466 }
2467
Mike Lockwood435eb642009-12-03 08:40:18 -05002468 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469
2470 if (mLastEventTime <= time) {
2471 mLastEventTime = time;
2472 // cancel all of the wake locks
2473 mWakeLockState = SCREEN_OFF;
2474 int N = mLocks.size();
2475 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002476 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 for (int i=0; i<N; i++) {
2478 WakeLock wl = mLocks.get(i);
2479 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002480 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2481 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2482 proxLock = true;
2483 } else {
2484 mLocks.get(i).activated = false;
2485 numCleared++;
2486 }
2487 }
2488 }
2489 if (!proxLock) {
2490 mProxIgnoredBecauseScreenTurnedOff = true;
2491 if (mDebugProximitySensor) {
2492 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
2494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002495 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002496 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002498 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 cancelTimerLocked();
2500 }
2501 }
2502
2503 public long timeSinceScreenOn() {
2504 synchronized (mLocks) {
2505 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2506 return 0;
2507 }
2508 return SystemClock.elapsedRealtime() - mScreenOffTime;
2509 }
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002513 synchronized (mLocks) {
2514 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002515 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002516 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002517 if (mKeyboardVisible != visible) {
2518 mKeyboardVisible = visible;
2519 // don't signal user activity if the screen is off; other code
2520 // will take care of turning on due to a true change to the lid
2521 // switch and synchronized with the lock screen.
2522 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002523 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002524 // force recompute of backlight values
2525 if (mLightSensorValue >= 0) {
2526 int value = (int)mLightSensorValue;
2527 mLightSensorValue = -1;
2528 lightSensorChangedLocked(value);
2529 }
2530 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002531 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2532 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002533 }
2534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536
2537 /**
2538 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002539 * When disabling user activity we also reset user power state so the keyguard can reset its
2540 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 */
2542 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002543 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002544 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 synchronized (mLocks) {
2547 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002548 if (!enabled) {
2549 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2550 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
2553 }
2554
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002555 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002556 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002557 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002558 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002559 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002560 // force recompute of backlight values
2561 if (mLightSensorValue >= 0) {
2562 int value = (int)mLightSensorValue;
2563 mLightSensorValue = -1;
2564 lightSensorChangedLocked(value);
2565 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002566 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002567 }
2568 }
2569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 /** Sets the screen off timeouts:
2571 * mKeylightDelay
2572 * mDimDelay
2573 * mScreenOffDelay
2574 * */
2575 private void setScreenOffTimeoutsLocked() {
2576 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002577 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 mDimDelay = -1;
2579 mScreenOffDelay = 0;
2580 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2581 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2582 mDimDelay = -1;
2583 mScreenOffDelay = 0;
2584 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002585 int totalDelay = mScreenOffTimeoutSetting;
2586 if (totalDelay > mMaximumScreenOffTimeout) {
2587 totalDelay = mMaximumScreenOffTimeout;
2588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2590 if (totalDelay < 0) {
2591 mScreenOffDelay = Integer.MAX_VALUE;
2592 } else if (mKeylightDelay < totalDelay) {
2593 // subtract the time that the keylight delay. This will give us the
2594 // remainder of the time that we need to sleep to get the accurate
2595 // screen off timeout.
2596 mScreenOffDelay = totalDelay - mKeylightDelay;
2597 } else {
2598 mScreenOffDelay = 0;
2599 }
2600 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2601 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2602 mScreenOffDelay = LONG_DIM_TIME;
2603 } else {
2604 mDimDelay = -1;
2605 }
2606 }
2607 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002608 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2610 + " mDimScreen=" + mDimScreen);
2611 }
2612 }
2613
2614 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002615 * Refreshes cached secure settings. Called once on startup, and
2616 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 */
Doug Zongker43866e02010-01-07 12:09:54 -08002618 private void updateSettingsValues() {
2619 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002621 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002623 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625
2626 private class LockList extends ArrayList<WakeLock>
2627 {
2628 void addLock(WakeLock wl)
2629 {
2630 int index = getIndex(wl.binder);
2631 if (index < 0) {
2632 this.add(wl);
2633 }
2634 }
2635
2636 WakeLock removeLock(IBinder binder)
2637 {
2638 int index = getIndex(binder);
2639 if (index >= 0) {
2640 return this.remove(index);
2641 } else {
2642 return null;
2643 }
2644 }
2645
2646 int getIndex(IBinder binder)
2647 {
2648 int N = this.size();
2649 for (int i=0; i<N; i++) {
2650 if (this.get(i).binder == binder) {
2651 return i;
2652 }
2653 }
2654 return -1;
2655 }
2656
2657 int gatherState()
2658 {
2659 int result = 0;
2660 int N = this.size();
2661 for (int i=0; i<N; i++) {
2662 WakeLock wl = this.get(i);
2663 if (wl.activated) {
2664 if (isScreenLock(wl.flags)) {
2665 result |= wl.minState;
2666 }
2667 }
2668 }
2669 return result;
2670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002671
Michael Chane96440f2009-05-06 10:27:36 -07002672 int reactivateScreenLocksLocked()
2673 {
2674 int result = 0;
2675 int N = this.size();
2676 for (int i=0; i<N; i++) {
2677 WakeLock wl = this.get(i);
2678 if (isScreenLock(wl.flags)) {
2679 wl.activated = true;
2680 result |= wl.minState;
2681 }
2682 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002683 if (mDebugProximitySensor) {
2684 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2685 + mProxIgnoredBecauseScreenTurnedOff);
2686 }
2687 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002688 return result;
2689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
2691
2692 void setPolicy(WindowManagerPolicy p) {
2693 synchronized (mLocks) {
2694 mPolicy = p;
2695 mLocks.notifyAll();
2696 }
2697 }
2698
2699 WindowManagerPolicy getPolicyLocked() {
2700 while (mPolicy == null || !mDoneBooting) {
2701 try {
2702 mLocks.wait();
2703 } catch (InterruptedException e) {
2704 // Ignore
2705 }
2706 }
2707 return mPolicy;
2708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002711 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2712 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2713 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002714 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002715 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002716 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002717 }
2718
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002719 // wait until sensors are enabled before turning on screen.
2720 // some devices will not activate the light sensor properly on boot
2721 // unless we do this.
2722 if (mUseSoftwareAutoBrightness) {
2723 // turn the screen on
2724 setPowerState(SCREEN_BRIGHT);
2725 } else {
2726 // turn everything on
2727 setPowerState(ALL_BRIGHT);
2728 }
2729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002731 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002733
Dianne Hackborn617f8772009-03-31 15:04:46 -07002734 long identity = Binder.clearCallingIdentity();
2735 try {
2736 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2737 mBatteryStats.noteScreenOn();
2738 } catch (RemoteException e) {
2739 // Nothing interesting to do.
2740 } finally {
2741 Binder.restoreCallingIdentity(identity);
2742 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002743 }
2744 }
2745
2746 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002747 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002748 synchronized (mLocks) {
2749 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2751 updateWakeLockLocked();
2752 mLocks.notifyAll();
2753 }
2754 }
2755
2756 public void monitor() {
2757 synchronized (mLocks) { }
2758 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002759
2760 public int getSupportedWakeLockFlags() {
2761 int result = PowerManager.PARTIAL_WAKE_LOCK
2762 | PowerManager.FULL_WAKE_LOCK
2763 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2764
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002765 if (mProximitySensor != null) {
2766 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2767 }
2768
2769 return result;
2770 }
2771
Mike Lockwood237a2992009-09-15 14:42:16 -04002772 public void setBacklightBrightness(int brightness) {
2773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2774 // Don't let applications turn the screen all the way off
2775 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002776 mLcdLight.setBrightness(brightness);
2777 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2778 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002779 long identity = Binder.clearCallingIdentity();
2780 try {
2781 mBatteryStats.noteScreenBrightness(brightness);
2782 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002783 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002784 } finally {
2785 Binder.restoreCallingIdentity(identity);
2786 }
2787
2788 // update our animation state
2789 if (ANIMATE_SCREEN_LIGHTS) {
2790 mScreenBrightness.curValue = brightness;
2791 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002792 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002793 }
2794 if (ANIMATE_KEYBOARD_LIGHTS) {
2795 mKeyboardBrightness.curValue = brightness;
2796 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002797 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002798 }
2799 if (ANIMATE_BUTTON_LIGHTS) {
2800 mButtonBrightness.curValue = brightness;
2801 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002802 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002803 }
2804 }
2805
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002806 public void setAttentionLight(boolean on, int color) {
2807 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002808 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002809 }
2810
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002811 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002812 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002813 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002814 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002815 if (!mProximitySensorEnabled) {
2816 // clear calling identity so sensor manager battery stats are accurate
2817 long identity = Binder.clearCallingIdentity();
2818 try {
2819 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2820 SensorManager.SENSOR_DELAY_NORMAL);
2821 mProximitySensorEnabled = true;
2822 } finally {
2823 Binder.restoreCallingIdentity(identity);
2824 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002825 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002826 }
2827
2828 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002829 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002830 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002831 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002832 if (mProximitySensorEnabled) {
2833 // clear calling identity so sensor manager battery stats are accurate
2834 long identity = Binder.clearCallingIdentity();
2835 try {
2836 mSensorManager.unregisterListener(mProximityListener);
2837 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002838 if (mProximityPartialLock.isHeld()) {
2839 mProximityPartialLock.release();
2840 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002841 mProximitySensorEnabled = false;
2842 } finally {
2843 Binder.restoreCallingIdentity(identity);
2844 }
2845 if (mProximitySensorActive) {
2846 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002847 if (mDebugProximitySensor) {
2848 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2849 + mProxIgnoredBecauseScreenTurnedOff);
2850 }
2851 if (!mProxIgnoredBecauseScreenTurnedOff) {
2852 forceUserActivityLocked();
2853 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002854 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002855 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002856 }
2857
Mike Lockwood20f87d72009-11-05 16:08:51 -05002858 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002859 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002860 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002861 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002862 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002863 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002864 return;
2865 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002866 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002867 if (mDebugProximitySensor) {
2868 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2869 + mProxIgnoredBecauseScreenTurnedOff);
2870 }
2871 if (!mProxIgnoredBecauseScreenTurnedOff) {
2872 goToSleepLocked(SystemClock.uptimeMillis(),
2873 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2874 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002875 mProximitySensorActive = true;
2876 } else {
2877 // proximity sensor negative events trigger as user activity.
2878 // temporarily set mUserActivityAllowed to true so this will work
2879 // even when the keyguard is on.
2880 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002881 if (mDebugProximitySensor) {
2882 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2883 + mProxIgnoredBecauseScreenTurnedOff);
2884 }
2885 if (!mProxIgnoredBecauseScreenTurnedOff) {
2886 forceUserActivityLocked();
2887 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002888
2889 if (mProximityWakeLockCount == 0) {
2890 // disable sensor if we have no listeners left after proximity negative
2891 disableProximityLockLocked();
2892 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002893 }
2894 }
2895
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002896 private void enableLightSensor(boolean enable) {
2897 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002898 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002899 }
2900 if (mSensorManager != null && mLightSensorEnabled != enable) {
2901 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002902 // clear calling identity so sensor manager battery stats are accurate
2903 long identity = Binder.clearCallingIdentity();
2904 try {
2905 if (enable) {
2906 mSensorManager.registerListener(mLightListener, mLightSensor,
2907 SensorManager.SENSOR_DELAY_NORMAL);
2908 } else {
2909 mSensorManager.unregisterListener(mLightListener);
2910 mHandler.removeCallbacks(mAutoBrightnessTask);
2911 }
2912 } finally {
2913 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002914 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002915 }
2916 }
2917
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002918 SensorEventListener mProximityListener = new SensorEventListener() {
2919 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002920 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002921 synchronized (mLocks) {
2922 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002923 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2924 mLastProximityEventTime = milliseconds;
2925 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002926 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002927
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002928 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002929 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2930 distance < mProximitySensor.getMaximumRange());
2931
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002932 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002933 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002934 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002935 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2936 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2937 mProximityPendingValue = (active ? 1 : 0);
2938 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002939 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002940 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002941 // process the value immediately
2942 mProximityPendingValue = -1;
2943 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002944 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002945
2946 // update mProximityPartialLock state
2947 boolean held = mProximityPartialLock.isHeld();
2948 if (!held && proximityTaskQueued) {
2949 // hold wakelock until mProximityTask runs
2950 mProximityPartialLock.acquire();
2951 } else if (held && !proximityTaskQueued) {
2952 mProximityPartialLock.release();
2953 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002954 }
2955 }
2956
2957 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2958 // ignore
2959 }
2960 };
2961
2962 SensorEventListener mLightListener = new SensorEventListener() {
2963 public void onSensorChanged(SensorEvent event) {
2964 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002965 // ignore light sensor while screen is turning off
2966 if (isScreenTurningOffLocked()) {
2967 return;
2968 }
2969
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002970 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002971 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002972 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002973 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002974 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002975 mHandler.removeCallbacks(mAutoBrightnessTask);
2976 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002977 if (mLightSensorValue == -1 ||
2978 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2979 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002980 lightSensorChangedLocked(value);
2981 } else {
2982 // delay processing to debounce the sensor
2983 mLightSensorPendingValue = value;
2984 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2985 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002986 } else {
2987 mLightSensorPendingValue = -1;
2988 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002989 }
2990 }
2991
2992 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2993 // ignore
2994 }
2995 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996}