blob: d80a2cd41c2db42abe446c4908d394a1bf93a181 [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;
43import android.os.Handler;
44import android.os.HandlerThread;
45import android.os.IBinder;
46import android.os.IPowerManager;
47import android.os.LocalPowerManager;
48import android.os.Power;
49import android.os.PowerManager;
50import android.os.Process;
51import android.os.RemoteException;
52import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070053import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings.SettingNotFoundException;
55import android.provider.Settings;
56import android.util.EventLog;
57import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.WindowManagerPolicy;
60import static android.provider.Settings.System.DIM_SCREEN;
61import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070063import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
65import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070066import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
67import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69import java.io.FileDescriptor;
70import java.io.PrintWriter;
71import java.util.ArrayList;
72import java.util.HashMap;
73import java.util.Observable;
74import java.util.Observer;
75
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080076public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040077 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79 private static final String TAG = "PowerManagerService";
80 static final String PARTIAL_NAME = "PowerManagerService";
81
82 private static final boolean LOG_PARTIAL_WL = false;
83
84 // Indicates whether touch-down cycles should be logged as part of the
85 // LOG_POWER_SCREEN_STATE log events
86 private static final boolean LOG_TOUCH_DOWNS = true;
87
88 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
89 | PowerManager.SCREEN_DIM_WAKE_LOCK
90 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070091 | PowerManager.FULL_WAKE_LOCK
92 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080095 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
97 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
98 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
99 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
100
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500102 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700103
Mike Lockwood20f87d72009-11-05 16:08:51 -0500104 // For debouncing the proximity sensor.
105 private static final int PROXIMITY_SENSOR_DELAY = 1000;
106
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400107 // trigger proximity if distance is less than 5 cm
108 private static final float PROXIMITY_THRESHOLD = 5.0f;
109
Doug Zongker43866e02010-01-07 12:09:54 -0800110 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
112
Amith Yamasani8b619832010-09-22 16:11:59 -0700113 // Default timeout for screen off, if not found in settings database = 15 seconds.
114 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 // flags for setPowerState
117 private static final int SCREEN_ON_BIT = 0x00000001;
118 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
119 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
120 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
121 private static final int BATTERY_LOW_BIT = 0x00000010;
122
123 // values for setPowerState
124
125 // SCREEN_OFF == everything off
126 private static final int SCREEN_OFF = 0x00000000;
127
128 // SCREEN_DIM == screen on, screen backlight dim
129 private static final int SCREEN_DIM = SCREEN_ON_BIT;
130
131 // SCREEN_BRIGHT == screen on, screen backlight bright
132 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
133
134 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
135 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
136
137 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
138 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
139
140 // used for noChangeLights in setPowerState()
141 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
142
Joe Onoratob08a1af2010-10-11 19:28:58 -0700143 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400146 // Slower animation for autobrightness changes
147 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 // These magic numbers are the initial state of the LEDs at boot. Ideally
150 // we should read them from the driver, but our current hardware returns 0
151 // for the initial value. Oops!
152 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
153 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
154 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700157 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
159 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500160 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500162 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
163 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mPartialCount = 0;
165 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500166 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
167 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
168 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 private int mUserState;
170 private boolean mKeyboardVisible = false;
171 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500172 private int mProximityWakeLockCount = 0;
173 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700174 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500175 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
176 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800177 private int mScreenOffTimeoutSetting;
178 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 private int mKeylightDelay;
180 private int mDimDelay;
181 private int mScreenOffDelay;
182 private int mWakeLockState;
183 private long mLastEventTime = 0;
184 private long mScreenOffTime;
185 private volatile WindowManagerPolicy mPolicy;
186 private final LockList mLocks = new LockList();
187 private Intent mScreenOffIntent;
188 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500189 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500191 private LightsService.Light mLcdLight;
192 private LightsService.Light mButtonLight;
193 private LightsService.Light mKeyboardLight;
194 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private UnsynchronizedWakeLock mBroadcastWakeLock;
196 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
197 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
198 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500199 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700201 private HandlerThread mScreenOffThread;
202 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500204 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700206 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700207 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private boolean mIsPowered = false;
209 private IActivityManager mActivityService;
210 private IBatteryStats mBatteryStats;
211 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700212 private SensorManager mSensorManager;
213 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400214 private Sensor mLightSensor;
215 private boolean mLightSensorEnabled;
216 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400217 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500218 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500219 private boolean mLightSensorPendingDecrease = false;
220 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700221 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500222 private int mLightSensorScreenBrightness = -1;
223 private int mLightSensorButtonBrightness = -1;
224 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500226 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private long mNextTimeout;
228 private volatile int mPokey = 0;
229 private volatile boolean mPokeAwakeOnSet = false;
230 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500231 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500232 // mLastScreenOnTime is the time the screen was last turned on
233 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private boolean mPreventScreenOn;
235 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500236 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400237 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700238 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700239 private int[] mAutoBrightnessLevels;
240 private int[] mLcdBacklightValues;
241 private int[] mButtonBacklightValues;
242 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500243 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700244 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700245 private int mWarningSpewThrottleCount;
246 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700247 private int mAnimationSetting = ANIM_SETTING_OFF;
248
249 // Must match with the ISurfaceComposer constants in C++.
250 private static final int ANIM_SETTING_ON = 0x01;
251 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 // Used when logging number and duration of touch-down cycles
254 private long mTotalTouchDownTime;
255 private long mLastTouchDown;
256 private int mTouchCycles;
257
258 // could be either static or controllable at runtime
259 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400260 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400261 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700262
263 private native void nativeInit();
264 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700265 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 /*
268 static PrintStream mLog;
269 static {
270 try {
271 mLog = new PrintStream("/data/power.log");
272 }
273 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800274 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276 }
277 static class Log {
278 static void d(String tag, String s) {
279 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800280 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 }
282 static void i(String tag, String s) {
283 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800284 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 }
286 static void w(String tag, String s) {
287 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800288 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 }
290 static void e(String tag, String s) {
291 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800292 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 }
294 }
295 */
296
297 /**
298 * This class works around a deadlock between the lock in PowerManager.WakeLock
299 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
300 * mToken object so it can be accessed from any thread, but it calls into here
301 * with its lock held. This class is essentially a reimplementation of
302 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
303 * only call it with our own locks held.
304 */
305 private class UnsynchronizedWakeLock {
306 int mFlags;
307 String mTag;
308 IBinder mToken;
309 int mCount = 0;
310 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500311 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312
313 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
314 mFlags = flags;
315 mTag = tag;
316 mToken = new Binder();
317 mRefCounted = refCounted;
318 }
319
320 public void acquire() {
321 if (!mRefCounted || mCount++ == 0) {
322 long ident = Binder.clearCallingIdentity();
323 try {
324 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700325 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500326 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 } finally {
328 Binder.restoreCallingIdentity(ident);
329 }
330 }
331 }
332
333 public void release() {
334 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500335 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500336 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338 if (mCount < 0) {
339 throw new RuntimeException("WakeLock under-locked " + mTag);
340 }
341 }
342
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500343 public boolean isHeld()
344 {
345 return mHeld;
346 }
347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 public String toString() {
349 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500350 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352 }
353
354 private final class BatteryReceiver extends BroadcastReceiver {
355 @Override
356 public void onReceive(Context context, Intent intent) {
357 synchronized (mLocks) {
358 boolean wasPowered = mIsPowered;
359 mIsPowered = mBatteryService.isPowered();
360
361 if (mIsPowered != wasPowered) {
362 // update mStayOnWhilePluggedIn wake lock
363 updateWakeLockLocked();
364
365 // treat plugging and unplugging the devices as a user activity.
366 // users find it disconcerting when they unplug the device
367 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500368 // to avoid turning on the screen when unplugging, we only trigger
369 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 // temporarily set mUserActivityAllowed to true so this will work
371 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700372 // However, you can also set config_unplugTurnsOnScreen to have it
373 // turn on. Some devices want this because they don't have a
374 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700376 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
377 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500378 forceUserActivityLocked();
379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381 }
382 }
383 }
384 }
385
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500386 private final class BootCompletedReceiver extends BroadcastReceiver {
387 @Override
388 public void onReceive(Context context, Intent intent) {
389 bootCompleted();
390 }
391 }
392
Mike Lockwoodb2865412010-02-02 22:40:33 -0500393 private final class DockReceiver extends BroadcastReceiver {
394 @Override
395 public void onReceive(Context context, Intent intent) {
396 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
397 Intent.EXTRA_DOCK_STATE_UNDOCKED);
398 dockStateChanged(state);
399 }
400 }
401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 /**
403 * Set the setting that determines whether the device stays on when plugged in.
404 * The argument is a bit string, with each bit specifying a power source that,
405 * when the device is connected to that source, causes the device to stay on.
406 * See {@link android.os.BatteryManager} for the list of power sources that
407 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
408 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
409 * @param val an {@code int} containing the bits that specify which power sources
410 * should cause the device to stay on.
411 */
412 public void setStayOnSetting(int val) {
413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
414 Settings.System.putInt(mContext.getContentResolver(),
415 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
416 }
417
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800418 public void setMaximumScreenOffTimeount(int timeMs) {
419 mContext.enforceCallingOrSelfPermission(
420 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
421 synchronized (mLocks) {
422 mMaximumScreenOffTimeout = timeMs;
423 // recalculate everything
424 setScreenOffTimeoutsLocked();
425 }
426 }
427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700429 private int getInt(String name, int defValue) {
430 ContentValues values = mSettings.getValues(name);
431 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
432 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 }
434
Joe Onorato609695d2010-10-14 14:57:49 -0700435 private float getFloat(String name, float defValue) {
436 ContentValues values = mSettings.getValues(name);
437 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
438 return fVal != null ? fVal : defValue;
439 }
440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 public void update(Observable o, Object arg) {
442 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700443 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
444 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
445 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 updateWakeLockLocked();
447
Amith Yamasani8b619832010-09-22 16:11:59 -0700448 // SCREEN_OFF_TIMEOUT, default to 15 seconds
449 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
Joe Onorato609695d2010-10-14 14:57:49 -0700451 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 //mDimScreen = getInt(DIM_SCREEN) != 0;
453
Amith Yamasani8b619832010-09-22 16:11:59 -0700454 // SCREEN_BRIGHTNESS_MODE, default to manual
455 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
456 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 // recalculate everything
459 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700460
461 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
462 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
463 mAnimationSetting = 0;
464 if (windowScale > 0.5f) {
465 mAnimationSetting |= ANIM_SETTING_OFF;
466 }
467 if (transitionScale > 0.5f) {
468 // Uncomment this if you want the screen-on animation.
469 // mAnimationSetting |= ANIM_SETTING_ON;
470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
472 }
473 }
474
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700475 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 // Hack to get our uid... should have a func for this.
477 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700478 MY_UID = Process.myUid();
479 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 Binder.restoreCallingIdentity(token);
481
482 // XXX remove this when the kernel doesn't timeout wake locks
483 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
484
485 // assume nothing is on yet
486 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 // Add ourself to the Watchdog monitors.
489 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 }
491
492 private ContentQueryMap mSettings;
493
Mike Lockwood3a322132009-11-24 00:30:52 -0500494 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700495 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500496 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 mContext = context;
498 mActivityService = activity;
499 mBatteryStats = BatteryStatsService.getService();
500 mBatteryService = battery;
501
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500502 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
503 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
504 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
505 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
506
Joe Onoratob08a1af2010-10-11 19:28:58 -0700507 nativeInit();
508 synchronized (mLocks) {
509 updateNativePowerStateLocked();
510 }
511
512 mInitComplete = false;
513 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
514 @Override
515 protected void onLooperPrepared() {
516 mScreenOffHandler = new Handler();
517 synchronized (mScreenOffThread) {
518 mInitComplete = true;
519 mScreenOffThread.notifyAll();
520 }
521 }
522 };
523 mScreenOffThread.start();
524
525 synchronized (mScreenOffThread) {
526 while (!mInitComplete) {
527 try {
528 mScreenOffThread.wait();
529 } catch (InterruptedException e) {
530 // Ignore
531 }
532 }
533 }
534
535 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 mHandlerThread = new HandlerThread("PowerManagerService") {
537 @Override
538 protected void onLooperPrepared() {
539 super.onLooperPrepared();
540 initInThread();
541 }
542 };
543 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 synchronized (mHandlerThread) {
546 while (!mInitComplete) {
547 try {
548 mHandlerThread.wait();
549 } catch (InterruptedException e) {
550 // Ignore
551 }
552 }
553 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700554
555 nativeInit();
556 synchronized (mLocks) {
557 updateNativePowerStateLocked();
558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 void initInThread() {
562 mHandler = new Handler();
563
564 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700565 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
567 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
568 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
569 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
570 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
571 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500572 mProximityPartialLock = new UnsynchronizedWakeLock(
573 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574
575 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
576 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
577 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
578 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
579
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700580 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400581
Joe Onoratob08a1af2010-10-11 19:28:58 -0700582 mAnimateScreenLights = resources.getBoolean(
583 com.android.internal.R.bool.config_animateScreenLights);
584
Joe Onorato6d747652010-10-11 15:15:31 -0700585 mUnplugTurnsOnScreen = resources.getBoolean(
586 com.android.internal.R.bool.config_unplugTurnsOnScreen);
587
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400588 // read settings for auto-brightness
589 mUseSoftwareAutoBrightness = resources.getBoolean(
590 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400591 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700592 mAutoBrightnessLevels = resources.getIntArray(
593 com.android.internal.R.array.config_autoBrightnessLevels);
594 mLcdBacklightValues = resources.getIntArray(
595 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
596 mButtonBacklightValues = resources.getIntArray(
597 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
598 mKeyboardBacklightValues = resources.getIntArray(
599 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500600 mLightSensorWarmupTime = resources.getInteger(
601 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700602 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700603
604 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
606 "(" + Settings.System.NAME + "=?) or ("
607 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700608 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700609 + Settings.System.NAME + "=?) or ("
610 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700612 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700613 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 null);
615 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
616 SettingsObserver settingsObserver = new SettingsObserver();
617 mSettings.addObserver(settingsObserver);
618
619 // pretend that the settings changed so we will get their initial state
620 settingsObserver.update(mSettings, null);
621
622 // register for the battery changed notifications
623 IntentFilter filter = new IntentFilter();
624 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
625 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500626 filter = new IntentFilter();
627 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
628 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500629 filter = new IntentFilter();
630 filter.addAction(Intent.ACTION_DOCK_EVENT);
631 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632
Doug Zongker43866e02010-01-07 12:09:54 -0800633 // Listen for secure settings changes
634 mContext.getContentResolver().registerContentObserver(
635 Settings.Secure.CONTENT_URI, true,
636 new ContentObserver(new Handler()) {
637 public void onChange(boolean selfChange) {
638 updateSettingsValues();
639 }
640 });
641 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 synchronized (mHandlerThread) {
644 mInitComplete = true;
645 mHandlerThread.notifyAll();
646 }
647 }
648
649 private class WakeLock implements IBinder.DeathRecipient
650 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700651 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 super();
653 flags = f;
654 binder = b;
655 tag = t;
656 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700657 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 if (u != MY_UID || (
659 !"KEEP_SCREEN_ON_FLAG".equals(tag)
660 && !"KeyInputQueue".equals(tag))) {
661 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
662 ? BatteryStats.WAKE_TYPE_PARTIAL
663 : BatteryStats.WAKE_TYPE_FULL;
664 } else {
665 monitorType = -1;
666 }
667 try {
668 b.linkToDeath(this, 0);
669 } catch (RemoteException e) {
670 binderDied();
671 }
672 }
673 public void binderDied() {
674 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500675 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677 }
678 final int flags;
679 final IBinder binder;
680 final String tag;
681 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400682 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700684 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 boolean activated = true;
686 int minState;
687 }
688
689 private void updateWakeLockLocked() {
690 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
691 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
692 mStayOnWhilePluggedInScreenDimLock.acquire();
693 mStayOnWhilePluggedInPartialLock.acquire();
694 } else {
695 mStayOnWhilePluggedInScreenDimLock.release();
696 mStayOnWhilePluggedInPartialLock.release();
697 }
698 }
699
700 private boolean isScreenLock(int flags)
701 {
702 int n = flags & LOCK_MASK;
703 return n == PowerManager.FULL_WAKE_LOCK
704 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400705 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
706 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
708
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700709 void enforceWakeSourcePermission(int uid, int pid) {
710 if (uid == Process.myUid()) {
711 return;
712 }
713 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
714 pid, uid, null);
715 }
716
717 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700719 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700720 if (uid != Process.myUid()) {
721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
722 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700723 if (ws != null) {
724 enforceWakeSourcePermission(uid, pid);
725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 long ident = Binder.clearCallingIdentity();
727 try {
728 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700729 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
731 } finally {
732 Binder.restoreCallingIdentity(ident);
733 }
734 }
735
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700736 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700737 if (wl.monitorType >= 0) {
738 long origId = Binder.clearCallingIdentity();
739 try {
740 if (ws != null) {
741 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
742 wl.monitorType);
743 } else {
744 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
745 }
746 } catch (RemoteException e) {
747 // Ignore
748 } finally {
749 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700750 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700751 }
752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700754 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700755 if (wl.monitorType >= 0) {
756 long origId = Binder.clearCallingIdentity();
757 try {
758 if (ws != null) {
759 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
760 wl.monitorType);
761 } else {
762 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
763 }
764 } catch (RemoteException e) {
765 // Ignore
766 } finally {
767 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700768 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700769 }
770 }
771
772 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
773 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800775 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700778 if (ws != null && ws.size() == 0) {
779 ws = null;
780 }
781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 int index = mLocks.getIndex(lock);
783 WakeLock wl;
784 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700785 boolean diffsource;
786 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700788 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 switch (wl.flags & LOCK_MASK)
790 {
791 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500792 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400793 wl.minState = SCREEN_BRIGHT;
794 } else {
795 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 break;
798 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
799 wl.minState = SCREEN_BRIGHT;
800 break;
801 case PowerManager.SCREEN_DIM_WAKE_LOCK:
802 wl.minState = SCREEN_DIM;
803 break;
804 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700805 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 break;
807 default:
808 // just log and bail. we're in the server, so don't
809 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800810 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 + " flags=" + flags);
812 return;
813 }
814 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700815 if (ws != null) {
816 wl.ws = new WorkSource(ws);
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700819 diffsource = false;
820 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 } else {
822 wl = mLocks.get(index);
823 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700824 oldsource = wl.ws;
825 if (oldsource != null) {
826 if (ws == null) {
827 wl.ws = null;
828 diffsource = true;
829 } else {
830 diffsource = oldsource.diff(ws);
831 }
832 } else if (ws != null) {
833 diffsource = true;
834 } else {
835 diffsource = false;
836 }
837 if (diffsource) {
838 wl.ws = new WorkSource(ws);
839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841 if (isScreenLock(flags)) {
842 // if this causes a wakeup, we reactivate all of the locks and
843 // set it to whatever they want. otherwise, we modulate that
844 // by the current state so we never turn it more on than
845 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400846 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
847 mProximityWakeLockCount++;
848 if (mProximityWakeLockCount == 1) {
849 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400852 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
853 int oldWakeLockState = mWakeLockState;
854 mWakeLockState = mLocks.reactivateScreenLocksLocked();
855 if (mSpew) {
856 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
857 + " mWakeLockState=0x"
858 + Integer.toHexString(mWakeLockState)
859 + " previous wakeLockState=0x"
860 + Integer.toHexString(oldWakeLockState));
861 }
862 } else {
863 if (mSpew) {
864 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
865 + " mLocks.gatherState()=0x"
866 + Integer.toHexString(mLocks.gatherState())
867 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
868 }
869 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400871 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
875 if (newlock) {
876 mPartialCount++;
877 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800878 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880 }
881 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700884 if (diffsource) {
885 // If the lock sources have changed, need to first release the
886 // old ones.
887 noteStopWakeLocked(wl, oldsource);
888 }
889 if (newlock || diffsource) {
890 noteStartWakeLocked(wl, ws);
891 }
892 }
893
894 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
895 int uid = Binder.getCallingUid();
896 int pid = Binder.getCallingPid();
897 if (ws != null && ws.size() == 0) {
898 ws = null;
899 }
900 if (ws != null) {
901 enforceWakeSourcePermission(uid, pid);
902 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700903 synchronized (mLocks) {
904 int index = mLocks.getIndex(lock);
905 if (index < 0) {
906 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700908 WakeLock wl = mLocks.get(index);
909 WorkSource oldsource = wl.ws;
910 wl.ws = ws != null ? new WorkSource(ws) : null;
911 noteStopWakeLocked(wl, oldsource);
912 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
914 }
915
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500916 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700917 int uid = Binder.getCallingUid();
918 if (uid != Process.myUid()) {
919 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921
922 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500923 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
925 }
926
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500927 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 WakeLock wl = mLocks.removeLock(lock);
929 if (wl == null) {
930 return;
931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800934 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
936 }
937
938 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400939 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
940 mProximityWakeLockCount--;
941 if (mProximityWakeLockCount == 0) {
942 if (mProximitySensorActive &&
943 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
944 // wait for proximity sensor to go negative before disabling sensor
945 if (mDebugProximitySensor) {
946 Slog.d(TAG, "waiting for proximity sensor to go negative");
947 }
948 } else {
949 disableProximityLockLocked();
950 }
951 }
952 } else {
953 mWakeLockState = mLocks.gatherState();
954 // goes in the middle to reduce flicker
955 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
956 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
957 }
958 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
962 mPartialCount--;
963 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800964 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 Power.releaseWakeLock(PARTIAL_NAME);
966 }
967 }
968 // Unlink the lock from the binder.
969 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970
Dianne Hackborn70be1672010-09-14 11:13:03 -0700971 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 private class PokeLock implements IBinder.DeathRecipient
975 {
976 PokeLock(int p, IBinder b, String t) {
977 super();
978 this.pokey = p;
979 this.binder = b;
980 this.tag = t;
981 try {
982 b.linkToDeath(this, 0);
983 } catch (RemoteException e) {
984 binderDied();
985 }
986 }
987 public void binderDied() {
988 setPokeLock(0, this.binder, this.tag);
989 }
990 int pokey;
991 IBinder binder;
992 String tag;
993 boolean awakeOnSet;
994 }
995
996 public void setPokeLock(int pokey, IBinder token, String tag) {
997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
998 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800999 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 return;
1001 }
1002
1003 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1004 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1005 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1006 }
1007
1008 synchronized (mLocks) {
1009 if (pokey != 0) {
1010 PokeLock p = mPokeLocks.get(token);
1011 int oldPokey = 0;
1012 if (p != null) {
1013 oldPokey = p.pokey;
1014 p.pokey = pokey;
1015 } else {
1016 p = new PokeLock(pokey, token, tag);
1017 mPokeLocks.put(token, p);
1018 }
1019 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1020 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1021 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1022 p.awakeOnSet = true;
1023 }
1024 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001025 PokeLock rLock = mPokeLocks.remove(token);
1026 if (rLock != null) {
1027 token.unlinkToDeath(rLock, 0);
1028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
1030
1031 int oldPokey = mPokey;
1032 int cumulative = 0;
1033 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1034 boolean awakeOnSet = false;
1035 for (PokeLock p: mPokeLocks.values()) {
1036 cumulative |= p.pokey;
1037 if (p.awakeOnSet) {
1038 awakeOnSet = true;
1039 }
1040 }
1041 mPokey = cumulative;
1042 mPokeAwakeOnSet = awakeOnSet;
1043
1044 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1045 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (oldCumulativeTimeout != newCumulativeTimeout) {
1048 setScreenOffTimeoutsLocked();
1049 // reset the countdown timer, but use the existing nextState so it doesn't
1050 // change anything
1051 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1052 }
1053 }
1054 }
1055
1056 private static String lockType(int type)
1057 {
1058 switch (type)
1059 {
1060 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001061 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001063 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001065 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001067 return "PARTIAL_WAKE_LOCK ";
1068 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1069 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 default:
David Brown251faa62009-08-02 22:04:36 -07001071 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073 }
1074
1075 private static String dumpPowerState(int state) {
1076 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1077 ? "KEYBOARD_BRIGHT_BIT " : "")
1078 + (((state & SCREEN_BRIGHT_BIT) != 0)
1079 ? "SCREEN_BRIGHT_BIT " : "")
1080 + (((state & SCREEN_ON_BIT) != 0)
1081 ? "SCREEN_ON_BIT " : "")
1082 + (((state & BATTERY_LOW_BIT) != 0)
1083 ? "BATTERY_LOW_BIT " : "");
1084 }
1085
1086 @Override
1087 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1088 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1089 != PackageManager.PERMISSION_GRANTED) {
1090 pw.println("Permission Denial: can't dump PowerManager from from pid="
1091 + Binder.getCallingPid()
1092 + ", uid=" + Binder.getCallingUid());
1093 return;
1094 }
1095
1096 long now = SystemClock.uptimeMillis();
1097
Mike Lockwoodca44df82010-02-25 13:48:49 -05001098 synchronized (mLocks) {
1099 pw.println("Power Manager State:");
1100 pw.println(" mIsPowered=" + mIsPowered
1101 + " mPowerState=" + mPowerState
1102 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1103 + " ms");
1104 pw.println(" mPartialCount=" + mPartialCount);
1105 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1106 pw.println(" mUserState=" + dumpPowerState(mUserState));
1107 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1108 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1109 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1110 + " " + ((mNextTimeout-now)/1000) + "s from now");
1111 pw.println(" mDimScreen=" + mDimScreen
1112 + " mStayOnConditions=" + mStayOnConditions);
1113 pw.println(" mScreenOffReason=" + mScreenOffReason
1114 + " mUserState=" + mUserState);
1115 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1116 + ',' + mBroadcastQueue[2] + "}");
1117 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1118 + ',' + mBroadcastWhy[2] + "}");
1119 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1120 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1121 + " mUserActivityAllowed=" + mUserActivityAllowed);
1122 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1123 + " mScreenOffDelay=" + mScreenOffDelay);
1124 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1125 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1126 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1127 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1128 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1129 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1130 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1131 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1132 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1133 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1134 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1135 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1136 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1137 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1138 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1139 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1140 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1141 pw.println(" mLightSensorValue=" + mLightSensorValue
1142 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001143 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1144 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001145 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1146 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1147 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1148 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1149 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1150 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001151
Mike Lockwoodca44df82010-02-25 13:48:49 -05001152 int N = mLocks.size();
1153 pw.println();
1154 pw.println("mLocks.size=" + N + ":");
1155 for (int i=0; i<N; i++) {
1156 WakeLock wl = mLocks.get(i);
1157 String type = lockType(wl.flags & LOCK_MASK);
1158 String acquireCausesWakeup = "";
1159 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1160 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1161 }
1162 String activated = "";
1163 if (wl.activated) {
1164 activated = " activated";
1165 }
1166 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001167 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1168 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001170
1171 pw.println();
1172 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1173 for (PokeLock p: mPokeLocks.values()) {
1174 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001175 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1176 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001177 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1178 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1179 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1180 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001182
Mike Lockwoodca44df82010-02-25 13:48:49 -05001183 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186
Joe Onorato7999bff2010-07-24 11:50:05 -04001187 private void setTimeoutLocked(long now, int nextState) {
1188 setTimeoutLocked(now, -1, nextState);
1189 }
1190
1191 // If they gave a timeoutOverride it is the number of seconds
1192 // to screen-off. Figure out where in the countdown cycle we
1193 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001194 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1195 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001196 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001197 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001198 long when = 0;
1199 if (timeoutOverride <= 0) {
1200 switch (nextState)
1201 {
1202 case SCREEN_BRIGHT:
1203 when = now + mKeylightDelay;
1204 break;
1205 case SCREEN_DIM:
1206 if (mDimDelay >= 0) {
1207 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001208 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001209 } else {
1210 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1211 }
1212 case SCREEN_OFF:
1213 synchronized (mLocks) {
1214 when = now + mScreenOffDelay;
1215 }
1216 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001217 default:
1218 when = now;
1219 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001221 } else {
1222 override: {
1223 if (timeoutOverride <= mScreenOffDelay) {
1224 when = now + timeoutOverride;
1225 nextState = SCREEN_OFF;
1226 break override;
1227 }
1228 timeoutOverride -= mScreenOffDelay;
1229
1230 if (mDimDelay >= 0) {
1231 if (timeoutOverride <= mDimDelay) {
1232 when = now + timeoutOverride;
1233 nextState = SCREEN_DIM;
1234 break override;
1235 }
1236 timeoutOverride -= mDimDelay;
1237 }
1238
1239 when = now + timeoutOverride;
1240 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001242 }
1243 if (mSpew) {
1244 Slog.d(TAG, "setTimeoutLocked now=" + now
1245 + " timeoutOverride=" + timeoutOverride
1246 + " nextState=" + nextState + " when=" + when);
1247 }
Joe Onorato797e6882010-08-26 14:46:01 -04001248
1249 mHandler.removeCallbacks(mTimeoutTask);
1250 mTimeoutTask.nextState = nextState;
1251 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1252 ? (originalTimeoutOverride - timeoutOverride)
1253 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001254 mHandler.postAtTime(mTimeoutTask, when);
1255 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258 }
1259
1260 private void cancelTimerLocked()
1261 {
1262 mHandler.removeCallbacks(mTimeoutTask);
1263 mTimeoutTask.nextState = -1;
1264 }
1265
1266 private class TimeoutTask implements Runnable
1267 {
1268 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001269 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 public void run()
1271 {
1272 synchronized (mLocks) {
1273 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001274 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
1276
1277 if (nextState == -1) {
1278 return;
1279 }
1280
1281 mUserState = this.nextState;
1282 setPowerState(this.nextState | mWakeLockState);
1283
1284 long now = SystemClock.uptimeMillis();
1285
1286 switch (this.nextState)
1287 {
1288 case SCREEN_BRIGHT:
1289 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001290 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 break;
1292 }
1293 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001294 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 break;
1296 }
1297 }
1298 }
1299 }
1300
1301 private void sendNotificationLocked(boolean on, int why)
1302 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001303 if (!on) {
1304 mStillNeedSleepNotification = false;
1305 }
1306
Joe Onorato128e7292009-03-24 18:41:31 -07001307 // Add to the queue.
1308 int index = 0;
1309 while (mBroadcastQueue[index] != -1) {
1310 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
Joe Onorato128e7292009-03-24 18:41:31 -07001312 mBroadcastQueue[index] = on ? 1 : 0;
1313 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314
Joe Onorato128e7292009-03-24 18:41:31 -07001315 // If we added it position 2, then there is a pair that can be stripped.
1316 // If we added it position 1 and we're turning the screen off, we can strip
1317 // the pair and do nothing, because the screen is already off, and therefore
1318 // keyguard has already been enabled.
1319 // However, if we added it at position 1 and we're turning it on, then position
1320 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1321 // on, so have to run the queue then.
1322 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001323 // While we're collapsing them, if it's going off, and the new reason
1324 // is more significant than the first, then use the new one.
1325 if (!on && mBroadcastWhy[0] > why) {
1326 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001327 }
1328 mBroadcastQueue[0] = on ? 1 : 0;
1329 mBroadcastQueue[1] = -1;
1330 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001331 mBroadcastWakeLock.release();
1332 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001333 index = 0;
1334 }
1335 if (index == 1 && !on) {
1336 mBroadcastQueue[0] = -1;
1337 mBroadcastQueue[1] = -1;
1338 index = -1;
1339 // The wake lock was being held, but we're not actually going to do any
1340 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001341 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001343 }
1344
1345 // Now send the message.
1346 if (index >= 0) {
1347 // Acquire the broadcast wake lock before changing the power
1348 // state. It will be release after the broadcast is sent.
1349 // We always increment the ref count for each notification in the queue
1350 // and always decrement when that notification is handled.
1351 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001352 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001353 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355 }
1356
1357 private Runnable mNotificationTask = new Runnable()
1358 {
1359 public void run()
1360 {
Joe Onorato128e7292009-03-24 18:41:31 -07001361 while (true) {
1362 int value;
1363 int why;
1364 WindowManagerPolicy policy;
1365 synchronized (mLocks) {
1366 value = mBroadcastQueue[0];
1367 why = mBroadcastWhy[0];
1368 for (int i=0; i<2; i++) {
1369 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1370 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1371 }
1372 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
Joe Onorato128e7292009-03-24 18:41:31 -07001374 if (value == 1) {
1375 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001376
Joe Onorato128e7292009-03-24 18:41:31 -07001377 policy.screenTurnedOn();
1378 try {
1379 ActivityManagerNative.getDefault().wakingUp();
1380 } catch (RemoteException e) {
1381 // ignore it
1382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383
Joe Onorato128e7292009-03-24 18:41:31 -07001384 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001385 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001386 }
1387 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1388 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1389 mScreenOnBroadcastDone, mHandler, 0, null, null);
1390 } else {
1391 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001392 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001393 mBroadcastWakeLock.mCount);
1394 mBroadcastWakeLock.release();
1395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 }
Joe Onorato128e7292009-03-24 18:41:31 -07001398 else if (value == 0) {
1399 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400
Joe Onorato128e7292009-03-24 18:41:31 -07001401 policy.screenTurnedOff(why);
1402 try {
1403 ActivityManagerNative.getDefault().goingToSleep();
1404 } catch (RemoteException e) {
1405 // ignore it.
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407
Joe Onorato128e7292009-03-24 18:41:31 -07001408 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1409 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1410 mScreenOffBroadcastDone, mHandler, 0, null, null);
1411 } else {
1412 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001413 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001414 mBroadcastWakeLock.mCount);
1415 mBroadcastWakeLock.release();
1416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
Joe Onorato128e7292009-03-24 18:41:31 -07001419 else {
1420 // If we're in this case, then this handler is running for a previous
1421 // paired transaction. mBroadcastWakeLock will already have been released.
1422 break;
1423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426 };
1427
1428 long mScreenOnStart;
1429 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1430 public void onReceive(Context context, Intent intent) {
1431 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001432 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1434 mBroadcastWakeLock.release();
1435 }
1436 }
1437 };
1438
1439 long mScreenOffStart;
1440 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1441 public void onReceive(Context context, Intent intent) {
1442 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1445 mBroadcastWakeLock.release();
1446 }
1447 }
1448 };
1449
1450 void logPointerUpEvent() {
1451 if (LOG_TOUCH_DOWNS) {
1452 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1453 mLastTouchDown = 0;
1454 }
1455 }
1456
1457 void logPointerDownEvent() {
1458 if (LOG_TOUCH_DOWNS) {
1459 // If we are not already timing a down/up sequence
1460 if (mLastTouchDown == 0) {
1461 mLastTouchDown = SystemClock.elapsedRealtime();
1462 mTouchCycles++;
1463 }
1464 }
1465 }
1466
1467 /**
1468 * Prevents the screen from turning on even if it *should* turn on due
1469 * to a subsequent full wake lock being acquired.
1470 * <p>
1471 * This is a temporary hack that allows an activity to "cover up" any
1472 * display glitches that happen during the activity's startup
1473 * sequence. (Specifically, this API was added to work around a
1474 * cosmetic bug in the "incoming call" sequence, where the lock screen
1475 * would flicker briefly before the incoming call UI became visible.)
1476 * TODO: There ought to be a more elegant way of doing this,
1477 * probably by having the PowerManager and ActivityManager
1478 * work together to let apps specify that the screen on/off
1479 * state should be synchronized with the Activity lifecycle.
1480 * <p>
1481 * Note that calling preventScreenOn(true) will NOT turn the screen
1482 * off if it's currently on. (This API only affects *future*
1483 * acquisitions of full wake locks.)
1484 * But calling preventScreenOn(false) WILL turn the screen on if
1485 * it's currently off because of a prior preventScreenOn(true) call.
1486 * <p>
1487 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1488 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1489 * call doesn't occur within 5 seconds, we'll turn the screen back on
1490 * ourselves (and log a warning about it); this prevents a buggy app
1491 * from disabling the screen forever.)
1492 * <p>
1493 * TODO: this feature should really be controlled by a new type of poke
1494 * lock (rather than an IPowerManager call).
1495 */
1496 public void preventScreenOn(boolean prevent) {
1497 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1498
1499 synchronized (mLocks) {
1500 if (prevent) {
1501 // First of all, grab a partial wake lock to
1502 // make sure the CPU stays on during the entire
1503 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1504 mPreventScreenOnPartialLock.acquire();
1505
1506 // Post a forceReenableScreen() call (for 5 seconds in the
1507 // future) to make sure the matching preventScreenOn(false) call
1508 // has happened by then.
1509 mHandler.removeCallbacks(mForceReenableScreenTask);
1510 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1511
1512 // Finally, set the flag that prevents the screen from turning on.
1513 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001514 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 mPreventScreenOn = true;
1516 } else {
1517 // (Re)enable the screen.
1518 mPreventScreenOn = false;
1519
1520 // We're "undoing" a the prior preventScreenOn(true) call, so we
1521 // no longer need the 5-second safeguard.
1522 mHandler.removeCallbacks(mForceReenableScreenTask);
1523
1524 // Forcibly turn on the screen if it's supposed to be on. (This
1525 // handles the case where the screen is currently off because of
1526 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001527 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001529 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1531 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001532 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001534 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536 }
1537
1538 // Release the partial wake lock that we held during the
1539 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1540 mPreventScreenOnPartialLock.release();
1541 }
1542 }
1543 }
1544
1545 public void setScreenBrightnessOverride(int brightness) {
1546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1547
Mike Lockwoodf527c712010-06-10 14:12:33 -04001548 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 synchronized (mLocks) {
1550 if (mScreenBrightnessOverride != brightness) {
1551 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001552 if (isScreenOn()) {
1553 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556 }
1557 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001558
1559 public void setButtonBrightnessOverride(int brightness) {
1560 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1561
Mike Lockwoodf527c712010-06-10 14:12:33 -04001562 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001563 synchronized (mLocks) {
1564 if (mButtonBrightnessOverride != brightness) {
1565 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001566 if (isScreenOn()) {
1567 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1568 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001569 }
1570 }
1571 }
1572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 /**
1574 * Sanity-check that gets called 5 seconds after any call to
1575 * preventScreenOn(true). This ensures that the original call
1576 * is followed promptly by a call to preventScreenOn(false).
1577 */
1578 private void forceReenableScreen() {
1579 // We shouldn't get here at all if mPreventScreenOn is false, since
1580 // we should have already removed any existing
1581 // mForceReenableScreenTask messages...
1582 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001583 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 return;
1585 }
1586
1587 // Uh oh. It's been 5 seconds since a call to
1588 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1589 // This means the app that called preventScreenOn(true) is either
1590 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1591 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1592 // crashed before doing so.)
1593
1594 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 + "Forcing the screen back on...");
1597 preventScreenOn(false);
1598 }
1599
1600 private Runnable mForceReenableScreenTask = new Runnable() {
1601 public void run() {
1602 forceReenableScreen();
1603 }
1604 };
1605
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001606 private int setScreenStateLocked(boolean on) {
1607 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001608 if (err == 0) {
1609 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1610 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001611 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001612 if (!on) {
1613 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001614 mButtonLight.turnOff();
1615 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001616 // clear current value so we will update based on the new conditions
1617 // when the sensor is reenabled.
1618 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001619 // reset our highest light sensor value when the screen turns off
1620 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001621 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001622 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001623 }
1624 return err;
1625 }
1626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 private void setPowerState(int state)
1628 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001629 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631
Mike Lockwood435eb642009-12-03 08:40:18 -05001632 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 {
1634 synchronized (mLocks) {
1635 int err;
1636
1637 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001640 + " noChangeLights=" + noChangeLights
1641 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
1643
1644 if (noChangeLights) {
1645 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1646 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001647 if (mProximitySensorActive) {
1648 // don't turn on the screen when the proximity sensor lock is held
1649 newState = (newState & ~SCREEN_BRIGHT);
1650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651
1652 if (batteryIsLow()) {
1653 newState |= BATTERY_LOW_BIT;
1654 } else {
1655 newState &= ~BATTERY_LOW_BIT;
1656 }
1657 if (newState == mPowerState) {
1658 return;
1659 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001660
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001661 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 newState |= ALL_BRIGHT;
1663 }
1664
1665 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1666 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1667
Mike Lockwood51b84492009-11-16 21:51:18 -05001668 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001669 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001671 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001673 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001677 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001679 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1681 }
1682
1683 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001684 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1686 }
1687
1688 if (oldScreenOn != newScreenOn) {
1689 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001690 // When the user presses the power button, we need to always send out the
1691 // notification that it's going to sleep so the keyguard goes on. But
1692 // we can't do that until the screen fades out, so we don't show the keyguard
1693 // too early.
1694 if (mStillNeedSleepNotification) {
1695 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 // Turn on the screen UNLESS there was a prior
1699 // preventScreenOn(true) request. (Note that the lifetime
1700 // of a single preventScreenOn() request is limited to 5
1701 // seconds to prevent a buggy app from disabling the
1702 // screen forever; see forceReenableScreen().)
1703 boolean reallyTurnScreenOn = true;
1704 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 + mPreventScreenOn);
1707 }
1708
1709 if (mPreventScreenOn) {
1710 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001711 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 reallyTurnScreenOn = false;
1714 }
1715 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001716 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 long identity = Binder.clearCallingIdentity();
1718 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001719 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 mBatteryStats.noteScreenOn();
1721 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001722 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 } finally {
1724 Binder.restoreCallingIdentity(identity);
1725 }
1726 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001727 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 // But continue as if we really did turn the screen on...
1729 err = 0;
1730 }
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 mLastTouchDown = 0;
1733 mTotalTouchDownTime = 0;
1734 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001735 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 mTotalTouchDownTime, mTouchCycles);
1737 if (err == 0) {
1738 mPowerState |= SCREEN_ON_BIT;
1739 sendNotificationLocked(true, -1);
1740 }
1741 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001742 // cancel light sensor task
1743 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001744 mLightSensorPendingDecrease = false;
1745 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 mScreenOffTime = SystemClock.elapsedRealtime();
1747 long identity = Binder.clearCallingIdentity();
1748 try {
1749 mBatteryStats.noteScreenOff();
1750 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001751 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 } finally {
1753 Binder.restoreCallingIdentity(identity);
1754 }
1755 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001756 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001758 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 err = 0;
1761 mLastTouchDown = 0;
1762 }
1763 }
1764 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001765
1766 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001769
1770 private void updateNativePowerStateLocked() {
1771 nativeSetPowerState(
1772 (mPowerState & SCREEN_ON_BIT) != 0,
1773 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001775
Mike Lockwood435eb642009-12-03 08:40:18 -05001776 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001780 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1781 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001783 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001785 mScreenOffReason = reason;
1786 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788 return err;
1789 }
1790
1791 private boolean batteryIsLow() {
1792 return (!mIsPowered &&
1793 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1794 }
1795
The Android Open Source Project10592532009-03-18 17:39:46 -07001796 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001797 final int oldState = mPowerState;
Joe Onorato60607a92010-10-23 14:49:30 -07001798 if ((newState & SCREEN_ON_BIT) != 0) {
1799 // Only turn on the buttons or keyboard if the screen is also on.
1800 // We should never see the buttons on but not the screen.
1801 newState = applyButtonState(newState);
1802 newState = applyKeyboardState(newState);
1803 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001804 final int realDifference = (newState ^ oldState);
1805 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001807 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 int offMask = 0;
1811 int dimMask = 0;
1812 int onMask = 0;
1813
1814 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001817 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1818 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001820 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822 }
1823
1824 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001825 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1826 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001828 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831
1832 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001833 int nominalCurrentValue = -1;
1834 // If there was an actual difference in the light state, then
1835 // figure out the "ideal" current value based on the previous
1836 // state. Otherwise, this is a change due to the brightness
1837 // override, so we want to animate from whatever the current
1838 // value is.
1839 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1840 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1841 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1842 nominalCurrentValue = preferredBrightness;
1843 break;
1844 case SCREEN_ON_BIT:
1845 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1846 break;
1847 case 0:
1848 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1849 break;
1850 case SCREEN_BRIGHT_BIT:
1851 default:
1852 // not possible
1853 nominalCurrentValue = (int)mScreenBrightness.curValue;
1854 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001855 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001856 }
1857 int brightness = preferredBrightness;
1858 int steps = ANIM_STEPS;
1859 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1860 // dim or turn off backlight, depending on if the screen is on
1861 // the scale is because the brightness ramp isn't linear and this biases
1862 // it so the later parts take longer.
1863 final float scale = 1.5f;
1864 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1865 if (ratio > 1.0f) ratio = 1.0f;
1866 if ((newState & SCREEN_ON_BIT) == 0) {
1867 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1868 // was bright
1869 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001871 // was dim
1872 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001874 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001876 if ((oldState & SCREEN_ON_BIT) != 0) {
1877 // was bright
1878 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1879 } else {
1880 // was dim
1881 steps = (int)(ANIM_STEPS*ratio);
1882 }
1883 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1884 // If the "stay on while plugged in" option is
1885 // turned on, then the screen will often not
1886 // automatically turn off while plugged in. To
1887 // still have a sense of when it is inactive, we
1888 // will then count going dim as turning off.
1889 mScreenOffTime = SystemClock.elapsedRealtime();
1890 }
1891 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001894 long identity = Binder.clearCallingIdentity();
1895 try {
1896 mBatteryStats.noteScreenBrightness(brightness);
1897 } catch (RemoteException e) {
1898 // Nothing interesting to do.
1899 } finally {
1900 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001902 mScreenBrightness.setTargetLocked(brightness, steps,
1903 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001905
Joe Onorato60607a92010-10-23 14:49:30 -07001906 if (mSpew) {
1907 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1908 + " dimMask=0x" + Integer.toHexString(dimMask)
1909 + " onMask=0x" + Integer.toHexString(onMask)
1910 + " difference=0x" + Integer.toHexString(difference)
1911 + " realDifference=0x" + Integer.toHexString(realDifference)
1912 + " forceState=0x" + Integer.toHexString(forceState)
1913 );
1914 }
1915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001917 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001918 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920 if (dimMask != 0) {
1921 int brightness = Power.BRIGHTNESS_DIM;
1922 if ((newState & BATTERY_LOW_BIT) != 0 &&
1923 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1924 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1925 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001926 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001927 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929 if (onMask != 0) {
1930 int brightness = getPreferredBrightness();
1931 if ((newState & BATTERY_LOW_BIT) != 0 &&
1932 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1933 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1934 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001935 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001936 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939
The Android Open Source Project10592532009-03-18 17:39:46 -07001940 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001941 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001942 ? LightsService.BRIGHTNESS_MODE_SENSOR
1943 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001944 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001945 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001946 }
1947 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001948 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001949 }
1950 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001951 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
1954
Joe Onoratob08a1af2010-10-11 19:28:58 -07001955 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 boolean initialized;
1959 int targetValue;
1960 float curValue;
1961 float delta;
1962 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 BrightnessState(int m) {
1965 mask = m;
1966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 public void dump(PrintWriter pw, String prefix) {
1969 pw.println(prefix + "animating=" + animating
1970 + " targetValue=" + targetValue
1971 + " curValue=" + curValue
1972 + " delta=" + delta);
1973 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001974
Joe Onoratob08a1af2010-10-11 19:28:58 -07001975 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001976 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 if (!initialized) {
1978 initialized = true;
1979 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001980 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001981 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001984 delta = (targetValue -
1985 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1986 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001988 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04001989 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
1990 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07001991 + " nominalCurrentValue=" + nominalCurrentValue
1992 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001995
1996 if (mSpew) {
1997 Slog.i(TAG, "scheduling light animator");
1998 }
1999 mScreenOffHandler.removeCallbacks(this);
2000 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 boolean stepLocked() {
2004 if (!animating) return false;
2005 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002006 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 + " target=" + targetValue + " delta=" + delta);
2008 }
2009 curValue += delta;
2010 int curIntValue = (int)curValue;
2011 boolean more = true;
2012 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002013 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 more = false;
2015 } else if (delta > 0) {
2016 if (curIntValue >= targetValue) {
2017 curValue = curIntValue = targetValue;
2018 more = false;
2019 }
2020 } else {
2021 if (curIntValue <= targetValue) {
2022 curValue = curIntValue = targetValue;
2023 more = false;
2024 }
2025 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002026 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002027 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002028 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002029 return more;
2030 }
2031
Joe Onorato3d3db602010-10-18 16:08:16 -04002032 void jumpToTargetLocked() {
2033 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 setLightBrightness(mask, targetValue);
2035 final int tv = targetValue;
2036 curValue = tv;
2037 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002038 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002039 }
2040
Joe Onorato3d3db602010-10-18 16:08:16 -04002041 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 animating = more;
2043 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002044 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002045 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 }
2047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002051 if (mAnimateScreenLights) {
2052 synchronized (mLocks) {
2053 long now = SystemClock.uptimeMillis();
2054 boolean more = mScreenBrightness.stepLocked();
2055 if (more) {
2056 mScreenOffHandler.postAtTime(this, now+(1000/60));
2057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002059 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002060 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002061 // we're turning off
2062 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2063 if (animate) {
2064 // It's pretty scary to hold mLocks for this long, and we should
2065 // redesign this, but it works for now.
2066 nativeStartSurfaceFlingerAnimation(
2067 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2068 ? 0 : mAnimationSetting);
2069 }
2070 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 private int getPreferredBrightness() {
2077 try {
2078 if (mScreenBrightnessOverride >= 0) {
2079 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002080 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002081 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002082 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2085 SCREEN_BRIGHTNESS);
2086 // Don't let applications turn the screen all the way off
2087 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2088 } catch (SettingNotFoundException snfe) {
2089 return Power.BRIGHTNESS_ON;
2090 }
2091 }
2092
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002093 private int applyButtonState(int state) {
2094 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002095 if ((state & BATTERY_LOW_BIT) != 0) {
2096 // do not override brightness if the battery is low
2097 return state;
2098 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002099 if (mButtonBrightnessOverride >= 0) {
2100 brightness = mButtonBrightnessOverride;
2101 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2102 brightness = mLightSensorButtonBrightness;
2103 }
2104 if (brightness > 0) {
2105 return state | BUTTON_BRIGHT_BIT;
2106 } else if (brightness == 0) {
2107 return state & ~BUTTON_BRIGHT_BIT;
2108 } else {
2109 return state;
2110 }
2111 }
2112
2113 private int applyKeyboardState(int state) {
2114 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002115 if ((state & BATTERY_LOW_BIT) != 0) {
2116 // do not override brightness if the battery is low
2117 return state;
2118 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002119 if (!mKeyboardVisible) {
2120 brightness = 0;
2121 } else if (mButtonBrightnessOverride >= 0) {
2122 brightness = mButtonBrightnessOverride;
2123 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2124 brightness = mLightSensorKeyboardBrightness;
2125 }
2126 if (brightness > 0) {
2127 return state | KEYBOARD_BRIGHT_BIT;
2128 } else if (brightness == 0) {
2129 return state & ~KEYBOARD_BRIGHT_BIT;
2130 } else {
2131 return state;
2132 }
2133 }
2134
Charles Mendis322591c2009-10-29 11:06:59 -07002135 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 synchronized (mLocks) {
2137 return (mPowerState & SCREEN_ON_BIT) != 0;
2138 }
2139 }
2140
Charles Mendis322591c2009-10-29 11:06:59 -07002141 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 synchronized (mLocks) {
2143 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2144 }
2145 }
2146
Mike Lockwood497087e32009-11-08 18:33:03 -05002147 private boolean isScreenTurningOffLocked() {
2148 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2149 }
2150
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002151 private boolean shouldLog(long time) {
2152 synchronized (mLocks) {
2153 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2154 mWarningSpewThrottleTime = time;
2155 mWarningSpewThrottleCount = 0;
2156 return true;
2157 } else if (mWarningSpewThrottleCount < 30) {
2158 mWarningSpewThrottleCount++;
2159 return true;
2160 } else {
2161 return false;
2162 }
2163 }
2164 }
2165
Mike Lockwood200b30b2009-09-20 00:23:59 -04002166 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002167 if (isScreenTurningOffLocked()) {
2168 // cancel animation so userActivity will succeed
2169 mScreenBrightness.animating = false;
2170 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002171 boolean savedActivityAllowed = mUserActivityAllowed;
2172 mUserActivityAllowed = true;
2173 userActivity(SystemClock.uptimeMillis(), false);
2174 mUserActivityAllowed = savedActivityAllowed;
2175 }
2176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002179 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 }
2181
2182 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002183 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2184 != PackageManager.PERMISSION_GRANTED) {
2185 if (shouldLog(time)) {
2186 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2187 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2188 }
2189 return;
2190 }
2191
Joe Onorato7999bff2010-07-24 11:50:05 -04002192 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 }
2194
2195 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002196 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
2198
2199 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002200 userActivity(time, -1, noChangeLights, eventType, force);
2201 }
2202
2203 /*
2204 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2205 * on with user activity. Don't use this function.
2206 */
2207 public void clearUserActivityTimeout(long now, long timeout) {
2208 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2209 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2210 userActivity(now, timeout, false, OTHER_EVENT, false);
2211 }
2212
2213 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2214 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215
Joe Onorato1a542c72010-11-08 09:48:20 -08002216 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002217 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002218 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002219 }
2220 return;
2221 }
2222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 synchronized (mLocks) {
2224 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002225 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 + " mUserActivityAllowed=" + mUserActivityAllowed
2227 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002228 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2229 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002230 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002231 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 }
Mike Lockwood05067122009-10-27 23:07:25 -04002233 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002234 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002235 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002236 return;
2237 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002238 // Disable proximity sensor if if user presses power key while we are in the
2239 // "waiting for proximity sensor to go negative" state.
2240 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2241 mProximitySensorActive = false;
2242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 if (mLastEventTime <= time || force) {
2244 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002245 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002246 // Only turn on button backlights if a button was pressed
2247 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002248 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2250 } else {
2251 // don't clear button/keyboard backlights when the screen is touched.
2252 mUserState |= SCREEN_BRIGHT;
2253 }
2254
Dianne Hackborn617f8772009-03-31 15:04:46 -07002255 int uid = Binder.getCallingUid();
2256 long ident = Binder.clearCallingIdentity();
2257 try {
2258 mBatteryStats.noteUserActivity(uid, eventType);
2259 } catch (RemoteException e) {
2260 // Ignore
2261 } finally {
2262 Binder.restoreCallingIdentity(ident);
2263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002264
Michael Chane96440f2009-05-06 10:27:36 -07002265 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002266 setPowerState(mUserState | mWakeLockState, noChangeLights,
2267 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002268 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
2271 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002272
2273 if (mPolicy != null) {
2274 mPolicy.userActivity();
2275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 }
2277
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002278 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2279 try {
2280 int i;
2281 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2282 if (sensorValue < mAutoBrightnessLevels[i]) {
2283 break;
2284 }
2285 }
2286 return values[i];
2287 } catch (Exception e) {
2288 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002289 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002290 return 255;
2291 }
2292 }
2293
Mike Lockwood20f87d72009-11-05 16:08:51 -05002294 private Runnable mProximityTask = new Runnable() {
2295 public void run() {
2296 synchronized (mLocks) {
2297 if (mProximityPendingValue != -1) {
2298 proximityChangedLocked(mProximityPendingValue == 1);
2299 mProximityPendingValue = -1;
2300 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002301 if (mProximityPartialLock.isHeld()) {
2302 mProximityPartialLock.release();
2303 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002304 }
2305 }
2306 };
2307
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002308 private Runnable mAutoBrightnessTask = new Runnable() {
2309 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002310 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002311 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2312 int value = (int)mLightSensorPendingValue;
2313 mLightSensorPendingDecrease = false;
2314 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002315 lightSensorChangedLocked(value);
2316 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002317 }
2318 }
2319 };
2320
Mike Lockwoodb2865412010-02-02 22:40:33 -05002321 private void dockStateChanged(int state) {
2322 synchronized (mLocks) {
2323 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2324 if (mIsDocked) {
2325 mHighestLightSensorValue = -1;
2326 }
2327 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2328 // force lights recalculation
2329 int value = (int)mLightSensorValue;
2330 mLightSensorValue = -1;
2331 lightSensorChangedLocked(value);
2332 }
2333 }
2334 }
2335
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002336 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002337 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002338 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002339 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002340
Joe Onorato06eb33a2010-10-25 14:09:21 -07002341 // Don't do anything if the screen is off.
2342 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2343 if (mDebugLightSensor) {
2344 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2345 }
2346 return;
2347 }
2348
Mike Lockwoodb2865412010-02-02 22:40:33 -05002349 // do not allow light sensor value to decrease
2350 if (mHighestLightSensorValue < value) {
2351 mHighestLightSensorValue = value;
2352 }
2353
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002354 if (mLightSensorValue != value) {
2355 mLightSensorValue = value;
2356 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002357 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2358 // we only do this if we are undocked, since lighting should be stable when
2359 // stationary in a dock.
2360 int lcdValue = getAutoBrightnessValue(
2361 (mIsDocked ? value : mHighestLightSensorValue),
2362 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002363 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002364 int keyboardValue;
2365 if (mKeyboardVisible) {
2366 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2367 } else {
2368 keyboardValue = 0;
2369 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002370 mLightSensorScreenBrightness = lcdValue;
2371 mLightSensorButtonBrightness = buttonValue;
2372 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002373
2374 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002375 Slog.d(TAG, "lcdValue " + lcdValue);
2376 Slog.d(TAG, "buttonValue " + buttonValue);
2377 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002378 }
2379
Mike Lockwood4984e732009-11-01 08:16:33 -05002380 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002381 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2382 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002383 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002384 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002385 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002386 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002387 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002388 mKeyboardLight.setBrightness(keyboardValue);
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) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002556 synchronized (mLocks) {
2557 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2558 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2559 mAutoBrightessEnabled = enabled;
2560 // This will get us a new value
2561 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002562 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002563 }
2564 }
2565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 /** Sets the screen off timeouts:
2567 * mKeylightDelay
2568 * mDimDelay
2569 * mScreenOffDelay
2570 * */
2571 private void setScreenOffTimeoutsLocked() {
2572 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002573 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 mDimDelay = -1;
2575 mScreenOffDelay = 0;
2576 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2577 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2578 mDimDelay = -1;
2579 mScreenOffDelay = 0;
2580 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002581 int totalDelay = mScreenOffTimeoutSetting;
2582 if (totalDelay > mMaximumScreenOffTimeout) {
2583 totalDelay = mMaximumScreenOffTimeout;
2584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2586 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002587 // negative number means stay on as long as possible.
2588 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 } else if (mKeylightDelay < totalDelay) {
2590 // subtract the time that the keylight delay. This will give us the
2591 // remainder of the time that we need to sleep to get the accurate
2592 // screen off timeout.
2593 mScreenOffDelay = totalDelay - mKeylightDelay;
2594 } else {
2595 mScreenOffDelay = 0;
2596 }
2597 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2598 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2599 mScreenOffDelay = LONG_DIM_TIME;
2600 } else {
2601 mDimDelay = -1;
2602 }
2603 }
2604 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002605 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2607 + " mDimScreen=" + mDimScreen);
2608 }
2609 }
2610
2611 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002612 * Refreshes cached secure settings. Called once on startup, and
2613 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 */
Doug Zongker43866e02010-01-07 12:09:54 -08002615 private void updateSettingsValues() {
2616 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002618 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002620 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622
2623 private class LockList extends ArrayList<WakeLock>
2624 {
2625 void addLock(WakeLock wl)
2626 {
2627 int index = getIndex(wl.binder);
2628 if (index < 0) {
2629 this.add(wl);
2630 }
2631 }
2632
2633 WakeLock removeLock(IBinder binder)
2634 {
2635 int index = getIndex(binder);
2636 if (index >= 0) {
2637 return this.remove(index);
2638 } else {
2639 return null;
2640 }
2641 }
2642
2643 int getIndex(IBinder binder)
2644 {
2645 int N = this.size();
2646 for (int i=0; i<N; i++) {
2647 if (this.get(i).binder == binder) {
2648 return i;
2649 }
2650 }
2651 return -1;
2652 }
2653
2654 int gatherState()
2655 {
2656 int result = 0;
2657 int N = this.size();
2658 for (int i=0; i<N; i++) {
2659 WakeLock wl = this.get(i);
2660 if (wl.activated) {
2661 if (isScreenLock(wl.flags)) {
2662 result |= wl.minState;
2663 }
2664 }
2665 }
2666 return result;
2667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002668
Michael Chane96440f2009-05-06 10:27:36 -07002669 int reactivateScreenLocksLocked()
2670 {
2671 int result = 0;
2672 int N = this.size();
2673 for (int i=0; i<N; i++) {
2674 WakeLock wl = this.get(i);
2675 if (isScreenLock(wl.flags)) {
2676 wl.activated = true;
2677 result |= wl.minState;
2678 }
2679 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002680 if (mDebugProximitySensor) {
2681 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2682 + mProxIgnoredBecauseScreenTurnedOff);
2683 }
2684 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002685 return result;
2686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 }
2688
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002689 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 synchronized (mLocks) {
2691 mPolicy = p;
2692 mLocks.notifyAll();
2693 }
2694 }
2695
2696 WindowManagerPolicy getPolicyLocked() {
2697 while (mPolicy == null || !mDoneBooting) {
2698 try {
2699 mLocks.wait();
2700 } catch (InterruptedException e) {
2701 // Ignore
2702 }
2703 }
2704 return mPolicy;
2705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002708 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2709 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2710 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002711 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002712 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002713 }
2714
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002715 // wait until sensors are enabled before turning on screen.
2716 // some devices will not activate the light sensor properly on boot
2717 // unless we do this.
2718 if (mUseSoftwareAutoBrightness) {
2719 // turn the screen on
2720 setPowerState(SCREEN_BRIGHT);
2721 } else {
2722 // turn everything on
2723 setPowerState(ALL_BRIGHT);
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002727 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002729
Joe Onoratod28f7532010-11-06 12:56:53 -07002730 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2731
Dianne Hackborn617f8772009-03-31 15:04:46 -07002732 long identity = Binder.clearCallingIdentity();
2733 try {
2734 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2735 mBatteryStats.noteScreenOn();
2736 } catch (RemoteException e) {
2737 // Nothing interesting to do.
2738 } finally {
2739 Binder.restoreCallingIdentity(identity);
2740 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002741 }
2742 }
2743
2744 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002745 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002746 synchronized (mLocks) {
2747 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2749 updateWakeLockLocked();
2750 mLocks.notifyAll();
2751 }
2752 }
2753
Joe Onoratob08a1af2010-10-11 19:28:58 -07002754 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 public void monitor() {
2756 synchronized (mLocks) { }
2757 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002758
2759 public int getSupportedWakeLockFlags() {
2760 int result = PowerManager.PARTIAL_WAKE_LOCK
2761 | PowerManager.FULL_WAKE_LOCK
2762 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2763
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002764 if (mProximitySensor != null) {
2765 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2766 }
2767
2768 return result;
2769 }
2770
Mike Lockwood237a2992009-09-15 14:42:16 -04002771 public void setBacklightBrightness(int brightness) {
2772 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2773 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002774 synchronized (mLocks) {
2775 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2776 mLcdLight.setBrightness(brightness);
2777 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2778 mButtonLight.setBrightness(brightness);
2779 long identity = Binder.clearCallingIdentity();
2780 try {
2781 mBatteryStats.noteScreenBrightness(brightness);
2782 } catch (RemoteException e) {
2783 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2784 } finally {
2785 Binder.restoreCallingIdentity(identity);
2786 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002787
Joe Onoratob08a1af2010-10-11 19:28:58 -07002788 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002789 synchronized (mLocks) {
2790 mScreenBrightness.targetValue = brightness;
2791 mScreenBrightness.jumpToTargetLocked();
2792 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002793 }
2794 }
2795
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002796 public void setAttentionLight(boolean on, int color) {
2797 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002798 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002799 }
2800
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002801 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002802 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002803 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002804 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002805 if (!mProximitySensorEnabled) {
2806 // clear calling identity so sensor manager battery stats are accurate
2807 long identity = Binder.clearCallingIdentity();
2808 try {
2809 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2810 SensorManager.SENSOR_DELAY_NORMAL);
2811 mProximitySensorEnabled = true;
2812 } finally {
2813 Binder.restoreCallingIdentity(identity);
2814 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002815 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002816 }
2817
2818 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002819 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002820 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002821 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002822 if (mProximitySensorEnabled) {
2823 // clear calling identity so sensor manager battery stats are accurate
2824 long identity = Binder.clearCallingIdentity();
2825 try {
2826 mSensorManager.unregisterListener(mProximityListener);
2827 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002828 if (mProximityPartialLock.isHeld()) {
2829 mProximityPartialLock.release();
2830 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002831 mProximitySensorEnabled = false;
2832 } finally {
2833 Binder.restoreCallingIdentity(identity);
2834 }
2835 if (mProximitySensorActive) {
2836 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002837 if (mDebugProximitySensor) {
2838 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2839 + mProxIgnoredBecauseScreenTurnedOff);
2840 }
2841 if (!mProxIgnoredBecauseScreenTurnedOff) {
2842 forceUserActivityLocked();
2843 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002844 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002845 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002846 }
2847
Mike Lockwood20f87d72009-11-05 16:08:51 -05002848 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002849 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002850 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002851 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002852 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002853 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002854 return;
2855 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002856 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002857 if (mDebugProximitySensor) {
2858 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2859 + mProxIgnoredBecauseScreenTurnedOff);
2860 }
2861 if (!mProxIgnoredBecauseScreenTurnedOff) {
2862 goToSleepLocked(SystemClock.uptimeMillis(),
2863 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2864 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002865 mProximitySensorActive = true;
2866 } else {
2867 // proximity sensor negative events trigger as user activity.
2868 // temporarily set mUserActivityAllowed to true so this will work
2869 // even when the keyguard is on.
2870 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002871 if (mDebugProximitySensor) {
2872 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2873 + mProxIgnoredBecauseScreenTurnedOff);
2874 }
2875 if (!mProxIgnoredBecauseScreenTurnedOff) {
2876 forceUserActivityLocked();
2877 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002878
2879 if (mProximityWakeLockCount == 0) {
2880 // disable sensor if we have no listeners left after proximity negative
2881 disableProximityLockLocked();
2882 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002883 }
2884 }
2885
Joe Onoratod28f7532010-11-06 12:56:53 -07002886 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002887 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002888 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2889 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2890 }
2891 if (!mAutoBrightessEnabled) {
2892 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002893 }
2894 if (mSensorManager != null && mLightSensorEnabled != enable) {
2895 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002896 // clear calling identity so sensor manager battery stats are accurate
2897 long identity = Binder.clearCallingIdentity();
2898 try {
2899 if (enable) {
2900 mSensorManager.registerListener(mLightListener, mLightSensor,
2901 SensorManager.SENSOR_DELAY_NORMAL);
2902 } else {
2903 mSensorManager.unregisterListener(mLightListener);
2904 mHandler.removeCallbacks(mAutoBrightnessTask);
2905 }
2906 } finally {
2907 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002908 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002909 }
2910 }
2911
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002912 SensorEventListener mProximityListener = new SensorEventListener() {
2913 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002914 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002915 synchronized (mLocks) {
2916 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002917 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2918 mLastProximityEventTime = milliseconds;
2919 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002920 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002921
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002922 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002923 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2924 distance < mProximitySensor.getMaximumRange());
2925
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002926 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002927 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002928 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002929 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2930 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2931 mProximityPendingValue = (active ? 1 : 0);
2932 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002933 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002934 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002935 // process the value immediately
2936 mProximityPendingValue = -1;
2937 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002938 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002939
2940 // update mProximityPartialLock state
2941 boolean held = mProximityPartialLock.isHeld();
2942 if (!held && proximityTaskQueued) {
2943 // hold wakelock until mProximityTask runs
2944 mProximityPartialLock.acquire();
2945 } else if (held && !proximityTaskQueued) {
2946 mProximityPartialLock.release();
2947 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002948 }
2949 }
2950
2951 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2952 // ignore
2953 }
2954 };
2955
2956 SensorEventListener mLightListener = new SensorEventListener() {
2957 public void onSensorChanged(SensorEvent event) {
2958 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002959 // ignore light sensor while screen is turning off
2960 if (isScreenTurningOffLocked()) {
2961 return;
2962 }
2963
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002964 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002965 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002966 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002967 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002968 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05002969 if (mLightSensorValue == -1 ||
2970 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2971 // process the value immediately if screen has just turned on
2972 mHandler.removeCallbacks(mAutoBrightnessTask);
2973 mLightSensorPendingDecrease = false;
2974 mLightSensorPendingIncrease = false;
2975 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002976 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002977 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
2978 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
2979 (value == mLightSensorValue) ||
2980 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
2981 // delay processing to debounce the sensor
2982 mHandler.removeCallbacks(mAutoBrightnessTask);
2983 mLightSensorPendingDecrease = (value < mLightSensorValue);
2984 mLightSensorPendingIncrease = (value > mLightSensorValue);
2985 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2986 mLightSensorPendingValue = value;
2987 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2988 }
2989 } else {
2990 mLightSensorPendingValue = value;
2991 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002992 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002993 }
2994 }
2995
2996 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2997 // ignore
2998 }
2999 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000}