blob: 69fa3bff2fc497746c380f25d214b7c083482c4d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070040import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.BatteryStats;
42import android.os.Binder;
Doug Zongker43866e02010-01-07 12:09:54 -080043import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.LocalPowerManager;
49import android.os.Power;
50import android.os.PowerManager;
51import android.os.Process;
52import android.os.RemoteException;
San Mehat14e69af2010-01-06 14:58:18 -080053import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings.SettingNotFoundException;
57import android.provider.Settings;
58import android.util.EventLog;
59import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.WindowManagerPolicy;
62import static android.provider.Settings.System.DIM_SCREEN;
63import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050064import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070065import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
67import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
68
69import java.io.FileDescriptor;
Doug Zongker50a21f42009-11-19 12:49:53 -080070import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.io.PrintWriter;
72import java.util.ArrayList;
73import java.util.HashMap;
74import java.util.Observable;
75import java.util.Observer;
76
Mike Lockwoodbc706a02009-07-27 13:50:57 -070077class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040078 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80 private static final String TAG = "PowerManagerService";
81 static final String PARTIAL_NAME = "PowerManagerService";
82
83 private static final boolean LOG_PARTIAL_WL = false;
84
85 // Indicates whether touch-down cycles should be logged as part of the
86 // LOG_POWER_SCREEN_STATE log events
87 private static final boolean LOG_TOUCH_DOWNS = true;
88
89 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
90 | PowerManager.SCREEN_DIM_WAKE_LOCK
91 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070092 | PowerManager.FULL_WAKE_LOCK
93 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
95 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080096 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
98 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
99 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
100 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
101
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700102 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500103 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700104
Mike Lockwood20f87d72009-11-05 16:08:51 -0500105 // For debouncing the proximity sensor.
106 private static final int PROXIMITY_SENSOR_DELAY = 1000;
107
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400108 // trigger proximity if distance is less than 5 cm
109 private static final float PROXIMITY_THRESHOLD = 5.0f;
110
Doug Zongker43866e02010-01-07 12:09:54 -0800111 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
113
Amith Yamasani8b619832010-09-22 16:11:59 -0700114 // Default timeout for screen off, if not found in settings database = 15 seconds.
115 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 // flags for setPowerState
118 private static final int SCREEN_ON_BIT = 0x00000001;
119 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
120 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
121 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
122 private static final int BATTERY_LOW_BIT = 0x00000010;
123
124 // values for setPowerState
125
126 // SCREEN_OFF == everything off
127 private static final int SCREEN_OFF = 0x00000000;
128
129 // SCREEN_DIM == screen on, screen backlight dim
130 private static final int SCREEN_DIM = SCREEN_ON_BIT;
131
132 // SCREEN_BRIGHT == screen on, screen backlight bright
133 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
134
135 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
136 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
137
138 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
139 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
140
141 // used for noChangeLights in setPowerState()
142 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
143
144 static final boolean ANIMATE_SCREEN_LIGHTS = true;
145 static final boolean ANIMATE_BUTTON_LIGHTS = false;
146 static final boolean ANIMATE_KEYBOARD_LIGHTS = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400149 // Slower animation for autobrightness changes
150 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 // These magic numbers are the initial state of the LEDs at boot. Ideally
153 // we should read them from the driver, but our current hardware returns 0
154 // for the initial value. Oops!
155 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
156 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
157 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700160 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
162 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500163 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500165 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
166 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 private int mPartialCount = 0;
168 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500169 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
170 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
171 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private int mUserState;
173 private boolean mKeyboardVisible = false;
174 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500175 private int mProximityWakeLockCount = 0;
176 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700177 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500178 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
179 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800180 private int mScreenOffTimeoutSetting;
181 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 private int mKeylightDelay;
183 private int mDimDelay;
184 private int mScreenOffDelay;
185 private int mWakeLockState;
186 private long mLastEventTime = 0;
187 private long mScreenOffTime;
188 private volatile WindowManagerPolicy mPolicy;
189 private final LockList mLocks = new LockList();
190 private Intent mScreenOffIntent;
191 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500192 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500194 private LightsService.Light mLcdLight;
195 private LightsService.Light mButtonLight;
196 private LightsService.Light mKeyboardLight;
197 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private UnsynchronizedWakeLock mBroadcastWakeLock;
199 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
200 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
201 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500202 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private HandlerThread mHandlerThread;
204 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500205 private final TimeoutTask mTimeoutTask = new TimeoutTask();
206 private final LightAnimator mLightAnimator = new LightAnimator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700208 = new BrightnessState(SCREEN_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private final BrightnessState mKeyboardBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700210 = new BrightnessState(KEYBOARD_BRIGHT_BIT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private final BrightnessState mButtonBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700212 = new BrightnessState(BUTTON_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700213 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 private boolean mIsPowered = false;
215 private IActivityManager mActivityService;
216 private IBatteryStats mBatteryStats;
217 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700218 private SensorManager mSensorManager;
219 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400220 private Sensor mLightSensor;
221 private boolean mLightSensorEnabled;
222 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400223 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500224 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700225 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500226 private int mLightSensorScreenBrightness = -1;
227 private int mLightSensorButtonBrightness = -1;
228 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500230 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private long mNextTimeout;
232 private volatile int mPokey = 0;
233 private volatile boolean mPokeAwakeOnSet = false;
234 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500235 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500236 // mLastScreenOnTime is the time the screen was last turned on
237 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 private boolean mPreventScreenOn;
239 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500240 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400241 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700242 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700243 private int[] mAutoBrightnessLevels;
244 private int[] mLcdBacklightValues;
245 private int[] mButtonBacklightValues;
246 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500247 private int mLightSensorWarmupTime;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700248 private int mWarningSpewThrottleCount;
249 private long mWarningSpewThrottleTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 // Used when logging number and duration of touch-down cycles
252 private long mTotalTouchDownTime;
253 private long mLastTouchDown;
254 private int mTouchCycles;
255
256 // could be either static or controllable at runtime
257 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400258 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400259 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700260
261 private native void nativeInit();
262 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263
264 /*
265 static PrintStream mLog;
266 static {
267 try {
268 mLog = new PrintStream("/data/power.log");
269 }
270 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800271 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 }
273 }
274 static class Log {
275 static void d(String tag, String s) {
276 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800277 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 }
279 static void i(String tag, String s) {
280 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800281 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283 static void w(String tag, String s) {
284 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287 static void e(String tag, String s) {
288 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800289 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291 }
292 */
293
294 /**
295 * This class works around a deadlock between the lock in PowerManager.WakeLock
296 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
297 * mToken object so it can be accessed from any thread, but it calls into here
298 * with its lock held. This class is essentially a reimplementation of
299 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
300 * only call it with our own locks held.
301 */
302 private class UnsynchronizedWakeLock {
303 int mFlags;
304 String mTag;
305 IBinder mToken;
306 int mCount = 0;
307 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500308 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309
310 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
311 mFlags = flags;
312 mTag = tag;
313 mToken = new Binder();
314 mRefCounted = refCounted;
315 }
316
317 public void acquire() {
318 if (!mRefCounted || mCount++ == 0) {
319 long ident = Binder.clearCallingIdentity();
320 try {
321 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700322 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500323 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 } finally {
325 Binder.restoreCallingIdentity(ident);
326 }
327 }
328 }
329
330 public void release() {
331 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500332 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500333 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 }
335 if (mCount < 0) {
336 throw new RuntimeException("WakeLock under-locked " + mTag);
337 }
338 }
339
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500340 public boolean isHeld()
341 {
342 return mHeld;
343 }
344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 public String toString() {
346 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500347 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
349 }
350
351 private final class BatteryReceiver extends BroadcastReceiver {
352 @Override
353 public void onReceive(Context context, Intent intent) {
354 synchronized (mLocks) {
355 boolean wasPowered = mIsPowered;
356 mIsPowered = mBatteryService.isPowered();
357
358 if (mIsPowered != wasPowered) {
359 // update mStayOnWhilePluggedIn wake lock
360 updateWakeLockLocked();
361
362 // treat plugging and unplugging the devices as a user activity.
363 // users find it disconcerting when they unplug the device
364 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500365 // to avoid turning on the screen when unplugging, we only trigger
366 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 // temporarily set mUserActivityAllowed to true so this will work
368 // even when the keyguard is on.
369 synchronized (mLocks) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500370 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0) {
371 forceUserActivityLocked();
372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 }
374 }
375 }
376 }
377 }
378
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500379 private final class BootCompletedReceiver extends BroadcastReceiver {
380 @Override
381 public void onReceive(Context context, Intent intent) {
382 bootCompleted();
383 }
384 }
385
Mike Lockwoodb2865412010-02-02 22:40:33 -0500386 private final class DockReceiver extends BroadcastReceiver {
387 @Override
388 public void onReceive(Context context, Intent intent) {
389 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
390 Intent.EXTRA_DOCK_STATE_UNDOCKED);
391 dockStateChanged(state);
392 }
393 }
394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 /**
396 * Set the setting that determines whether the device stays on when plugged in.
397 * The argument is a bit string, with each bit specifying a power source that,
398 * when the device is connected to that source, causes the device to stay on.
399 * See {@link android.os.BatteryManager} for the list of power sources that
400 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
401 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
402 * @param val an {@code int} containing the bits that specify which power sources
403 * should cause the device to stay on.
404 */
405 public void setStayOnSetting(int val) {
406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
407 Settings.System.putInt(mContext.getContentResolver(),
408 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
409 }
410
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800411 public void setMaximumScreenOffTimeount(int timeMs) {
412 mContext.enforceCallingOrSelfPermission(
413 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
414 synchronized (mLocks) {
415 mMaximumScreenOffTimeout = timeMs;
416 // recalculate everything
417 setScreenOffTimeoutsLocked();
418 }
419 }
420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700422 private int getInt(String name, int defValue) {
423 ContentValues values = mSettings.getValues(name);
424 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
425 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
427
428 public void update(Observable o, Object arg) {
429 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700430 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
431 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
432 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 updateWakeLockLocked();
434
Amith Yamasani8b619832010-09-22 16:11:59 -0700435 // SCREEN_OFF_TIMEOUT, default to 15 seconds
436 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437
438 // DIM_SCREEN
439 //mDimScreen = getInt(DIM_SCREEN) != 0;
440
Amith Yamasani8b619832010-09-22 16:11:59 -0700441 // SCREEN_BRIGHTNESS_MODE, default to manual
442 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
443 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 // recalculate everything
446 setScreenOffTimeoutsLocked();
447 }
448 }
449 }
450
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700451 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 // Hack to get our uid... should have a func for this.
453 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700454 MY_UID = Process.myUid();
455 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 Binder.restoreCallingIdentity(token);
457
458 // XXX remove this when the kernel doesn't timeout wake locks
459 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
460
461 // assume nothing is on yet
462 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 // Add ourself to the Watchdog monitors.
465 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
467
468 private ContentQueryMap mSettings;
469
Mike Lockwood3a322132009-11-24 00:30:52 -0500470 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700471 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500472 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 mContext = context;
474 mActivityService = activity;
475 mBatteryStats = BatteryStatsService.getService();
476 mBatteryService = battery;
477
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500478 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
479 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
480 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
481 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 mHandlerThread = new HandlerThread("PowerManagerService") {
484 @Override
485 protected void onLooperPrepared() {
486 super.onLooperPrepared();
487 initInThread();
488 }
489 };
490 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 synchronized (mHandlerThread) {
493 while (!mInitComplete) {
494 try {
495 mHandlerThread.wait();
496 } catch (InterruptedException e) {
497 // Ignore
498 }
499 }
500 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700501
502 nativeInit();
503 synchronized (mLocks) {
504 updateNativePowerStateLocked();
505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 void initInThread() {
509 mHandler = new Handler();
510
511 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700512 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
514 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
515 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
516 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
517 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
518 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500519 mProximityPartialLock = new UnsynchronizedWakeLock(
520 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521
522 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
523 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
524 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
525 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
526
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700527 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400528
529 // read settings for auto-brightness
530 mUseSoftwareAutoBrightness = resources.getBoolean(
531 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400532 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700533 mAutoBrightnessLevels = resources.getIntArray(
534 com.android.internal.R.array.config_autoBrightnessLevels);
535 mLcdBacklightValues = resources.getIntArray(
536 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
537 mButtonBacklightValues = resources.getIntArray(
538 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
539 mKeyboardBacklightValues = resources.getIntArray(
540 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500541 mLightSensorWarmupTime = resources.getInteger(
542 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700543 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700544
545 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
547 "(" + Settings.System.NAME + "=?) or ("
548 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700549 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700551 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
552 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 null);
554 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
555 SettingsObserver settingsObserver = new SettingsObserver();
556 mSettings.addObserver(settingsObserver);
557
558 // pretend that the settings changed so we will get their initial state
559 settingsObserver.update(mSettings, null);
560
561 // register for the battery changed notifications
562 IntentFilter filter = new IntentFilter();
563 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
564 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500565 filter = new IntentFilter();
566 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
567 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500568 filter = new IntentFilter();
569 filter.addAction(Intent.ACTION_DOCK_EVENT);
570 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571
Doug Zongker43866e02010-01-07 12:09:54 -0800572 // Listen for secure settings changes
573 mContext.getContentResolver().registerContentObserver(
574 Settings.Secure.CONTENT_URI, true,
575 new ContentObserver(new Handler()) {
576 public void onChange(boolean selfChange) {
577 updateSettingsValues();
578 }
579 });
580 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 synchronized (mHandlerThread) {
583 mInitComplete = true;
584 mHandlerThread.notifyAll();
585 }
586 }
587
588 private class WakeLock implements IBinder.DeathRecipient
589 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700590 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 super();
592 flags = f;
593 binder = b;
594 tag = t;
595 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700596 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 if (u != MY_UID || (
598 !"KEEP_SCREEN_ON_FLAG".equals(tag)
599 && !"KeyInputQueue".equals(tag))) {
600 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
601 ? BatteryStats.WAKE_TYPE_PARTIAL
602 : BatteryStats.WAKE_TYPE_FULL;
603 } else {
604 monitorType = -1;
605 }
606 try {
607 b.linkToDeath(this, 0);
608 } catch (RemoteException e) {
609 binderDied();
610 }
611 }
612 public void binderDied() {
613 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500614 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
616 }
617 final int flags;
618 final IBinder binder;
619 final String tag;
620 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400621 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700623 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 boolean activated = true;
625 int minState;
626 }
627
628 private void updateWakeLockLocked() {
629 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
630 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
631 mStayOnWhilePluggedInScreenDimLock.acquire();
632 mStayOnWhilePluggedInPartialLock.acquire();
633 } else {
634 mStayOnWhilePluggedInScreenDimLock.release();
635 mStayOnWhilePluggedInPartialLock.release();
636 }
637 }
638
639 private boolean isScreenLock(int flags)
640 {
641 int n = flags & LOCK_MASK;
642 return n == PowerManager.FULL_WAKE_LOCK
643 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400644 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
645 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700648 void enforceWakeSourcePermission(int uid, int pid) {
649 if (uid == Process.myUid()) {
650 return;
651 }
652 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
653 pid, uid, null);
654 }
655
656 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700658 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700659 if (uid != Process.myUid()) {
660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
661 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700662 if (ws != null) {
663 enforceWakeSourcePermission(uid, pid);
664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 long ident = Binder.clearCallingIdentity();
666 try {
667 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700668 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670 } finally {
671 Binder.restoreCallingIdentity(ident);
672 }
673 }
674
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700675 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700676 if (wl.monitorType >= 0) {
677 long origId = Binder.clearCallingIdentity();
678 try {
679 if (ws != null) {
680 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
681 wl.monitorType);
682 } else {
683 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
684 }
685 } catch (RemoteException e) {
686 // Ignore
687 } finally {
688 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700689 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700690 }
691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700693 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700694 if (wl.monitorType >= 0) {
695 long origId = Binder.clearCallingIdentity();
696 try {
697 if (ws != null) {
698 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
699 wl.monitorType);
700 } else {
701 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
702 }
703 } catch (RemoteException e) {
704 // Ignore
705 } finally {
706 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700707 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700708 }
709 }
710
711 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
712 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800714 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700717 if (ws != null && ws.size() == 0) {
718 ws = null;
719 }
720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 int index = mLocks.getIndex(lock);
722 WakeLock wl;
723 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700724 boolean diffsource;
725 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700727 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 switch (wl.flags & LOCK_MASK)
729 {
730 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500731 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400732 wl.minState = SCREEN_BRIGHT;
733 } else {
734 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 break;
737 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
738 wl.minState = SCREEN_BRIGHT;
739 break;
740 case PowerManager.SCREEN_DIM_WAKE_LOCK:
741 wl.minState = SCREEN_DIM;
742 break;
743 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700744 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 break;
746 default:
747 // just log and bail. we're in the server, so don't
748 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 + " flags=" + flags);
751 return;
752 }
753 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700754 if (ws != null) {
755 wl.ws = new WorkSource(ws);
756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700758 diffsource = false;
759 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 } else {
761 wl = mLocks.get(index);
762 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700763 oldsource = wl.ws;
764 if (oldsource != null) {
765 if (ws == null) {
766 wl.ws = null;
767 diffsource = true;
768 } else {
769 diffsource = oldsource.diff(ws);
770 }
771 } else if (ws != null) {
772 diffsource = true;
773 } else {
774 diffsource = false;
775 }
776 if (diffsource) {
777 wl.ws = new WorkSource(ws);
778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
780 if (isScreenLock(flags)) {
781 // if this causes a wakeup, we reactivate all of the locks and
782 // set it to whatever they want. otherwise, we modulate that
783 // by the current state so we never turn it more on than
784 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400785 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
786 mProximityWakeLockCount++;
787 if (mProximityWakeLockCount == 1) {
788 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400791 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
792 int oldWakeLockState = mWakeLockState;
793 mWakeLockState = mLocks.reactivateScreenLocksLocked();
794 if (mSpew) {
795 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
796 + " mWakeLockState=0x"
797 + Integer.toHexString(mWakeLockState)
798 + " previous wakeLockState=0x"
799 + Integer.toHexString(oldWakeLockState));
800 }
801 } else {
802 if (mSpew) {
803 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
804 + " mLocks.gatherState()=0x"
805 + Integer.toHexString(mLocks.gatherState())
806 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
807 }
808 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400810 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 }
813 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
814 if (newlock) {
815 mPartialCount++;
816 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 }
819 }
820 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700823 if (diffsource) {
824 // If the lock sources have changed, need to first release the
825 // old ones.
826 noteStopWakeLocked(wl, oldsource);
827 }
828 if (newlock || diffsource) {
829 noteStartWakeLocked(wl, ws);
830 }
831 }
832
833 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
834 int uid = Binder.getCallingUid();
835 int pid = Binder.getCallingPid();
836 if (ws != null && ws.size() == 0) {
837 ws = null;
838 }
839 if (ws != null) {
840 enforceWakeSourcePermission(uid, pid);
841 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700842 synchronized (mLocks) {
843 int index = mLocks.getIndex(lock);
844 if (index < 0) {
845 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700847 WakeLock wl = mLocks.get(index);
848 WorkSource oldsource = wl.ws;
849 wl.ws = ws != null ? new WorkSource(ws) : null;
850 noteStopWakeLocked(wl, oldsource);
851 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853 }
854
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500855 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700856 int uid = Binder.getCallingUid();
857 if (uid != Process.myUid()) {
858 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
861 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500862 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
864 }
865
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500866 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 WakeLock wl = mLocks.removeLock(lock);
868 if (wl == null) {
869 return;
870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800873 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
875 }
876
877 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400878 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
879 mProximityWakeLockCount--;
880 if (mProximityWakeLockCount == 0) {
881 if (mProximitySensorActive &&
882 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
883 // wait for proximity sensor to go negative before disabling sensor
884 if (mDebugProximitySensor) {
885 Slog.d(TAG, "waiting for proximity sensor to go negative");
886 }
887 } else {
888 disableProximityLockLocked();
889 }
890 }
891 } else {
892 mWakeLockState = mLocks.gatherState();
893 // goes in the middle to reduce flicker
894 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
895 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
896 }
897 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
901 mPartialCount--;
902 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 Power.releaseWakeLock(PARTIAL_NAME);
905 }
906 }
907 // Unlink the lock from the binder.
908 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909
Dianne Hackborn70be1672010-09-14 11:13:03 -0700910 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 private class PokeLock implements IBinder.DeathRecipient
914 {
915 PokeLock(int p, IBinder b, String t) {
916 super();
917 this.pokey = p;
918 this.binder = b;
919 this.tag = t;
920 try {
921 b.linkToDeath(this, 0);
922 } catch (RemoteException e) {
923 binderDied();
924 }
925 }
926 public void binderDied() {
927 setPokeLock(0, this.binder, this.tag);
928 }
929 int pokey;
930 IBinder binder;
931 String tag;
932 boolean awakeOnSet;
933 }
934
935 public void setPokeLock(int pokey, IBinder token, String tag) {
936 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
937 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800938 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 return;
940 }
941
942 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
943 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
944 + " and POKE_LOCK_MEDIUM_TIMEOUT");
945 }
946
947 synchronized (mLocks) {
948 if (pokey != 0) {
949 PokeLock p = mPokeLocks.get(token);
950 int oldPokey = 0;
951 if (p != null) {
952 oldPokey = p.pokey;
953 p.pokey = pokey;
954 } else {
955 p = new PokeLock(pokey, token, tag);
956 mPokeLocks.put(token, p);
957 }
958 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
959 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
960 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
961 p.awakeOnSet = true;
962 }
963 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -0700964 PokeLock rLock = mPokeLocks.remove(token);
965 if (rLock != null) {
966 token.unlinkToDeath(rLock, 0);
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969
970 int oldPokey = mPokey;
971 int cumulative = 0;
972 boolean oldAwakeOnSet = mPokeAwakeOnSet;
973 boolean awakeOnSet = false;
974 for (PokeLock p: mPokeLocks.values()) {
975 cumulative |= p.pokey;
976 if (p.awakeOnSet) {
977 awakeOnSet = true;
978 }
979 }
980 mPokey = cumulative;
981 mPokeAwakeOnSet = awakeOnSet;
982
983 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
984 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 if (oldCumulativeTimeout != newCumulativeTimeout) {
987 setScreenOffTimeoutsLocked();
988 // reset the countdown timer, but use the existing nextState so it doesn't
989 // change anything
990 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
991 }
992 }
993 }
994
995 private static String lockType(int type)
996 {
997 switch (type)
998 {
999 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001000 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001002 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001004 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001006 return "PARTIAL_WAKE_LOCK ";
1007 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1008 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 default:
David Brown251faa62009-08-02 22:04:36 -07001010 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
1012 }
1013
1014 private static String dumpPowerState(int state) {
1015 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1016 ? "KEYBOARD_BRIGHT_BIT " : "")
1017 + (((state & SCREEN_BRIGHT_BIT) != 0)
1018 ? "SCREEN_BRIGHT_BIT " : "")
1019 + (((state & SCREEN_ON_BIT) != 0)
1020 ? "SCREEN_ON_BIT " : "")
1021 + (((state & BATTERY_LOW_BIT) != 0)
1022 ? "BATTERY_LOW_BIT " : "");
1023 }
1024
1025 @Override
1026 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1027 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1028 != PackageManager.PERMISSION_GRANTED) {
1029 pw.println("Permission Denial: can't dump PowerManager from from pid="
1030 + Binder.getCallingPid()
1031 + ", uid=" + Binder.getCallingUid());
1032 return;
1033 }
1034
1035 long now = SystemClock.uptimeMillis();
1036
Mike Lockwoodca44df82010-02-25 13:48:49 -05001037 synchronized (mLocks) {
1038 pw.println("Power Manager State:");
1039 pw.println(" mIsPowered=" + mIsPowered
1040 + " mPowerState=" + mPowerState
1041 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1042 + " ms");
1043 pw.println(" mPartialCount=" + mPartialCount);
1044 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1045 pw.println(" mUserState=" + dumpPowerState(mUserState));
1046 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1047 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1048 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1049 + " " + ((mNextTimeout-now)/1000) + "s from now");
1050 pw.println(" mDimScreen=" + mDimScreen
1051 + " mStayOnConditions=" + mStayOnConditions);
1052 pw.println(" mScreenOffReason=" + mScreenOffReason
1053 + " mUserState=" + mUserState);
1054 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1055 + ',' + mBroadcastQueue[2] + "}");
1056 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1057 + ',' + mBroadcastWhy[2] + "}");
1058 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1059 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1060 + " mUserActivityAllowed=" + mUserActivityAllowed);
1061 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1062 + " mScreenOffDelay=" + mScreenOffDelay);
1063 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1064 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1065 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1066 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1067 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1068 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1069 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1070 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1071 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1072 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1073 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1074 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1075 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1076 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1077 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1078 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1079 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1080 pw.println(" mLightSensorValue=" + mLightSensorValue
1081 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
1082 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1083 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1084 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1085 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1086 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1087 mScreenBrightness.dump(pw, " mScreenBrightness: ");
1088 mKeyboardBrightness.dump(pw, " mKeyboardBrightness: ");
1089 mButtonBrightness.dump(pw, " mButtonBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
Mike Lockwoodca44df82010-02-25 13:48:49 -05001091 int N = mLocks.size();
1092 pw.println();
1093 pw.println("mLocks.size=" + N + ":");
1094 for (int i=0; i<N; i++) {
1095 WakeLock wl = mLocks.get(i);
1096 String type = lockType(wl.flags & LOCK_MASK);
1097 String acquireCausesWakeup = "";
1098 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1099 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1100 }
1101 String activated = "";
1102 if (wl.activated) {
1103 activated = " activated";
1104 }
1105 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001106 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1107 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001109
1110 pw.println();
1111 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1112 for (PokeLock p: mPokeLocks.values()) {
1113 pw.println(" poke lock '" + p.tag + "':"
1114 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1115 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1116 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1117 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1118 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1119 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1120 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1121 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001123
Mike Lockwoodca44df82010-02-25 13:48:49 -05001124 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127
Joe Onorato7999bff2010-07-24 11:50:05 -04001128 private void setTimeoutLocked(long now, int nextState) {
1129 setTimeoutLocked(now, -1, nextState);
1130 }
1131
1132 // If they gave a timeoutOverride it is the number of seconds
1133 // to screen-off. Figure out where in the countdown cycle we
1134 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001135 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1136 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001137 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001138 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001139 long when = 0;
1140 if (timeoutOverride <= 0) {
1141 switch (nextState)
1142 {
1143 case SCREEN_BRIGHT:
1144 when = now + mKeylightDelay;
1145 break;
1146 case SCREEN_DIM:
1147 if (mDimDelay >= 0) {
1148 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001149 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001150 } else {
1151 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1152 }
1153 case SCREEN_OFF:
1154 synchronized (mLocks) {
1155 when = now + mScreenOffDelay;
1156 }
1157 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001158 default:
1159 when = now;
1160 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001162 } else {
1163 override: {
1164 if (timeoutOverride <= mScreenOffDelay) {
1165 when = now + timeoutOverride;
1166 nextState = SCREEN_OFF;
1167 break override;
1168 }
1169 timeoutOverride -= mScreenOffDelay;
1170
1171 if (mDimDelay >= 0) {
1172 if (timeoutOverride <= mDimDelay) {
1173 when = now + timeoutOverride;
1174 nextState = SCREEN_DIM;
1175 break override;
1176 }
1177 timeoutOverride -= mDimDelay;
1178 }
1179
1180 when = now + timeoutOverride;
1181 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001183 }
1184 if (mSpew) {
1185 Slog.d(TAG, "setTimeoutLocked now=" + now
1186 + " timeoutOverride=" + timeoutOverride
1187 + " nextState=" + nextState + " when=" + when);
1188 }
Joe Onorato797e6882010-08-26 14:46:01 -04001189
1190 mHandler.removeCallbacks(mTimeoutTask);
1191 mTimeoutTask.nextState = nextState;
1192 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1193 ? (originalTimeoutOverride - timeoutOverride)
1194 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001195 mHandler.postAtTime(mTimeoutTask, when);
1196 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199 }
1200
1201 private void cancelTimerLocked()
1202 {
1203 mHandler.removeCallbacks(mTimeoutTask);
1204 mTimeoutTask.nextState = -1;
1205 }
1206
1207 private class TimeoutTask implements Runnable
1208 {
1209 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001210 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 public void run()
1212 {
1213 synchronized (mLocks) {
1214 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001215 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
1217
1218 if (nextState == -1) {
1219 return;
1220 }
1221
1222 mUserState = this.nextState;
1223 setPowerState(this.nextState | mWakeLockState);
1224
1225 long now = SystemClock.uptimeMillis();
1226
1227 switch (this.nextState)
1228 {
1229 case SCREEN_BRIGHT:
1230 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001231 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 break;
1233 }
1234 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001235 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 break;
1237 }
1238 }
1239 }
1240 }
1241
1242 private void sendNotificationLocked(boolean on, int why)
1243 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001244 if (!on) {
1245 mStillNeedSleepNotification = false;
1246 }
1247
Joe Onorato128e7292009-03-24 18:41:31 -07001248 // Add to the queue.
1249 int index = 0;
1250 while (mBroadcastQueue[index] != -1) {
1251 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 }
Joe Onorato128e7292009-03-24 18:41:31 -07001253 mBroadcastQueue[index] = on ? 1 : 0;
1254 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255
Joe Onorato128e7292009-03-24 18:41:31 -07001256 // If we added it position 2, then there is a pair that can be stripped.
1257 // If we added it position 1 and we're turning the screen off, we can strip
1258 // the pair and do nothing, because the screen is already off, and therefore
1259 // keyguard has already been enabled.
1260 // However, if we added it at position 1 and we're turning it on, then position
1261 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1262 // on, so have to run the queue then.
1263 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001264 // While we're collapsing them, if it's going off, and the new reason
1265 // is more significant than the first, then use the new one.
1266 if (!on && mBroadcastWhy[0] > why) {
1267 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001268 }
1269 mBroadcastQueue[0] = on ? 1 : 0;
1270 mBroadcastQueue[1] = -1;
1271 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001272 mBroadcastWakeLock.release();
1273 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001274 index = 0;
1275 }
1276 if (index == 1 && !on) {
1277 mBroadcastQueue[0] = -1;
1278 mBroadcastQueue[1] = -1;
1279 index = -1;
1280 // The wake lock was being held, but we're not actually going to do any
1281 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001282 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001284 }
1285
1286 // Now send the message.
1287 if (index >= 0) {
1288 // Acquire the broadcast wake lock before changing the power
1289 // state. It will be release after the broadcast is sent.
1290 // We always increment the ref count for each notification in the queue
1291 // and always decrement when that notification is handled.
1292 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001293 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001294 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
1296 }
1297
1298 private Runnable mNotificationTask = new Runnable()
1299 {
1300 public void run()
1301 {
Joe Onorato128e7292009-03-24 18:41:31 -07001302 while (true) {
1303 int value;
1304 int why;
1305 WindowManagerPolicy policy;
1306 synchronized (mLocks) {
1307 value = mBroadcastQueue[0];
1308 why = mBroadcastWhy[0];
1309 for (int i=0; i<2; i++) {
1310 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1311 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1312 }
1313 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
Joe Onorato128e7292009-03-24 18:41:31 -07001315 if (value == 1) {
1316 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001317
Joe Onorato128e7292009-03-24 18:41:31 -07001318 policy.screenTurnedOn();
1319 try {
1320 ActivityManagerNative.getDefault().wakingUp();
1321 } catch (RemoteException e) {
1322 // ignore it
1323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324
Joe Onorato128e7292009-03-24 18:41:31 -07001325 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001326 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001327 }
1328 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1329 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1330 mScreenOnBroadcastDone, mHandler, 0, null, null);
1331 } else {
1332 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001333 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001334 mBroadcastWakeLock.mCount);
1335 mBroadcastWakeLock.release();
1336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338 }
Joe Onorato128e7292009-03-24 18:41:31 -07001339 else if (value == 0) {
1340 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001341
Joe Onorato128e7292009-03-24 18:41:31 -07001342 policy.screenTurnedOff(why);
1343 try {
1344 ActivityManagerNative.getDefault().goingToSleep();
1345 } catch (RemoteException e) {
1346 // ignore it.
1347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348
Joe Onorato128e7292009-03-24 18:41:31 -07001349 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1350 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1351 mScreenOffBroadcastDone, mHandler, 0, null, null);
1352 } else {
1353 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001354 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001355 mBroadcastWakeLock.mCount);
1356 mBroadcastWakeLock.release();
1357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359 }
Joe Onorato128e7292009-03-24 18:41:31 -07001360 else {
1361 // If we're in this case, then this handler is running for a previous
1362 // paired transaction. mBroadcastWakeLock will already have been released.
1363 break;
1364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366 }
1367 };
1368
1369 long mScreenOnStart;
1370 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1371 public void onReceive(Context context, Intent intent) {
1372 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001373 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1375 mBroadcastWakeLock.release();
1376 }
1377 }
1378 };
1379
1380 long mScreenOffStart;
1381 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1382 public void onReceive(Context context, Intent intent) {
1383 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001384 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1386 mBroadcastWakeLock.release();
1387 }
1388 }
1389 };
1390
1391 void logPointerUpEvent() {
1392 if (LOG_TOUCH_DOWNS) {
1393 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1394 mLastTouchDown = 0;
1395 }
1396 }
1397
1398 void logPointerDownEvent() {
1399 if (LOG_TOUCH_DOWNS) {
1400 // If we are not already timing a down/up sequence
1401 if (mLastTouchDown == 0) {
1402 mLastTouchDown = SystemClock.elapsedRealtime();
1403 mTouchCycles++;
1404 }
1405 }
1406 }
1407
1408 /**
1409 * Prevents the screen from turning on even if it *should* turn on due
1410 * to a subsequent full wake lock being acquired.
1411 * <p>
1412 * This is a temporary hack that allows an activity to "cover up" any
1413 * display glitches that happen during the activity's startup
1414 * sequence. (Specifically, this API was added to work around a
1415 * cosmetic bug in the "incoming call" sequence, where the lock screen
1416 * would flicker briefly before the incoming call UI became visible.)
1417 * TODO: There ought to be a more elegant way of doing this,
1418 * probably by having the PowerManager and ActivityManager
1419 * work together to let apps specify that the screen on/off
1420 * state should be synchronized with the Activity lifecycle.
1421 * <p>
1422 * Note that calling preventScreenOn(true) will NOT turn the screen
1423 * off if it's currently on. (This API only affects *future*
1424 * acquisitions of full wake locks.)
1425 * But calling preventScreenOn(false) WILL turn the screen on if
1426 * it's currently off because of a prior preventScreenOn(true) call.
1427 * <p>
1428 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1429 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1430 * call doesn't occur within 5 seconds, we'll turn the screen back on
1431 * ourselves (and log a warning about it); this prevents a buggy app
1432 * from disabling the screen forever.)
1433 * <p>
1434 * TODO: this feature should really be controlled by a new type of poke
1435 * lock (rather than an IPowerManager call).
1436 */
1437 public void preventScreenOn(boolean prevent) {
1438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1439
1440 synchronized (mLocks) {
1441 if (prevent) {
1442 // First of all, grab a partial wake lock to
1443 // make sure the CPU stays on during the entire
1444 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1445 mPreventScreenOnPartialLock.acquire();
1446
1447 // Post a forceReenableScreen() call (for 5 seconds in the
1448 // future) to make sure the matching preventScreenOn(false) call
1449 // has happened by then.
1450 mHandler.removeCallbacks(mForceReenableScreenTask);
1451 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1452
1453 // Finally, set the flag that prevents the screen from turning on.
1454 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001455 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 mPreventScreenOn = true;
1457 } else {
1458 // (Re)enable the screen.
1459 mPreventScreenOn = false;
1460
1461 // We're "undoing" a the prior preventScreenOn(true) call, so we
1462 // no longer need the 5-second safeguard.
1463 mHandler.removeCallbacks(mForceReenableScreenTask);
1464
1465 // Forcibly turn on the screen if it's supposed to be on. (This
1466 // handles the case where the screen is currently off because of
1467 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001468 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001470 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1472 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001473 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001475 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477 }
1478
1479 // Release the partial wake lock that we held during the
1480 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1481 mPreventScreenOnPartialLock.release();
1482 }
1483 }
1484 }
1485
1486 public void setScreenBrightnessOverride(int brightness) {
1487 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1488
Mike Lockwoodf527c712010-06-10 14:12:33 -04001489 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 synchronized (mLocks) {
1491 if (mScreenBrightnessOverride != brightness) {
1492 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001493 if (isScreenOn()) {
1494 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497 }
1498 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001499
1500 public void setButtonBrightnessOverride(int brightness) {
1501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1502
Mike Lockwoodf527c712010-06-10 14:12:33 -04001503 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001504 synchronized (mLocks) {
1505 if (mButtonBrightnessOverride != brightness) {
1506 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001507 if (isScreenOn()) {
1508 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1509 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001510 }
1511 }
1512 }
1513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 /**
1515 * Sanity-check that gets called 5 seconds after any call to
1516 * preventScreenOn(true). This ensures that the original call
1517 * is followed promptly by a call to preventScreenOn(false).
1518 */
1519 private void forceReenableScreen() {
1520 // We shouldn't get here at all if mPreventScreenOn is false, since
1521 // we should have already removed any existing
1522 // mForceReenableScreenTask messages...
1523 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 return;
1526 }
1527
1528 // Uh oh. It's been 5 seconds since a call to
1529 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1530 // This means the app that called preventScreenOn(true) is either
1531 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1532 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1533 // crashed before doing so.)
1534
1535 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001536 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 + "Forcing the screen back on...");
1538 preventScreenOn(false);
1539 }
1540
1541 private Runnable mForceReenableScreenTask = new Runnable() {
1542 public void run() {
1543 forceReenableScreen();
1544 }
1545 };
1546
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001547 private int setScreenStateLocked(boolean on) {
1548 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001549 if (err == 0) {
1550 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1551 if (mUseSoftwareAutoBrightness) {
1552 enableLightSensor(on);
1553 if (!on) {
1554 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001555 mButtonLight.turnOff();
1556 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001557 // clear current value so we will update based on the new conditions
1558 // when the sensor is reenabled.
1559 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001560 // reset our highest light sensor value when the screen turns off
1561 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001562 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001563 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001564 }
1565 return err;
1566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 private void setPowerState(int state)
1569 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001570 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572
Mike Lockwood435eb642009-12-03 08:40:18 -05001573 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 {
1575 synchronized (mLocks) {
1576 int err;
1577
1578 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001579 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001581 + " noChangeLights=" + noChangeLights
1582 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
1585 if (noChangeLights) {
1586 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1587 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001588 if (mProximitySensorActive) {
1589 // don't turn on the screen when the proximity sensor lock is held
1590 newState = (newState & ~SCREEN_BRIGHT);
1591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592
1593 if (batteryIsLow()) {
1594 newState |= BATTERY_LOW_BIT;
1595 } else {
1596 newState &= ~BATTERY_LOW_BIT;
1597 }
1598 if (newState == mPowerState) {
1599 return;
1600 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001601
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001602 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 newState |= ALL_BRIGHT;
1604 }
1605
1606 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1607 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1608
Mike Lockwood51b844962009-11-16 21:51:18 -05001609 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001610 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001612 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001614 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001618 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1622 }
1623
1624 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001625 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1627 }
1628
1629 if (oldScreenOn != newScreenOn) {
1630 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001631 // When the user presses the power button, we need to always send out the
1632 // notification that it's going to sleep so the keyguard goes on. But
1633 // we can't do that until the screen fades out, so we don't show the keyguard
1634 // too early.
1635 if (mStillNeedSleepNotification) {
1636 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 // Turn on the screen UNLESS there was a prior
1640 // preventScreenOn(true) request. (Note that the lifetime
1641 // of a single preventScreenOn() request is limited to 5
1642 // seconds to prevent a buggy app from disabling the
1643 // screen forever; see forceReenableScreen().)
1644 boolean reallyTurnScreenOn = true;
1645 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001646 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 + mPreventScreenOn);
1648 }
1649
1650 if (mPreventScreenOn) {
1651 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001652 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654 reallyTurnScreenOn = false;
1655 }
1656 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001657 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 long identity = Binder.clearCallingIdentity();
1659 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001660 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 mBatteryStats.noteScreenOn();
1662 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001663 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 } finally {
1665 Binder.restoreCallingIdentity(identity);
1666 }
1667 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001668 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 // But continue as if we really did turn the screen on...
1670 err = 0;
1671 }
1672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 mLastTouchDown = 0;
1674 mTotalTouchDownTime = 0;
1675 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001676 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 mTotalTouchDownTime, mTouchCycles);
1678 if (err == 0) {
1679 mPowerState |= SCREEN_ON_BIT;
1680 sendNotificationLocked(true, -1);
1681 }
1682 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001683 // cancel light sensor task
1684 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 mScreenOffTime = SystemClock.elapsedRealtime();
1686 long identity = Binder.clearCallingIdentity();
1687 try {
1688 mBatteryStats.noteScreenOff();
1689 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001690 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 } finally {
1692 Binder.restoreCallingIdentity(identity);
1693 }
1694 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001695 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001697 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 err = 0;
1700 mLastTouchDown = 0;
1701 }
1702 }
1703 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001704
1705 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001708
1709 private void updateNativePowerStateLocked() {
1710 nativeSetPowerState(
1711 (mPowerState & SCREEN_ON_BIT) != 0,
1712 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001714
Mike Lockwood435eb642009-12-03 08:40:18 -05001715 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001717 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 // called multiple times in the same state. -joeo
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001719 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime, mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001721 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001723 mScreenOffReason = reason;
1724 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726 return err;
1727 }
1728
1729 private boolean batteryIsLow() {
1730 return (!mIsPowered &&
1731 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1732 }
1733
The Android Open Source Project10592532009-03-18 17:39:46 -07001734 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001735 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001736 newState = applyButtonState(newState);
1737 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001738 final int realDifference = (newState ^ oldState);
1739 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 int offMask = 0;
1745 int dimMask = 0;
1746 int onMask = 0;
1747
1748 int preferredBrightness = getPreferredBrightness();
1749 boolean startAnimation = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
1752 if (ANIMATE_KEYBOARD_LIGHTS) {
1753 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1754 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001755 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001756 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001758 mKeyboardBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001759 ANIM_STEPS, INITIAL_KEYBOARD_BRIGHTNESS,
1760 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762 startAnimation = true;
1763 } else {
1764 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001765 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001767 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769 }
1770 }
1771
1772 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
1773 if (ANIMATE_BUTTON_LIGHTS) {
1774 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1775 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_OFF,
Joe Onorato128e7292009-03-24 18:41:31 -07001776 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001777 Power.BRIGHTNESS_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 } else {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001779 mButtonBrightness.setTargetLocked(Power.BRIGHTNESS_ON,
Joe Onorato128e7292009-03-24 18:41:31 -07001780 ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
1781 Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783 startAnimation = true;
1784 } else {
1785 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001786 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001788 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790 }
1791 }
1792
1793 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1794 if (ANIMATE_SCREEN_LIGHTS) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001795 int nominalCurrentValue = -1;
1796 // If there was an actual difference in the light state, then
1797 // figure out the "ideal" current value based on the previous
1798 // state. Otherwise, this is a change due to the brightness
1799 // override, so we want to animate from whatever the current
1800 // value is.
1801 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1802 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1803 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1804 nominalCurrentValue = preferredBrightness;
1805 break;
1806 case SCREEN_ON_BIT:
1807 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1808 break;
1809 case 0:
1810 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1811 break;
1812 case SCREEN_BRIGHT_BIT:
1813 default:
1814 // not possible
1815 nominalCurrentValue = (int)mScreenBrightness.curValue;
1816 break;
1817 }
Joe Onorato128e7292009-03-24 18:41:31 -07001818 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001819 int brightness = preferredBrightness;
1820 int steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1822 // dim or turn off backlight, depending on if the screen is on
1823 // the scale is because the brightness ramp isn't linear and this biases
1824 // it so the later parts take longer.
1825 final float scale = 1.5f;
1826 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1827 if (ratio > 1.0f) ratio = 1.0f;
1828 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1830 // was bright
1831 steps = ANIM_STEPS;
1832 } else {
1833 // was dim
1834 steps = (int)(ANIM_STEPS*ratio*scale);
1835 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001836 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 if ((oldState & SCREEN_ON_BIT) != 0) {
1839 // was bright
1840 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1841 } else {
1842 // was dim
1843 steps = (int)(ANIM_STEPS*ratio);
1844 }
1845 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1846 // If the "stay on while plugged in" option is
1847 // turned on, then the screen will often not
1848 // automatically turn off while plugged in. To
1849 // still have a sense of when it is inactive, we
1850 // will then count going dim as turning off.
1851 mScreenOffTime = SystemClock.elapsedRealtime();
1852 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001853 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001856 long identity = Binder.clearCallingIdentity();
1857 try {
1858 mBatteryStats.noteScreenBrightness(brightness);
1859 } catch (RemoteException e) {
1860 // Nothing interesting to do.
1861 } finally {
1862 Binder.restoreCallingIdentity(identity);
1863 }
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001864 if (mScreenBrightness.setTargetLocked(brightness,
1865 steps, INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue)) {
1866 startAnimation = true;
1867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 } else {
1869 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1870 // dim or turn off backlight, depending on if the screen is on
1871 if ((newState & SCREEN_ON_BIT) == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001872 offMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001874 dimMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07001877 onMask |= SCREEN_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 }
1880 }
1881
1882 if (startAnimation) {
1883 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001884 Slog.i(TAG, "Scheduling light animator!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 mHandler.removeCallbacks(mLightAnimator);
1887 mHandler.post(mLightAnimator);
1888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001891 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001892 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 if (dimMask != 0) {
1895 int brightness = Power.BRIGHTNESS_DIM;
1896 if ((newState & BATTERY_LOW_BIT) != 0 &&
1897 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1898 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1899 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001900 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001901 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903 if (onMask != 0) {
1904 int brightness = getPreferredBrightness();
1905 if ((newState & BATTERY_LOW_BIT) != 0 &&
1906 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1907 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1908 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001909 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001910 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913
The Android Open Source Project10592532009-03-18 17:39:46 -07001914 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001915 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001916 ? LightsService.BRIGHTNESS_MODE_SENSOR
1917 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001918 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001919 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001920 }
1921 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001922 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001923 }
1924 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001925 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928
1929 class BrightnessState {
1930 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 boolean initialized;
1933 int targetValue;
1934 float curValue;
1935 float delta;
1936 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 BrightnessState(int m) {
1939 mask = m;
1940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 public void dump(PrintWriter pw, String prefix) {
1943 pw.println(prefix + "animating=" + animating
1944 + " targetValue=" + targetValue
1945 + " curValue=" + curValue
1946 + " delta=" + delta);
1947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001948
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001949 boolean setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001950 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (!initialized) {
1952 initialized = true;
1953 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001954 } else if (targetValue == target) {
1955 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
1957 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001958 delta = (targetValue -
1959 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1960 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001962 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001963 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001964 + " target=" + targetValue + " delta=" + delta
1965 + " nominalCurrentValue=" + nominalCurrentValue
1966 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968 animating = true;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001969 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 boolean stepLocked() {
1973 if (!animating) return false;
1974 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001975 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 + " target=" + targetValue + " delta=" + delta);
1977 }
1978 curValue += delta;
1979 int curIntValue = (int)curValue;
1980 boolean more = true;
1981 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001982 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 more = false;
1984 } else if (delta > 0) {
1985 if (curIntValue >= targetValue) {
1986 curValue = curIntValue = targetValue;
1987 more = false;
1988 }
1989 } else {
1990 if (curIntValue <= targetValue) {
1991 curValue = curIntValue = targetValue;
1992 more = false;
1993 }
1994 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001995 //Slog.i(TAG, "Animating brightess " + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001996 setLightBrightness(mask, curIntValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 animating = more;
1998 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001999 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002000 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002 }
2003 return more;
2004 }
2005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 private class LightAnimator implements Runnable {
2008 public void run() {
2009 synchronized (mLocks) {
2010 long now = SystemClock.uptimeMillis();
2011 boolean more = mScreenBrightness.stepLocked();
2012 if (mKeyboardBrightness.stepLocked()) {
2013 more = true;
2014 }
2015 if (mButtonBrightness.stepLocked()) {
2016 more = true;
2017 }
2018 if (more) {
2019 mHandler.postAtTime(mLightAnimator, now+(1000/60));
2020 }
2021 }
2022 }
2023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 private int getPreferredBrightness() {
2026 try {
2027 if (mScreenBrightnessOverride >= 0) {
2028 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002029 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002030 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002031 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2034 SCREEN_BRIGHTNESS);
2035 // Don't let applications turn the screen all the way off
2036 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2037 } catch (SettingNotFoundException snfe) {
2038 return Power.BRIGHTNESS_ON;
2039 }
2040 }
2041
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002042 private int applyButtonState(int state) {
2043 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002044 if ((state & BATTERY_LOW_BIT) != 0) {
2045 // do not override brightness if the battery is low
2046 return state;
2047 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002048 if (mButtonBrightnessOverride >= 0) {
2049 brightness = mButtonBrightnessOverride;
2050 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2051 brightness = mLightSensorButtonBrightness;
2052 }
2053 if (brightness > 0) {
2054 return state | BUTTON_BRIGHT_BIT;
2055 } else if (brightness == 0) {
2056 return state & ~BUTTON_BRIGHT_BIT;
2057 } else {
2058 return state;
2059 }
2060 }
2061
2062 private int applyKeyboardState(int state) {
2063 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002064 if ((state & BATTERY_LOW_BIT) != 0) {
2065 // do not override brightness if the battery is low
2066 return state;
2067 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002068 if (!mKeyboardVisible) {
2069 brightness = 0;
2070 } else if (mButtonBrightnessOverride >= 0) {
2071 brightness = mButtonBrightnessOverride;
2072 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2073 brightness = mLightSensorKeyboardBrightness;
2074 }
2075 if (brightness > 0) {
2076 return state | KEYBOARD_BRIGHT_BIT;
2077 } else if (brightness == 0) {
2078 return state & ~KEYBOARD_BRIGHT_BIT;
2079 } else {
2080 return state;
2081 }
2082 }
2083
Charles Mendis322591c2009-10-29 11:06:59 -07002084 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 synchronized (mLocks) {
2086 return (mPowerState & SCREEN_ON_BIT) != 0;
2087 }
2088 }
2089
Charles Mendis322591c2009-10-29 11:06:59 -07002090 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 synchronized (mLocks) {
2092 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2093 }
2094 }
2095
Mike Lockwood497087e32009-11-08 18:33:03 -05002096 private boolean isScreenTurningOffLocked() {
2097 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2098 }
2099
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002100 private boolean shouldLog(long time) {
2101 synchronized (mLocks) {
2102 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2103 mWarningSpewThrottleTime = time;
2104 mWarningSpewThrottleCount = 0;
2105 return true;
2106 } else if (mWarningSpewThrottleCount < 30) {
2107 mWarningSpewThrottleCount++;
2108 return true;
2109 } else {
2110 return false;
2111 }
2112 }
2113 }
2114
Mike Lockwood200b30b2009-09-20 00:23:59 -04002115 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002116 if (isScreenTurningOffLocked()) {
2117 // cancel animation so userActivity will succeed
2118 mScreenBrightness.animating = false;
2119 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002120 boolean savedActivityAllowed = mUserActivityAllowed;
2121 mUserActivityAllowed = true;
2122 userActivity(SystemClock.uptimeMillis(), false);
2123 mUserActivityAllowed = savedActivityAllowed;
2124 }
2125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002128 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130
2131 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002132 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2133 != PackageManager.PERMISSION_GRANTED) {
2134 if (shouldLog(time)) {
2135 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2136 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2137 }
2138 return;
2139 }
2140
Joe Onorato7999bff2010-07-24 11:50:05 -04002141 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143
2144 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002145 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
2147
2148 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002149 userActivity(time, -1, noChangeLights, eventType, force);
2150 }
2151
2152 /*
2153 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2154 * on with user activity. Don't use this function.
2155 */
2156 public void clearUserActivityTimeout(long now, long timeout) {
2157 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2158 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2159 userActivity(now, timeout, false, OTHER_EVENT, false);
2160 }
2161
2162 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2163 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164
2165 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002166 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002168 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170 return;
2171 }
2172
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002173 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2174 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2175 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2176 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002177 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002178 }
2179 return;
2180 }
2181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 if (false) {
2183 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002184 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002186 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
2188 }
2189
2190 synchronized (mLocks) {
2191 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 + " mUserActivityAllowed=" + mUserActivityAllowed
2194 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002195 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2196 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002197 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002198 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
Mike Lockwood05067122009-10-27 23:07:25 -04002200 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002201 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002202 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002203 return;
2204 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002205 // Disable proximity sensor if if user presses power key while we are in the
2206 // "waiting for proximity sensor to go negative" state.
2207 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2208 mProximitySensorActive = false;
2209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 if (mLastEventTime <= time || force) {
2211 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002212 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002213 // Only turn on button backlights if a button was pressed
2214 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002215 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2217 } else {
2218 // don't clear button/keyboard backlights when the screen is touched.
2219 mUserState |= SCREEN_BRIGHT;
2220 }
2221
Dianne Hackborn617f8772009-03-31 15:04:46 -07002222 int uid = Binder.getCallingUid();
2223 long ident = Binder.clearCallingIdentity();
2224 try {
2225 mBatteryStats.noteUserActivity(uid, eventType);
2226 } catch (RemoteException e) {
2227 // Ignore
2228 } finally {
2229 Binder.restoreCallingIdentity(ident);
2230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002231
Michael Chane96440f2009-05-06 10:27:36 -07002232 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002233 setPowerState(mUserState | mWakeLockState, noChangeLights,
2234 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002235 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
2237 }
2238 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002239
2240 if (mPolicy != null) {
2241 mPolicy.userActivity();
2242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 }
2244
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002245 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2246 try {
2247 int i;
2248 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2249 if (sensorValue < mAutoBrightnessLevels[i]) {
2250 break;
2251 }
2252 }
2253 return values[i];
2254 } catch (Exception e) {
2255 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002256 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002257 return 255;
2258 }
2259 }
2260
Mike Lockwood20f87d72009-11-05 16:08:51 -05002261 private Runnable mProximityTask = new Runnable() {
2262 public void run() {
2263 synchronized (mLocks) {
2264 if (mProximityPendingValue != -1) {
2265 proximityChangedLocked(mProximityPendingValue == 1);
2266 mProximityPendingValue = -1;
2267 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002268 if (mProximityPartialLock.isHeld()) {
2269 mProximityPartialLock.release();
2270 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002271 }
2272 }
2273 };
2274
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002275 private Runnable mAutoBrightnessTask = new Runnable() {
2276 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002277 synchronized (mLocks) {
2278 int value = (int)mLightSensorPendingValue;
2279 if (value >= 0) {
2280 mLightSensorPendingValue = -1;
2281 lightSensorChangedLocked(value);
2282 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002283 }
2284 }
2285 };
2286
Mike Lockwoodb2865412010-02-02 22:40:33 -05002287 private void dockStateChanged(int state) {
2288 synchronized (mLocks) {
2289 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2290 if (mIsDocked) {
2291 mHighestLightSensorValue = -1;
2292 }
2293 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2294 // force lights recalculation
2295 int value = (int)mLightSensorValue;
2296 mLightSensorValue = -1;
2297 lightSensorChangedLocked(value);
2298 }
2299 }
2300 }
2301
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002302 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002303 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002304 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002305 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002306
Mike Lockwoodb2865412010-02-02 22:40:33 -05002307 // do not allow light sensor value to decrease
2308 if (mHighestLightSensorValue < value) {
2309 mHighestLightSensorValue = value;
2310 }
2311
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002312 if (mLightSensorValue != value) {
2313 mLightSensorValue = value;
2314 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002315 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2316 // we only do this if we are undocked, since lighting should be stable when
2317 // stationary in a dock.
2318 int lcdValue = getAutoBrightnessValue(
2319 (mIsDocked ? value : mHighestLightSensorValue),
2320 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002321 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002322 int keyboardValue;
2323 if (mKeyboardVisible) {
2324 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2325 } else {
2326 keyboardValue = 0;
2327 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002328 mLightSensorScreenBrightness = lcdValue;
2329 mLightSensorButtonBrightness = buttonValue;
2330 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002331
2332 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002333 Slog.d(TAG, "lcdValue " + lcdValue);
2334 Slog.d(TAG, "buttonValue " + buttonValue);
2335 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002336 }
2337
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002338 boolean startAnimation = false;
Mike Lockwood4984e732009-11-01 08:16:33 -05002339 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002340 if (ANIMATE_SCREEN_LIGHTS) {
2341 if (mScreenBrightness.setTargetLocked(lcdValue,
2342 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_SCREEN_BRIGHTNESS,
2343 (int)mScreenBrightness.curValue)) {
2344 startAnimation = true;
2345 }
2346 } else {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002347 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002348 ? LightsService.BRIGHTNESS_MODE_SENSOR
2349 : LightsService.BRIGHTNESS_MODE_USER);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002350 mLcdLight.setBrightness(lcdValue, brightnessMode);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002351 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002352 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002353 if (mButtonBrightnessOverride < 0) {
2354 if (ANIMATE_BUTTON_LIGHTS) {
2355 if (mButtonBrightness.setTargetLocked(buttonValue,
2356 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2357 (int)mButtonBrightness.curValue)) {
2358 startAnimation = true;
2359 }
2360 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002361 mButtonLight.setBrightness(buttonValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002362 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002363 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002364 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
2365 if (ANIMATE_KEYBOARD_LIGHTS) {
2366 if (mKeyboardBrightness.setTargetLocked(keyboardValue,
2367 AUTOBRIGHTNESS_ANIM_STEPS, INITIAL_BUTTON_BRIGHTNESS,
2368 (int)mKeyboardBrightness.curValue)) {
2369 startAnimation = true;
2370 }
2371 } else {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002372 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002373 }
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002374 }
2375 if (startAnimation) {
2376 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002377 Slog.i(TAG, "lightSensorChangedLocked scheduling light animator");
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002378 }
2379 mHandler.removeCallbacks(mLightAnimator);
2380 mHandler.post(mLightAnimator);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002381 }
2382 }
2383 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002384 }
2385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 /**
2387 * The user requested that we go to sleep (probably with the power button).
2388 * This overrides all wake locks that are held.
2389 */
2390 public void goToSleep(long time)
2391 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002392 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2393 }
2394
2395 /**
2396 * The user requested that we go to sleep (probably with the power button).
2397 * This overrides all wake locks that are held.
2398 */
2399 public void goToSleepWithReason(long time, int reason)
2400 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2402 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002403 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
2405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002408 * Reboot the device immediately, passing 'reason' (may be null)
2409 * to the underlying __reboot system call. Should not return.
2410 */
2411 public void reboot(String reason)
2412 {
2413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002414
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002415 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2416 throw new IllegalStateException("Too early to call reboot()");
2417 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002418
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002419 final String finalReason = reason;
2420 Runnable runnable = new Runnable() {
2421 public void run() {
2422 synchronized (this) {
2423 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002424 }
2425
San Mehat1e512792010-01-07 10:40:29 -08002426 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002427 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002428 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002429 mHandler.post(runnable);
2430
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002431 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002432 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002433 while (true) {
2434 try {
2435 runnable.wait();
2436 } catch (InterruptedException e) {
2437 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002438 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002439 }
2440 }
2441
Dan Egnor60d87622009-12-16 16:32:58 -08002442 /**
2443 * Crash the runtime (causing a complete restart of the Android framework).
2444 * Requires REBOOT permission. Mostly for testing. Should not return.
2445 */
2446 public void crash(final String message)
2447 {
2448 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2449 Thread t = new Thread("PowerManagerService.crash()") {
2450 public void run() { throw new RuntimeException(message); }
2451 };
2452 try {
2453 t.start();
2454 t.join();
2455 } catch (InterruptedException e) {
2456 Log.wtf(TAG, e);
2457 }
2458 }
2459
Mike Lockwood435eb642009-12-03 08:40:18 -05002460 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461
2462 if (mLastEventTime <= time) {
2463 mLastEventTime = time;
2464 // cancel all of the wake locks
2465 mWakeLockState = SCREEN_OFF;
2466 int N = mLocks.size();
2467 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002468 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 for (int i=0; i<N; i++) {
2470 WakeLock wl = mLocks.get(i);
2471 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002472 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2473 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2474 proxLock = true;
2475 } else {
2476 mLocks.get(i).activated = false;
2477 numCleared++;
2478 }
2479 }
2480 }
2481 if (!proxLock) {
2482 mProxIgnoredBecauseScreenTurnedOff = true;
2483 if (mDebugProximitySensor) {
2484 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 }
2486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002487 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002488 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002490 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 cancelTimerLocked();
2492 }
2493 }
2494
2495 public long timeSinceScreenOn() {
2496 synchronized (mLocks) {
2497 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2498 return 0;
2499 }
2500 return SystemClock.elapsedRealtime() - mScreenOffTime;
2501 }
2502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002505 synchronized (mLocks) {
2506 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002507 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002508 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002509 if (mKeyboardVisible != visible) {
2510 mKeyboardVisible = visible;
2511 // don't signal user activity if the screen is off; other code
2512 // will take care of turning on due to a true change to the lid
2513 // switch and synchronized with the lock screen.
2514 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002515 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002516 // force recompute of backlight values
2517 if (mLightSensorValue >= 0) {
2518 int value = (int)mLightSensorValue;
2519 mLightSensorValue = -1;
2520 lightSensorChangedLocked(value);
2521 }
2522 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002523 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2524 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002525 }
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
2529 /**
2530 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002531 * When disabling user activity we also reset user power state so the keyguard can reset its
2532 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 */
2534 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002535 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002536 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 synchronized (mLocks) {
2539 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002540 if (!enabled) {
2541 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2542 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545 }
2546
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002547 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002548 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002549 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002550 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002551 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002552 // force recompute of backlight values
2553 if (mLightSensorValue >= 0) {
2554 int value = (int)mLightSensorValue;
2555 mLightSensorValue = -1;
2556 lightSensorChangedLocked(value);
2557 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002558 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002559 }
2560 }
2561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 /** Sets the screen off timeouts:
2563 * mKeylightDelay
2564 * mDimDelay
2565 * mScreenOffDelay
2566 * */
2567 private void setScreenOffTimeoutsLocked() {
2568 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002569 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 mDimDelay = -1;
2571 mScreenOffDelay = 0;
2572 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2573 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2574 mDimDelay = -1;
2575 mScreenOffDelay = 0;
2576 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002577 int totalDelay = mScreenOffTimeoutSetting;
2578 if (totalDelay > mMaximumScreenOffTimeout) {
2579 totalDelay = mMaximumScreenOffTimeout;
2580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2582 if (totalDelay < 0) {
2583 mScreenOffDelay = Integer.MAX_VALUE;
2584 } else if (mKeylightDelay < totalDelay) {
2585 // subtract the time that the keylight delay. This will give us the
2586 // remainder of the time that we need to sleep to get the accurate
2587 // screen off timeout.
2588 mScreenOffDelay = totalDelay - mKeylightDelay;
2589 } else {
2590 mScreenOffDelay = 0;
2591 }
2592 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2593 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2594 mScreenOffDelay = LONG_DIM_TIME;
2595 } else {
2596 mDimDelay = -1;
2597 }
2598 }
2599 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002600 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2602 + " mDimScreen=" + mDimScreen);
2603 }
2604 }
2605
2606 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002607 * Refreshes cached secure settings. Called once on startup, and
2608 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 */
Doug Zongker43866e02010-01-07 12:09:54 -08002610 private void updateSettingsValues() {
2611 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002613 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002615 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617
2618 private class LockList extends ArrayList<WakeLock>
2619 {
2620 void addLock(WakeLock wl)
2621 {
2622 int index = getIndex(wl.binder);
2623 if (index < 0) {
2624 this.add(wl);
2625 }
2626 }
2627
2628 WakeLock removeLock(IBinder binder)
2629 {
2630 int index = getIndex(binder);
2631 if (index >= 0) {
2632 return this.remove(index);
2633 } else {
2634 return null;
2635 }
2636 }
2637
2638 int getIndex(IBinder binder)
2639 {
2640 int N = this.size();
2641 for (int i=0; i<N; i++) {
2642 if (this.get(i).binder == binder) {
2643 return i;
2644 }
2645 }
2646 return -1;
2647 }
2648
2649 int gatherState()
2650 {
2651 int result = 0;
2652 int N = this.size();
2653 for (int i=0; i<N; i++) {
2654 WakeLock wl = this.get(i);
2655 if (wl.activated) {
2656 if (isScreenLock(wl.flags)) {
2657 result |= wl.minState;
2658 }
2659 }
2660 }
2661 return result;
2662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002663
Michael Chane96440f2009-05-06 10:27:36 -07002664 int reactivateScreenLocksLocked()
2665 {
2666 int result = 0;
2667 int N = this.size();
2668 for (int i=0; i<N; i++) {
2669 WakeLock wl = this.get(i);
2670 if (isScreenLock(wl.flags)) {
2671 wl.activated = true;
2672 result |= wl.minState;
2673 }
2674 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002675 if (mDebugProximitySensor) {
2676 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2677 + mProxIgnoredBecauseScreenTurnedOff);
2678 }
2679 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002680 return result;
2681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683
2684 void setPolicy(WindowManagerPolicy p) {
2685 synchronized (mLocks) {
2686 mPolicy = p;
2687 mLocks.notifyAll();
2688 }
2689 }
2690
2691 WindowManagerPolicy getPolicyLocked() {
2692 while (mPolicy == null || !mDoneBooting) {
2693 try {
2694 mLocks.wait();
2695 } catch (InterruptedException e) {
2696 // Ignore
2697 }
2698 }
2699 return mPolicy;
2700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002703 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2704 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2705 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002706 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002707 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002708 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002709 }
2710
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002711 // wait until sensors are enabled before turning on screen.
2712 // some devices will not activate the light sensor properly on boot
2713 // unless we do this.
2714 if (mUseSoftwareAutoBrightness) {
2715 // turn the screen on
2716 setPowerState(SCREEN_BRIGHT);
2717 } else {
2718 // turn everything on
2719 setPowerState(ALL_BRIGHT);
2720 }
2721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002723 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002725
Dianne Hackborn617f8772009-03-31 15:04:46 -07002726 long identity = Binder.clearCallingIdentity();
2727 try {
2728 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2729 mBatteryStats.noteScreenOn();
2730 } catch (RemoteException e) {
2731 // Nothing interesting to do.
2732 } finally {
2733 Binder.restoreCallingIdentity(identity);
2734 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002735 }
2736 }
2737
2738 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002739 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002740 synchronized (mLocks) {
2741 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2743 updateWakeLockLocked();
2744 mLocks.notifyAll();
2745 }
2746 }
2747
2748 public void monitor() {
2749 synchronized (mLocks) { }
2750 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002751
2752 public int getSupportedWakeLockFlags() {
2753 int result = PowerManager.PARTIAL_WAKE_LOCK
2754 | PowerManager.FULL_WAKE_LOCK
2755 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2756
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002757 if (mProximitySensor != null) {
2758 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2759 }
2760
2761 return result;
2762 }
2763
Mike Lockwood237a2992009-09-15 14:42:16 -04002764 public void setBacklightBrightness(int brightness) {
2765 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2766 // Don't let applications turn the screen all the way off
2767 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002768 mLcdLight.setBrightness(brightness);
2769 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2770 mButtonLight.setBrightness(brightness);
Mike Lockwood237a2992009-09-15 14:42:16 -04002771 long identity = Binder.clearCallingIdentity();
2772 try {
2773 mBatteryStats.noteScreenBrightness(brightness);
2774 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
Mike Lockwood237a2992009-09-15 14:42:16 -04002776 } finally {
2777 Binder.restoreCallingIdentity(identity);
2778 }
2779
2780 // update our animation state
2781 if (ANIMATE_SCREEN_LIGHTS) {
2782 mScreenBrightness.curValue = brightness;
2783 mScreenBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002784 mScreenBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002785 }
2786 if (ANIMATE_KEYBOARD_LIGHTS) {
2787 mKeyboardBrightness.curValue = brightness;
2788 mKeyboardBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002789 mKeyboardBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002790 }
2791 if (ANIMATE_BUTTON_LIGHTS) {
2792 mButtonBrightness.curValue = brightness;
2793 mButtonBrightness.animating = false;
Mike Lockwooddd9668e2009-10-27 15:47:02 -04002794 mButtonBrightness.targetValue = -1;
Mike Lockwood237a2992009-09-15 14:42:16 -04002795 }
2796 }
2797
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002798 public void setAttentionLight(boolean on, int color) {
2799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002800 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002801 }
2802
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002803 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002804 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002805 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002806 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002807 if (!mProximitySensorEnabled) {
2808 // clear calling identity so sensor manager battery stats are accurate
2809 long identity = Binder.clearCallingIdentity();
2810 try {
2811 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2812 SensorManager.SENSOR_DELAY_NORMAL);
2813 mProximitySensorEnabled = true;
2814 } finally {
2815 Binder.restoreCallingIdentity(identity);
2816 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002817 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002818 }
2819
2820 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002821 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002822 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002823 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002824 if (mProximitySensorEnabled) {
2825 // clear calling identity so sensor manager battery stats are accurate
2826 long identity = Binder.clearCallingIdentity();
2827 try {
2828 mSensorManager.unregisterListener(mProximityListener);
2829 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002830 if (mProximityPartialLock.isHeld()) {
2831 mProximityPartialLock.release();
2832 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002833 mProximitySensorEnabled = false;
2834 } finally {
2835 Binder.restoreCallingIdentity(identity);
2836 }
2837 if (mProximitySensorActive) {
2838 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002839 if (mDebugProximitySensor) {
2840 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2841 + mProxIgnoredBecauseScreenTurnedOff);
2842 }
2843 if (!mProxIgnoredBecauseScreenTurnedOff) {
2844 forceUserActivityLocked();
2845 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002846 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002847 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002848 }
2849
Mike Lockwood20f87d72009-11-05 16:08:51 -05002850 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002851 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002852 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002853 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002854 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002855 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002856 return;
2857 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002858 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002859 if (mDebugProximitySensor) {
2860 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2861 + mProxIgnoredBecauseScreenTurnedOff);
2862 }
2863 if (!mProxIgnoredBecauseScreenTurnedOff) {
2864 goToSleepLocked(SystemClock.uptimeMillis(),
2865 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2866 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002867 mProximitySensorActive = true;
2868 } else {
2869 // proximity sensor negative events trigger as user activity.
2870 // temporarily set mUserActivityAllowed to true so this will work
2871 // even when the keyguard is on.
2872 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002873 if (mDebugProximitySensor) {
2874 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2875 + mProxIgnoredBecauseScreenTurnedOff);
2876 }
2877 if (!mProxIgnoredBecauseScreenTurnedOff) {
2878 forceUserActivityLocked();
2879 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002880
2881 if (mProximityWakeLockCount == 0) {
2882 // disable sensor if we have no listeners left after proximity negative
2883 disableProximityLockLocked();
2884 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002885 }
2886 }
2887
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002888 private void enableLightSensor(boolean enable) {
2889 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002890 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002891 }
2892 if (mSensorManager != null && mLightSensorEnabled != enable) {
2893 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002894 // clear calling identity so sensor manager battery stats are accurate
2895 long identity = Binder.clearCallingIdentity();
2896 try {
2897 if (enable) {
2898 mSensorManager.registerListener(mLightListener, mLightSensor,
2899 SensorManager.SENSOR_DELAY_NORMAL);
2900 } else {
2901 mSensorManager.unregisterListener(mLightListener);
2902 mHandler.removeCallbacks(mAutoBrightnessTask);
2903 }
2904 } finally {
2905 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002906 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002907 }
2908 }
2909
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002910 SensorEventListener mProximityListener = new SensorEventListener() {
2911 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002912 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002913 synchronized (mLocks) {
2914 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002915 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2916 mLastProximityEventTime = milliseconds;
2917 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002918 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002919
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002920 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002921 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2922 distance < mProximitySensor.getMaximumRange());
2923
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002924 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002925 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002926 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002927 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2928 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2929 mProximityPendingValue = (active ? 1 : 0);
2930 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002931 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002932 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002933 // process the value immediately
2934 mProximityPendingValue = -1;
2935 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002936 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002937
2938 // update mProximityPartialLock state
2939 boolean held = mProximityPartialLock.isHeld();
2940 if (!held && proximityTaskQueued) {
2941 // hold wakelock until mProximityTask runs
2942 mProximityPartialLock.acquire();
2943 } else if (held && !proximityTaskQueued) {
2944 mProximityPartialLock.release();
2945 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002946 }
2947 }
2948
2949 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2950 // ignore
2951 }
2952 };
2953
2954 SensorEventListener mLightListener = new SensorEventListener() {
2955 public void onSensorChanged(SensorEvent event) {
2956 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002957 // ignore light sensor while screen is turning off
2958 if (isScreenTurningOffLocked()) {
2959 return;
2960 }
2961
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002962 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002963 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002964 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002965 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002966 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002967 mHandler.removeCallbacks(mAutoBrightnessTask);
2968 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002969 if (mLightSensorValue == -1 ||
2970 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2971 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002972 lightSensorChangedLocked(value);
2973 } else {
2974 // delay processing to debounce the sensor
2975 mLightSensorPendingValue = value;
2976 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2977 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002978 } else {
2979 mLightSensorPendingValue = -1;
2980 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002981 }
2982 }
2983
2984 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2985 // ignore
2986 }
2987 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988}