blob: f53ce2d9806a461459a0090eacabf216984a9c71 [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
Joe Onoratob08a1af2010-10-11 19:28:58 -0700144 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400147 // Slower animation for autobrightness changes
148 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 // These magic numbers are the initial state of the LEDs at boot. Ideally
151 // we should read them from the driver, but our current hardware returns 0
152 // for the initial value. Oops!
153 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
154 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
155 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700158 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
160 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500161 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500163 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
164 private final int[] mBroadcastWhy = new int[3];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mPartialCount = 0;
166 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500167 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
168 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
169 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 private int mUserState;
171 private boolean mKeyboardVisible = false;
172 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500173 private int mProximityWakeLockCount = 0;
174 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700175 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500176 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
177 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800178 private int mScreenOffTimeoutSetting;
179 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private int mKeylightDelay;
181 private int mDimDelay;
182 private int mScreenOffDelay;
183 private int mWakeLockState;
184 private long mLastEventTime = 0;
185 private long mScreenOffTime;
186 private volatile WindowManagerPolicy mPolicy;
187 private final LockList mLocks = new LockList();
188 private Intent mScreenOffIntent;
189 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500190 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500192 private LightsService.Light mLcdLight;
193 private LightsService.Light mButtonLight;
194 private LightsService.Light mKeyboardLight;
195 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private UnsynchronizedWakeLock mBroadcastWakeLock;
197 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
198 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
199 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500200 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700202 private HandlerThread mScreenOffThread;
203 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500205 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700207 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700208 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private boolean mIsPowered = false;
210 private IActivityManager mActivityService;
211 private IBatteryStats mBatteryStats;
212 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700213 private SensorManager mSensorManager;
214 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400215 private Sensor mLightSensor;
216 private boolean mLightSensorEnabled;
217 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400218 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500219 private int mHighestLightSensorValue = -1;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700220 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500221 private int mLightSensorScreenBrightness = -1;
222 private int mLightSensorButtonBrightness = -1;
223 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500225 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private long mNextTimeout;
227 private volatile int mPokey = 0;
228 private volatile boolean mPokeAwakeOnSet = false;
229 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500230 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500231 // mLastScreenOnTime is the time the screen was last turned on
232 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private boolean mPreventScreenOn;
234 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500235 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400236 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700237 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700238 private int[] mAutoBrightnessLevels;
239 private int[] mLcdBacklightValues;
240 private int[] mButtonBacklightValues;
241 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500242 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700243 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700244 private int mWarningSpewThrottleCount;
245 private long mWarningSpewThrottleTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
247 // Used when logging number and duration of touch-down cycles
248 private long mTotalTouchDownTime;
249 private long mLastTouchDown;
250 private int mTouchCycles;
251
252 // could be either static or controllable at runtime
253 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400254 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400255 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700256
257 private native void nativeInit();
258 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onoratob08a1af2010-10-11 19:28:58 -0700259 private native void nativeStartSurfaceFlingerAnimation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260
261 /*
262 static PrintStream mLog;
263 static {
264 try {
265 mLog = new PrintStream("/data/power.log");
266 }
267 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800268 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270 }
271 static class Log {
272 static void d(String tag, String s) {
273 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800274 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276 static void i(String tag, String s) {
277 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800278 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280 static void w(String tag, String s) {
281 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800282 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284 static void e(String tag, String s) {
285 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800286 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 }
289 */
290
291 /**
292 * This class works around a deadlock between the lock in PowerManager.WakeLock
293 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
294 * mToken object so it can be accessed from any thread, but it calls into here
295 * with its lock held. This class is essentially a reimplementation of
296 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
297 * only call it with our own locks held.
298 */
299 private class UnsynchronizedWakeLock {
300 int mFlags;
301 String mTag;
302 IBinder mToken;
303 int mCount = 0;
304 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500305 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306
307 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
308 mFlags = flags;
309 mTag = tag;
310 mToken = new Binder();
311 mRefCounted = refCounted;
312 }
313
314 public void acquire() {
315 if (!mRefCounted || mCount++ == 0) {
316 long ident = Binder.clearCallingIdentity();
317 try {
318 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700319 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 } finally {
322 Binder.restoreCallingIdentity(ident);
323 }
324 }
325 }
326
327 public void release() {
328 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500329 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500330 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 }
332 if (mCount < 0) {
333 throw new RuntimeException("WakeLock under-locked " + mTag);
334 }
335 }
336
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500337 public boolean isHeld()
338 {
339 return mHeld;
340 }
341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 public String toString() {
343 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500344 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346 }
347
348 private final class BatteryReceiver extends BroadcastReceiver {
349 @Override
350 public void onReceive(Context context, Intent intent) {
351 synchronized (mLocks) {
352 boolean wasPowered = mIsPowered;
353 mIsPowered = mBatteryService.isPowered();
354
355 if (mIsPowered != wasPowered) {
356 // update mStayOnWhilePluggedIn wake lock
357 updateWakeLockLocked();
358
359 // treat plugging and unplugging the devices as a user activity.
360 // users find it disconcerting when they unplug the device
361 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500362 // to avoid turning on the screen when unplugging, we only trigger
363 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 // temporarily set mUserActivityAllowed to true so this will work
365 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700366 // However, you can also set config_unplugTurnsOnScreen to have it
367 // turn on. Some devices want this because they don't have a
368 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700370 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
371 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500372 forceUserActivityLocked();
373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 }
375 }
376 }
377 }
378 }
379
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500380 private final class BootCompletedReceiver extends BroadcastReceiver {
381 @Override
382 public void onReceive(Context context, Intent intent) {
383 bootCompleted();
384 }
385 }
386
Mike Lockwoodb2865412010-02-02 22:40:33 -0500387 private final class DockReceiver extends BroadcastReceiver {
388 @Override
389 public void onReceive(Context context, Intent intent) {
390 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
391 Intent.EXTRA_DOCK_STATE_UNDOCKED);
392 dockStateChanged(state);
393 }
394 }
395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 /**
397 * Set the setting that determines whether the device stays on when plugged in.
398 * The argument is a bit string, with each bit specifying a power source that,
399 * when the device is connected to that source, causes the device to stay on.
400 * See {@link android.os.BatteryManager} for the list of power sources that
401 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
402 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
403 * @param val an {@code int} containing the bits that specify which power sources
404 * should cause the device to stay on.
405 */
406 public void setStayOnSetting(int val) {
407 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
408 Settings.System.putInt(mContext.getContentResolver(),
409 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
410 }
411
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800412 public void setMaximumScreenOffTimeount(int timeMs) {
413 mContext.enforceCallingOrSelfPermission(
414 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
415 synchronized (mLocks) {
416 mMaximumScreenOffTimeout = timeMs;
417 // recalculate everything
418 setScreenOffTimeoutsLocked();
419 }
420 }
421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700423 private int getInt(String name, int defValue) {
424 ContentValues values = mSettings.getValues(name);
425 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
426 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
428
429 public void update(Observable o, Object arg) {
430 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700431 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
432 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
433 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 updateWakeLockLocked();
435
Amith Yamasani8b619832010-09-22 16:11:59 -0700436 // SCREEN_OFF_TIMEOUT, default to 15 seconds
437 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438
439 // DIM_SCREEN
440 //mDimScreen = getInt(DIM_SCREEN) != 0;
441
Amith Yamasani8b619832010-09-22 16:11:59 -0700442 // SCREEN_BRIGHTNESS_MODE, default to manual
443 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
444 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 // recalculate everything
447 setScreenOffTimeoutsLocked();
448 }
449 }
450 }
451
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700452 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 // Hack to get our uid... should have a func for this.
454 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700455 MY_UID = Process.myUid();
456 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 Binder.restoreCallingIdentity(token);
458
459 // XXX remove this when the kernel doesn't timeout wake locks
460 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
461
462 // assume nothing is on yet
463 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 // Add ourself to the Watchdog monitors.
466 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 }
468
469 private ContentQueryMap mSettings;
470
Mike Lockwood3a322132009-11-24 00:30:52 -0500471 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700472 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500473 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 mContext = context;
475 mActivityService = activity;
476 mBatteryStats = BatteryStatsService.getService();
477 mBatteryService = battery;
478
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500479 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
480 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
481 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
482 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
483
Joe Onoratob08a1af2010-10-11 19:28:58 -0700484 nativeInit();
485 synchronized (mLocks) {
486 updateNativePowerStateLocked();
487 }
488
489 mInitComplete = false;
490 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
491 @Override
492 protected void onLooperPrepared() {
493 mScreenOffHandler = new Handler();
494 synchronized (mScreenOffThread) {
495 mInitComplete = true;
496 mScreenOffThread.notifyAll();
497 }
498 }
499 };
500 mScreenOffThread.start();
501
502 synchronized (mScreenOffThread) {
503 while (!mInitComplete) {
504 try {
505 mScreenOffThread.wait();
506 } catch (InterruptedException e) {
507 // Ignore
508 }
509 }
510 }
511
512 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 mHandlerThread = new HandlerThread("PowerManagerService") {
514 @Override
515 protected void onLooperPrepared() {
516 super.onLooperPrepared();
517 initInThread();
518 }
519 };
520 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 synchronized (mHandlerThread) {
523 while (!mInitComplete) {
524 try {
525 mHandlerThread.wait();
526 } catch (InterruptedException e) {
527 // Ignore
528 }
529 }
530 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700531
532 nativeInit();
533 synchronized (mLocks) {
534 updateNativePowerStateLocked();
535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 void initInThread() {
539 mHandler = new Handler();
540
541 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700542 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
544 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
545 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
546 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
547 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
548 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500549 mProximityPartialLock = new UnsynchronizedWakeLock(
550 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551
552 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
553 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
554 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
555 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
556
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700557 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400558
Joe Onoratob08a1af2010-10-11 19:28:58 -0700559 mAnimateScreenLights = resources.getBoolean(
560 com.android.internal.R.bool.config_animateScreenLights);
561
Joe Onorato6d747652010-10-11 15:15:31 -0700562 mUnplugTurnsOnScreen = resources.getBoolean(
563 com.android.internal.R.bool.config_unplugTurnsOnScreen);
564
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400565 // read settings for auto-brightness
566 mUseSoftwareAutoBrightness = resources.getBoolean(
567 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400568 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700569 mAutoBrightnessLevels = resources.getIntArray(
570 com.android.internal.R.array.config_autoBrightnessLevels);
571 mLcdBacklightValues = resources.getIntArray(
572 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
573 mButtonBacklightValues = resources.getIntArray(
574 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
575 mKeyboardBacklightValues = resources.getIntArray(
576 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500577 mLightSensorWarmupTime = resources.getInteger(
578 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700579 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700580
581 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
583 "(" + Settings.System.NAME + "=?) or ("
584 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700585 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700587 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
588 SCREEN_BRIGHTNESS_MODE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 null);
590 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
591 SettingsObserver settingsObserver = new SettingsObserver();
592 mSettings.addObserver(settingsObserver);
593
594 // pretend that the settings changed so we will get their initial state
595 settingsObserver.update(mSettings, null);
596
597 // register for the battery changed notifications
598 IntentFilter filter = new IntentFilter();
599 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
600 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500601 filter = new IntentFilter();
602 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
603 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500604 filter = new IntentFilter();
605 filter.addAction(Intent.ACTION_DOCK_EVENT);
606 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
Doug Zongker43866e02010-01-07 12:09:54 -0800608 // Listen for secure settings changes
609 mContext.getContentResolver().registerContentObserver(
610 Settings.Secure.CONTENT_URI, true,
611 new ContentObserver(new Handler()) {
612 public void onChange(boolean selfChange) {
613 updateSettingsValues();
614 }
615 });
616 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 synchronized (mHandlerThread) {
619 mInitComplete = true;
620 mHandlerThread.notifyAll();
621 }
622 }
623
624 private class WakeLock implements IBinder.DeathRecipient
625 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700626 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 super();
628 flags = f;
629 binder = b;
630 tag = t;
631 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700632 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 if (u != MY_UID || (
634 !"KEEP_SCREEN_ON_FLAG".equals(tag)
635 && !"KeyInputQueue".equals(tag))) {
636 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
637 ? BatteryStats.WAKE_TYPE_PARTIAL
638 : BatteryStats.WAKE_TYPE_FULL;
639 } else {
640 monitorType = -1;
641 }
642 try {
643 b.linkToDeath(this, 0);
644 } catch (RemoteException e) {
645 binderDied();
646 }
647 }
648 public void binderDied() {
649 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500650 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 }
652 }
653 final int flags;
654 final IBinder binder;
655 final String tag;
656 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400657 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700659 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 boolean activated = true;
661 int minState;
662 }
663
664 private void updateWakeLockLocked() {
665 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
666 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
667 mStayOnWhilePluggedInScreenDimLock.acquire();
668 mStayOnWhilePluggedInPartialLock.acquire();
669 } else {
670 mStayOnWhilePluggedInScreenDimLock.release();
671 mStayOnWhilePluggedInPartialLock.release();
672 }
673 }
674
675 private boolean isScreenLock(int flags)
676 {
677 int n = flags & LOCK_MASK;
678 return n == PowerManager.FULL_WAKE_LOCK
679 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400680 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
681 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 }
683
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700684 void enforceWakeSourcePermission(int uid, int pid) {
685 if (uid == Process.myUid()) {
686 return;
687 }
688 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
689 pid, uid, null);
690 }
691
692 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700695 if (uid != Process.myUid()) {
696 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
697 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700698 if (ws != null) {
699 enforceWakeSourcePermission(uid, pid);
700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 long ident = Binder.clearCallingIdentity();
702 try {
703 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700704 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706 } finally {
707 Binder.restoreCallingIdentity(ident);
708 }
709 }
710
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700711 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700712 if (wl.monitorType >= 0) {
713 long origId = Binder.clearCallingIdentity();
714 try {
715 if (ws != null) {
716 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
717 wl.monitorType);
718 } else {
719 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
720 }
721 } catch (RemoteException e) {
722 // Ignore
723 } finally {
724 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700725 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700726 }
727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700729 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700730 if (wl.monitorType >= 0) {
731 long origId = Binder.clearCallingIdentity();
732 try {
733 if (ws != null) {
734 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
735 wl.monitorType);
736 } else {
737 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
738 }
739 } catch (RemoteException e) {
740 // Ignore
741 } finally {
742 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700743 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700744 }
745 }
746
747 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
748 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800750 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 }
752
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700753 if (ws != null && ws.size() == 0) {
754 ws = null;
755 }
756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 int index = mLocks.getIndex(lock);
758 WakeLock wl;
759 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700760 boolean diffsource;
761 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700763 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 switch (wl.flags & LOCK_MASK)
765 {
766 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500767 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400768 wl.minState = SCREEN_BRIGHT;
769 } else {
770 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 break;
773 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
774 wl.minState = SCREEN_BRIGHT;
775 break;
776 case PowerManager.SCREEN_DIM_WAKE_LOCK:
777 wl.minState = SCREEN_DIM;
778 break;
779 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700780 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 break;
782 default:
783 // just log and bail. we're in the server, so don't
784 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800785 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 + " flags=" + flags);
787 return;
788 }
789 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 if (ws != null) {
791 wl.ws = new WorkSource(ws);
792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700794 diffsource = false;
795 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 } else {
797 wl = mLocks.get(index);
798 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700799 oldsource = wl.ws;
800 if (oldsource != null) {
801 if (ws == null) {
802 wl.ws = null;
803 diffsource = true;
804 } else {
805 diffsource = oldsource.diff(ws);
806 }
807 } else if (ws != null) {
808 diffsource = true;
809 } else {
810 diffsource = false;
811 }
812 if (diffsource) {
813 wl.ws = new WorkSource(ws);
814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816 if (isScreenLock(flags)) {
817 // if this causes a wakeup, we reactivate all of the locks and
818 // set it to whatever they want. otherwise, we modulate that
819 // by the current state so we never turn it more on than
820 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400821 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
822 mProximityWakeLockCount++;
823 if (mProximityWakeLockCount == 1) {
824 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400827 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
828 int oldWakeLockState = mWakeLockState;
829 mWakeLockState = mLocks.reactivateScreenLocksLocked();
830 if (mSpew) {
831 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
832 + " mWakeLockState=0x"
833 + Integer.toHexString(mWakeLockState)
834 + " previous wakeLockState=0x"
835 + Integer.toHexString(oldWakeLockState));
836 }
837 } else {
838 if (mSpew) {
839 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
840 + " mLocks.gatherState()=0x"
841 + Integer.toHexString(mLocks.gatherState())
842 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
843 }
844 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400846 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
850 if (newlock) {
851 mPartialCount++;
852 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800853 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
855 }
856 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700859 if (diffsource) {
860 // If the lock sources have changed, need to first release the
861 // old ones.
862 noteStopWakeLocked(wl, oldsource);
863 }
864 if (newlock || diffsource) {
865 noteStartWakeLocked(wl, ws);
866 }
867 }
868
869 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
870 int uid = Binder.getCallingUid();
871 int pid = Binder.getCallingPid();
872 if (ws != null && ws.size() == 0) {
873 ws = null;
874 }
875 if (ws != null) {
876 enforceWakeSourcePermission(uid, pid);
877 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700878 synchronized (mLocks) {
879 int index = mLocks.getIndex(lock);
880 if (index < 0) {
881 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700883 WakeLock wl = mLocks.get(index);
884 WorkSource oldsource = wl.ws;
885 wl.ws = ws != null ? new WorkSource(ws) : null;
886 noteStopWakeLocked(wl, oldsource);
887 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 }
890
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500891 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700892 int uid = Binder.getCallingUid();
893 if (uid != Process.myUid()) {
894 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896
897 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500898 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900 }
901
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500902 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 WakeLock wl = mLocks.removeLock(lock);
904 if (wl == null) {
905 return;
906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800909 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
911 }
912
913 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400914 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
915 mProximityWakeLockCount--;
916 if (mProximityWakeLockCount == 0) {
917 if (mProximitySensorActive &&
918 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
919 // wait for proximity sensor to go negative before disabling sensor
920 if (mDebugProximitySensor) {
921 Slog.d(TAG, "waiting for proximity sensor to go negative");
922 }
923 } else {
924 disableProximityLockLocked();
925 }
926 }
927 } else {
928 mWakeLockState = mLocks.gatherState();
929 // goes in the middle to reduce flicker
930 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
931 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
932 }
933 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
937 mPartialCount--;
938 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800939 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 Power.releaseWakeLock(PARTIAL_NAME);
941 }
942 }
943 // Unlink the lock from the binder.
944 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945
Dianne Hackborn70be1672010-09-14 11:13:03 -0700946 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 private class PokeLock implements IBinder.DeathRecipient
950 {
951 PokeLock(int p, IBinder b, String t) {
952 super();
953 this.pokey = p;
954 this.binder = b;
955 this.tag = t;
956 try {
957 b.linkToDeath(this, 0);
958 } catch (RemoteException e) {
959 binderDied();
960 }
961 }
962 public void binderDied() {
963 setPokeLock(0, this.binder, this.tag);
964 }
965 int pokey;
966 IBinder binder;
967 String tag;
968 boolean awakeOnSet;
969 }
970
971 public void setPokeLock(int pokey, IBinder token, String tag) {
972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
973 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800974 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 return;
976 }
977
978 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
979 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
980 + " and POKE_LOCK_MEDIUM_TIMEOUT");
981 }
982
983 synchronized (mLocks) {
984 if (pokey != 0) {
985 PokeLock p = mPokeLocks.get(token);
986 int oldPokey = 0;
987 if (p != null) {
988 oldPokey = p.pokey;
989 p.pokey = pokey;
990 } else {
991 p = new PokeLock(pokey, token, tag);
992 mPokeLocks.put(token, p);
993 }
994 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
995 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
996 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
997 p.awakeOnSet = true;
998 }
999 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001000 PokeLock rLock = mPokeLocks.remove(token);
1001 if (rLock != null) {
1002 token.unlinkToDeath(rLock, 0);
1003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
1005
1006 int oldPokey = mPokey;
1007 int cumulative = 0;
1008 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1009 boolean awakeOnSet = false;
1010 for (PokeLock p: mPokeLocks.values()) {
1011 cumulative |= p.pokey;
1012 if (p.awakeOnSet) {
1013 awakeOnSet = true;
1014 }
1015 }
1016 mPokey = cumulative;
1017 mPokeAwakeOnSet = awakeOnSet;
1018
1019 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1020 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 if (oldCumulativeTimeout != newCumulativeTimeout) {
1023 setScreenOffTimeoutsLocked();
1024 // reset the countdown timer, but use the existing nextState so it doesn't
1025 // change anything
1026 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1027 }
1028 }
1029 }
1030
1031 private static String lockType(int type)
1032 {
1033 switch (type)
1034 {
1035 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001036 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001038 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001040 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001042 return "PARTIAL_WAKE_LOCK ";
1043 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1044 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 default:
David Brown251faa62009-08-02 22:04:36 -07001046 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048 }
1049
1050 private static String dumpPowerState(int state) {
1051 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1052 ? "KEYBOARD_BRIGHT_BIT " : "")
1053 + (((state & SCREEN_BRIGHT_BIT) != 0)
1054 ? "SCREEN_BRIGHT_BIT " : "")
1055 + (((state & SCREEN_ON_BIT) != 0)
1056 ? "SCREEN_ON_BIT " : "")
1057 + (((state & BATTERY_LOW_BIT) != 0)
1058 ? "BATTERY_LOW_BIT " : "");
1059 }
1060
1061 @Override
1062 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1063 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1064 != PackageManager.PERMISSION_GRANTED) {
1065 pw.println("Permission Denial: can't dump PowerManager from from pid="
1066 + Binder.getCallingPid()
1067 + ", uid=" + Binder.getCallingUid());
1068 return;
1069 }
1070
1071 long now = SystemClock.uptimeMillis();
1072
Mike Lockwoodca44df82010-02-25 13:48:49 -05001073 synchronized (mLocks) {
1074 pw.println("Power Manager State:");
1075 pw.println(" mIsPowered=" + mIsPowered
1076 + " mPowerState=" + mPowerState
1077 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1078 + " ms");
1079 pw.println(" mPartialCount=" + mPartialCount);
1080 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1081 pw.println(" mUserState=" + dumpPowerState(mUserState));
1082 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1083 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1084 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1085 + " " + ((mNextTimeout-now)/1000) + "s from now");
1086 pw.println(" mDimScreen=" + mDimScreen
1087 + " mStayOnConditions=" + mStayOnConditions);
1088 pw.println(" mScreenOffReason=" + mScreenOffReason
1089 + " mUserState=" + mUserState);
1090 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1091 + ',' + mBroadcastQueue[2] + "}");
1092 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1093 + ',' + mBroadcastWhy[2] + "}");
1094 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1095 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1096 + " mUserActivityAllowed=" + mUserActivityAllowed);
1097 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1098 + " mScreenOffDelay=" + mScreenOffDelay);
1099 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1100 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1101 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1102 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1103 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1104 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1105 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1106 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1107 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1108 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1109 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1110 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1111 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1112 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1113 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1114 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1115 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1116 pw.println(" mLightSensorValue=" + mLightSensorValue
1117 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
1118 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1119 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1120 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1121 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1122 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1123 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001124
Mike Lockwoodca44df82010-02-25 13:48:49 -05001125 int N = mLocks.size();
1126 pw.println();
1127 pw.println("mLocks.size=" + N + ":");
1128 for (int i=0; i<N; i++) {
1129 WakeLock wl = mLocks.get(i);
1130 String type = lockType(wl.flags & LOCK_MASK);
1131 String acquireCausesWakeup = "";
1132 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1133 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1134 }
1135 String activated = "";
1136 if (wl.activated) {
1137 activated = " activated";
1138 }
1139 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001140 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1141 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001143
1144 pw.println();
1145 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1146 for (PokeLock p: mPokeLocks.values()) {
1147 pw.println(" poke lock '" + p.tag + "':"
1148 + ((p.pokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0
1149 ? " POKE_LOCK_IGNORE_CHEEK_EVENTS" : "")
1150 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0
1151 ? " POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS" : "")
1152 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1153 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1154 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1155 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001157
Mike Lockwoodca44df82010-02-25 13:48:49 -05001158 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
Joe Onorato7999bff2010-07-24 11:50:05 -04001162 private void setTimeoutLocked(long now, int nextState) {
1163 setTimeoutLocked(now, -1, nextState);
1164 }
1165
1166 // If they gave a timeoutOverride it is the number of seconds
1167 // to screen-off. Figure out where in the countdown cycle we
1168 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001169 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1170 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001171 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001172 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001173 long when = 0;
1174 if (timeoutOverride <= 0) {
1175 switch (nextState)
1176 {
1177 case SCREEN_BRIGHT:
1178 when = now + mKeylightDelay;
1179 break;
1180 case SCREEN_DIM:
1181 if (mDimDelay >= 0) {
1182 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001183 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001184 } else {
1185 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1186 }
1187 case SCREEN_OFF:
1188 synchronized (mLocks) {
1189 when = now + mScreenOffDelay;
1190 }
1191 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001192 default:
1193 when = now;
1194 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001196 } else {
1197 override: {
1198 if (timeoutOverride <= mScreenOffDelay) {
1199 when = now + timeoutOverride;
1200 nextState = SCREEN_OFF;
1201 break override;
1202 }
1203 timeoutOverride -= mScreenOffDelay;
1204
1205 if (mDimDelay >= 0) {
1206 if (timeoutOverride <= mDimDelay) {
1207 when = now + timeoutOverride;
1208 nextState = SCREEN_DIM;
1209 break override;
1210 }
1211 timeoutOverride -= mDimDelay;
1212 }
1213
1214 when = now + timeoutOverride;
1215 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001217 }
1218 if (mSpew) {
1219 Slog.d(TAG, "setTimeoutLocked now=" + now
1220 + " timeoutOverride=" + timeoutOverride
1221 + " nextState=" + nextState + " when=" + when);
1222 }
Joe Onorato797e6882010-08-26 14:46:01 -04001223
1224 mHandler.removeCallbacks(mTimeoutTask);
1225 mTimeoutTask.nextState = nextState;
1226 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1227 ? (originalTimeoutOverride - timeoutOverride)
1228 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001229 mHandler.postAtTime(mTimeoutTask, when);
1230 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 private void cancelTimerLocked()
1236 {
1237 mHandler.removeCallbacks(mTimeoutTask);
1238 mTimeoutTask.nextState = -1;
1239 }
1240
1241 private class TimeoutTask implements Runnable
1242 {
1243 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001244 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 public void run()
1246 {
1247 synchronized (mLocks) {
1248 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001249 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
1251
1252 if (nextState == -1) {
1253 return;
1254 }
1255
1256 mUserState = this.nextState;
1257 setPowerState(this.nextState | mWakeLockState);
1258
1259 long now = SystemClock.uptimeMillis();
1260
1261 switch (this.nextState)
1262 {
1263 case SCREEN_BRIGHT:
1264 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001265 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 break;
1267 }
1268 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001269 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 break;
1271 }
1272 }
1273 }
1274 }
1275
1276 private void sendNotificationLocked(boolean on, int why)
1277 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001278 if (!on) {
1279 mStillNeedSleepNotification = false;
1280 }
1281
Joe Onorato128e7292009-03-24 18:41:31 -07001282 // Add to the queue.
1283 int index = 0;
1284 while (mBroadcastQueue[index] != -1) {
1285 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
Joe Onorato128e7292009-03-24 18:41:31 -07001287 mBroadcastQueue[index] = on ? 1 : 0;
1288 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289
Joe Onorato128e7292009-03-24 18:41:31 -07001290 // If we added it position 2, then there is a pair that can be stripped.
1291 // If we added it position 1 and we're turning the screen off, we can strip
1292 // the pair and do nothing, because the screen is already off, and therefore
1293 // keyguard has already been enabled.
1294 // However, if we added it at position 1 and we're turning it on, then position
1295 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1296 // on, so have to run the queue then.
1297 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001298 // While we're collapsing them, if it's going off, and the new reason
1299 // is more significant than the first, then use the new one.
1300 if (!on && mBroadcastWhy[0] > why) {
1301 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001302 }
1303 mBroadcastQueue[0] = on ? 1 : 0;
1304 mBroadcastQueue[1] = -1;
1305 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001306 mBroadcastWakeLock.release();
1307 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001308 index = 0;
1309 }
1310 if (index == 1 && !on) {
1311 mBroadcastQueue[0] = -1;
1312 mBroadcastQueue[1] = -1;
1313 index = -1;
1314 // The wake lock was being held, but we're not actually going to do any
1315 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001316 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001318 }
1319
1320 // Now send the message.
1321 if (index >= 0) {
1322 // Acquire the broadcast wake lock before changing the power
1323 // state. It will be release after the broadcast is sent.
1324 // We always increment the ref count for each notification in the queue
1325 // and always decrement when that notification is handled.
1326 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001327 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001328 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 }
1331
1332 private Runnable mNotificationTask = new Runnable()
1333 {
1334 public void run()
1335 {
Joe Onorato128e7292009-03-24 18:41:31 -07001336 while (true) {
1337 int value;
1338 int why;
1339 WindowManagerPolicy policy;
1340 synchronized (mLocks) {
1341 value = mBroadcastQueue[0];
1342 why = mBroadcastWhy[0];
1343 for (int i=0; i<2; i++) {
1344 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1345 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1346 }
1347 policy = getPolicyLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
Joe Onorato128e7292009-03-24 18:41:31 -07001349 if (value == 1) {
1350 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001351
Joe Onorato128e7292009-03-24 18:41:31 -07001352 policy.screenTurnedOn();
1353 try {
1354 ActivityManagerNative.getDefault().wakingUp();
1355 } catch (RemoteException e) {
1356 // ignore it
1357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
Joe Onorato128e7292009-03-24 18:41:31 -07001359 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001360 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001361 }
1362 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1363 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1364 mScreenOnBroadcastDone, mHandler, 0, null, null);
1365 } else {
1366 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001367 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001368 mBroadcastWakeLock.mCount);
1369 mBroadcastWakeLock.release();
1370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 }
1372 }
Joe Onorato128e7292009-03-24 18:41:31 -07001373 else if (value == 0) {
1374 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001375
Joe Onorato128e7292009-03-24 18:41:31 -07001376 policy.screenTurnedOff(why);
1377 try {
1378 ActivityManagerNative.getDefault().goingToSleep();
1379 } catch (RemoteException e) {
1380 // ignore it.
1381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382
Joe Onorato128e7292009-03-24 18:41:31 -07001383 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1384 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1385 mScreenOffBroadcastDone, mHandler, 0, null, null);
1386 } else {
1387 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001388 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001389 mBroadcastWakeLock.mCount);
1390 mBroadcastWakeLock.release();
1391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393 }
Joe Onorato128e7292009-03-24 18:41:31 -07001394 else {
1395 // If we're in this case, then this handler is running for a previous
1396 // paired transaction. mBroadcastWakeLock will already have been released.
1397 break;
1398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400 }
1401 };
1402
1403 long mScreenOnStart;
1404 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1405 public void onReceive(Context context, Intent intent) {
1406 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1409 mBroadcastWakeLock.release();
1410 }
1411 }
1412 };
1413
1414 long mScreenOffStart;
1415 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1416 public void onReceive(Context context, Intent intent) {
1417 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001418 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1420 mBroadcastWakeLock.release();
1421 }
1422 }
1423 };
1424
1425 void logPointerUpEvent() {
1426 if (LOG_TOUCH_DOWNS) {
1427 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1428 mLastTouchDown = 0;
1429 }
1430 }
1431
1432 void logPointerDownEvent() {
1433 if (LOG_TOUCH_DOWNS) {
1434 // If we are not already timing a down/up sequence
1435 if (mLastTouchDown == 0) {
1436 mLastTouchDown = SystemClock.elapsedRealtime();
1437 mTouchCycles++;
1438 }
1439 }
1440 }
1441
1442 /**
1443 * Prevents the screen from turning on even if it *should* turn on due
1444 * to a subsequent full wake lock being acquired.
1445 * <p>
1446 * This is a temporary hack that allows an activity to "cover up" any
1447 * display glitches that happen during the activity's startup
1448 * sequence. (Specifically, this API was added to work around a
1449 * cosmetic bug in the "incoming call" sequence, where the lock screen
1450 * would flicker briefly before the incoming call UI became visible.)
1451 * TODO: There ought to be a more elegant way of doing this,
1452 * probably by having the PowerManager and ActivityManager
1453 * work together to let apps specify that the screen on/off
1454 * state should be synchronized with the Activity lifecycle.
1455 * <p>
1456 * Note that calling preventScreenOn(true) will NOT turn the screen
1457 * off if it's currently on. (This API only affects *future*
1458 * acquisitions of full wake locks.)
1459 * But calling preventScreenOn(false) WILL turn the screen on if
1460 * it's currently off because of a prior preventScreenOn(true) call.
1461 * <p>
1462 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1463 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1464 * call doesn't occur within 5 seconds, we'll turn the screen back on
1465 * ourselves (and log a warning about it); this prevents a buggy app
1466 * from disabling the screen forever.)
1467 * <p>
1468 * TODO: this feature should really be controlled by a new type of poke
1469 * lock (rather than an IPowerManager call).
1470 */
1471 public void preventScreenOn(boolean prevent) {
1472 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1473
1474 synchronized (mLocks) {
1475 if (prevent) {
1476 // First of all, grab a partial wake lock to
1477 // make sure the CPU stays on during the entire
1478 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1479 mPreventScreenOnPartialLock.acquire();
1480
1481 // Post a forceReenableScreen() call (for 5 seconds in the
1482 // future) to make sure the matching preventScreenOn(false) call
1483 // has happened by then.
1484 mHandler.removeCallbacks(mForceReenableScreenTask);
1485 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1486
1487 // Finally, set the flag that prevents the screen from turning on.
1488 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001489 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 mPreventScreenOn = true;
1491 } else {
1492 // (Re)enable the screen.
1493 mPreventScreenOn = false;
1494
1495 // We're "undoing" a the prior preventScreenOn(true) call, so we
1496 // no longer need the 5-second safeguard.
1497 mHandler.removeCallbacks(mForceReenableScreenTask);
1498
1499 // Forcibly turn on the screen if it's supposed to be on. (This
1500 // handles the case where the screen is currently off because of
1501 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001502 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001504 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1506 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001507 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001509 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511 }
1512
1513 // Release the partial wake lock that we held during the
1514 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1515 mPreventScreenOnPartialLock.release();
1516 }
1517 }
1518 }
1519
1520 public void setScreenBrightnessOverride(int brightness) {
1521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1522
Mike Lockwoodf527c712010-06-10 14:12:33 -04001523 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 synchronized (mLocks) {
1525 if (mScreenBrightnessOverride != brightness) {
1526 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001527 if (isScreenOn()) {
1528 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 }
1532 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001533
1534 public void setButtonBrightnessOverride(int brightness) {
1535 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1536
Mike Lockwoodf527c712010-06-10 14:12:33 -04001537 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001538 synchronized (mLocks) {
1539 if (mButtonBrightnessOverride != brightness) {
1540 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001541 if (isScreenOn()) {
1542 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1543 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001544 }
1545 }
1546 }
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 /**
1549 * Sanity-check that gets called 5 seconds after any call to
1550 * preventScreenOn(true). This ensures that the original call
1551 * is followed promptly by a call to preventScreenOn(false).
1552 */
1553 private void forceReenableScreen() {
1554 // We shouldn't get here at all if mPreventScreenOn is false, since
1555 // we should have already removed any existing
1556 // mForceReenableScreenTask messages...
1557 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001558 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 return;
1560 }
1561
1562 // Uh oh. It's been 5 seconds since a call to
1563 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1564 // This means the app that called preventScreenOn(true) is either
1565 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1566 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1567 // crashed before doing so.)
1568
1569 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001570 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 + "Forcing the screen back on...");
1572 preventScreenOn(false);
1573 }
1574
1575 private Runnable mForceReenableScreenTask = new Runnable() {
1576 public void run() {
1577 forceReenableScreen();
1578 }
1579 };
1580
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001581 private int setScreenStateLocked(boolean on) {
1582 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001583 if (err == 0) {
1584 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1585 if (mUseSoftwareAutoBrightness) {
1586 enableLightSensor(on);
1587 if (!on) {
1588 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001589 mButtonLight.turnOff();
1590 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001591 // clear current value so we will update based on the new conditions
1592 // when the sensor is reenabled.
1593 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001594 // reset our highest light sensor value when the screen turns off
1595 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001596 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001597 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001598 }
1599 return err;
1600 }
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 private void setPowerState(int state)
1603 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001604 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
Mike Lockwood435eb642009-12-03 08:40:18 -05001607 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 {
1609 synchronized (mLocks) {
1610 int err;
1611
1612 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001613 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001615 + " noChangeLights=" + noChangeLights
1616 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
1619 if (noChangeLights) {
1620 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1621 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001622 if (mProximitySensorActive) {
1623 // don't turn on the screen when the proximity sensor lock is held
1624 newState = (newState & ~SCREEN_BRIGHT);
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626
1627 if (batteryIsLow()) {
1628 newState |= BATTERY_LOW_BIT;
1629 } else {
1630 newState &= ~BATTERY_LOW_BIT;
1631 }
1632 if (newState == mPowerState) {
1633 return;
1634 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001635
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001636 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 newState |= ALL_BRIGHT;
1638 }
1639
1640 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1641 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1642
Mike Lockwood51b84492009-11-16 21:51:18 -05001643 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001644 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001646 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001648 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001652 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001654 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1656 }
1657
1658 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001659 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1661 }
1662
1663 if (oldScreenOn != newScreenOn) {
1664 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001665 // When the user presses the power button, we need to always send out the
1666 // notification that it's going to sleep so the keyguard goes on. But
1667 // we can't do that until the screen fades out, so we don't show the keyguard
1668 // too early.
1669 if (mStillNeedSleepNotification) {
1670 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1671 }
1672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 // Turn on the screen UNLESS there was a prior
1674 // preventScreenOn(true) request. (Note that the lifetime
1675 // of a single preventScreenOn() request is limited to 5
1676 // seconds to prevent a buggy app from disabling the
1677 // screen forever; see forceReenableScreen().)
1678 boolean reallyTurnScreenOn = true;
1679 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 + mPreventScreenOn);
1682 }
1683
1684 if (mPreventScreenOn) {
1685 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001686 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 reallyTurnScreenOn = false;
1689 }
1690 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001691 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 long identity = Binder.clearCallingIdentity();
1693 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001694 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 mBatteryStats.noteScreenOn();
1696 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 } finally {
1699 Binder.restoreCallingIdentity(identity);
1700 }
1701 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001702 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 // But continue as if we really did turn the screen on...
1704 err = 0;
1705 }
1706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 mLastTouchDown = 0;
1708 mTotalTouchDownTime = 0;
1709 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001710 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 mTotalTouchDownTime, mTouchCycles);
1712 if (err == 0) {
1713 mPowerState |= SCREEN_ON_BIT;
1714 sendNotificationLocked(true, -1);
1715 }
1716 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001717 // cancel light sensor task
1718 mHandler.removeCallbacks(mAutoBrightnessTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 mScreenOffTime = SystemClock.elapsedRealtime();
1720 long identity = Binder.clearCallingIdentity();
1721 try {
1722 mBatteryStats.noteScreenOff();
1723 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001724 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 } finally {
1726 Binder.restoreCallingIdentity(identity);
1727 }
1728 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001729 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001731 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 err = 0;
1734 mLastTouchDown = 0;
1735 }
1736 }
1737 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001738
1739 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001742
1743 private void updateNativePowerStateLocked() {
1744 nativeSetPowerState(
1745 (mPowerState & SCREEN_ON_BIT) != 0,
1746 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001748
Mike Lockwood435eb642009-12-03 08:40:18 -05001749 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001751 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001753 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1754 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001756 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001758 mScreenOffReason = reason;
1759 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 return err;
1762 }
1763
1764 private boolean batteryIsLow() {
1765 return (!mIsPowered &&
1766 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1767 }
1768
The Android Open Source Project10592532009-03-18 17:39:46 -07001769 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001770 final int oldState = mPowerState;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001771 newState = applyButtonState(newState);
1772 newState = applyKeyboardState(newState);
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001773 final int realDifference = (newState ^ oldState);
1774 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 int offMask = 0;
1780 int dimMask = 0;
1781 int onMask = 0;
1782
1783 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001786 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1787 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001789 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 }
1792
1793 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001794 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1795 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001797 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799 }
1800
1801 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001802 int nominalCurrentValue = -1;
1803 // If there was an actual difference in the light state, then
1804 // figure out the "ideal" current value based on the previous
1805 // state. Otherwise, this is a change due to the brightness
1806 // override, so we want to animate from whatever the current
1807 // value is.
1808 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1809 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1810 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1811 nominalCurrentValue = preferredBrightness;
1812 break;
1813 case SCREEN_ON_BIT:
1814 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1815 break;
1816 case 0:
1817 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1818 break;
1819 case SCREEN_BRIGHT_BIT:
1820 default:
1821 // not possible
1822 nominalCurrentValue = (int)mScreenBrightness.curValue;
1823 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001824 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001825 }
1826 int brightness = preferredBrightness;
1827 int steps = ANIM_STEPS;
1828 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1829 // dim or turn off backlight, depending on if the screen is on
1830 // the scale is because the brightness ramp isn't linear and this biases
1831 // it so the later parts take longer.
1832 final float scale = 1.5f;
1833 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1834 if (ratio > 1.0f) ratio = 1.0f;
1835 if ((newState & SCREEN_ON_BIT) == 0) {
1836 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1837 // was bright
1838 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001840 // was dim
1841 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001843 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001845 if ((oldState & SCREEN_ON_BIT) != 0) {
1846 // was bright
1847 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1848 } else {
1849 // was dim
1850 steps = (int)(ANIM_STEPS*ratio);
1851 }
1852 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1853 // If the "stay on while plugged in" option is
1854 // turned on, then the screen will often not
1855 // automatically turn off while plugged in. To
1856 // still have a sense of when it is inactive, we
1857 // will then count going dim as turning off.
1858 mScreenOffTime = SystemClock.elapsedRealtime();
1859 }
1860 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
1862 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001863 long identity = Binder.clearCallingIdentity();
1864 try {
1865 mBatteryStats.noteScreenBrightness(brightness);
1866 } catch (RemoteException e) {
1867 // Nothing interesting to do.
1868 } finally {
1869 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001871 mScreenBrightness.setTargetLocked(brightness, steps,
1872 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001876 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001877 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 if (dimMask != 0) {
1880 int brightness = Power.BRIGHTNESS_DIM;
1881 if ((newState & BATTERY_LOW_BIT) != 0 &&
1882 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1883 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1884 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001885 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001886 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 if (onMask != 0) {
1889 int brightness = getPreferredBrightness();
1890 if ((newState & BATTERY_LOW_BIT) != 0 &&
1891 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1892 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1893 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001894 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001895 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898
The Android Open Source Project10592532009-03-18 17:39:46 -07001899 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001900 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001901 ? LightsService.BRIGHTNESS_MODE_SENSOR
1902 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001903 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001904 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001905 }
1906 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001907 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001908 }
1909 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001910 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
1913
Joe Onoratob08a1af2010-10-11 19:28:58 -07001914 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 boolean initialized;
1918 int targetValue;
1919 float curValue;
1920 float delta;
1921 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 BrightnessState(int m) {
1924 mask = m;
1925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 public void dump(PrintWriter pw, String prefix) {
1928 pw.println(prefix + "animating=" + animating
1929 + " targetValue=" + targetValue
1930 + " curValue=" + curValue
1931 + " delta=" + delta);
1932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001933
Joe Onoratob08a1af2010-10-11 19:28:58 -07001934 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07001935 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 if (!initialized) {
1937 initialized = true;
1938 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07001939 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001940 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001943 delta = (targetValue -
1944 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
1945 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07001947 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato8a9b2202010-02-26 18:56:32 -08001948 Slog.i(TAG, "Setting target " + mask + ": cur=" + curValue
Joe Onorato128e7292009-03-24 18:41:31 -07001949 + " target=" + targetValue + " delta=" + delta
1950 + " nominalCurrentValue=" + nominalCurrentValue
1951 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
1953 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001954
1955 if (mSpew) {
1956 Slog.i(TAG, "scheduling light animator");
1957 }
1958 mScreenOffHandler.removeCallbacks(this);
1959 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 boolean stepLocked() {
1963 if (!animating) return false;
1964 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001965 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 + " target=" + targetValue + " delta=" + delta);
1967 }
1968 curValue += delta;
1969 int curIntValue = (int)curValue;
1970 boolean more = true;
1971 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001972 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 more = false;
1974 } else if (delta > 0) {
1975 if (curIntValue >= targetValue) {
1976 curValue = curIntValue = targetValue;
1977 more = false;
1978 }
1979 } else {
1980 if (curIntValue <= targetValue) {
1981 curValue = curIntValue = targetValue;
1982 more = false;
1983 }
1984 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001985 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001986 setLightBrightness(mask, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07001987 finishAnimation(more, curIntValue);
1988 return more;
1989 }
1990
1991 void jumpToTarget() {
1992 if (mSpew) Slog.d(TAG, "jumpToTarget targetValue=" + targetValue + ": " + mask);
1993 setLightBrightness(mask, targetValue);
1994 final int tv = targetValue;
1995 curValue = tv;
1996 targetValue = -1;
1997 finishAnimation(false, tv);
1998 }
1999
2000 private void finishAnimation(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 animating = more;
2002 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002003 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002004 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002010 if (mAnimateScreenLights) {
2011 synchronized (mLocks) {
2012 long now = SystemClock.uptimeMillis();
2013 boolean more = mScreenBrightness.stepLocked();
2014 if (more) {
2015 mScreenOffHandler.postAtTime(this, now+(1000/60));
2016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002018 } else {
2019 boolean animate;
2020 boolean jump;
2021 synchronized (mLocks) {
2022 jump = animating; // we haven't already run this animation
2023 animate = jump && targetValue == Power.BRIGHTNESS_OFF; // we're turning off
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002025 if (animate) {
2026 nativeStartSurfaceFlingerAnimation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002028 mScreenBrightness.jumpToTarget();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030 }
2031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 private int getPreferredBrightness() {
2034 try {
2035 if (mScreenBrightnessOverride >= 0) {
2036 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002037 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002038 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002039 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2042 SCREEN_BRIGHTNESS);
2043 // Don't let applications turn the screen all the way off
2044 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2045 } catch (SettingNotFoundException snfe) {
2046 return Power.BRIGHTNESS_ON;
2047 }
2048 }
2049
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002050 private int applyButtonState(int state) {
2051 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002052 if ((state & BATTERY_LOW_BIT) != 0) {
2053 // do not override brightness if the battery is low
2054 return state;
2055 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002056 if (mButtonBrightnessOverride >= 0) {
2057 brightness = mButtonBrightnessOverride;
2058 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2059 brightness = mLightSensorButtonBrightness;
2060 }
2061 if (brightness > 0) {
2062 return state | BUTTON_BRIGHT_BIT;
2063 } else if (brightness == 0) {
2064 return state & ~BUTTON_BRIGHT_BIT;
2065 } else {
2066 return state;
2067 }
2068 }
2069
2070 private int applyKeyboardState(int state) {
2071 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002072 if ((state & BATTERY_LOW_BIT) != 0) {
2073 // do not override brightness if the battery is low
2074 return state;
2075 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002076 if (!mKeyboardVisible) {
2077 brightness = 0;
2078 } else if (mButtonBrightnessOverride >= 0) {
2079 brightness = mButtonBrightnessOverride;
2080 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2081 brightness = mLightSensorKeyboardBrightness;
2082 }
2083 if (brightness > 0) {
2084 return state | KEYBOARD_BRIGHT_BIT;
2085 } else if (brightness == 0) {
2086 return state & ~KEYBOARD_BRIGHT_BIT;
2087 } else {
2088 return state;
2089 }
2090 }
2091
Charles Mendis322591c2009-10-29 11:06:59 -07002092 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 synchronized (mLocks) {
2094 return (mPowerState & SCREEN_ON_BIT) != 0;
2095 }
2096 }
2097
Charles Mendis322591c2009-10-29 11:06:59 -07002098 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 synchronized (mLocks) {
2100 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2101 }
2102 }
2103
Mike Lockwood497087e32009-11-08 18:33:03 -05002104 private boolean isScreenTurningOffLocked() {
2105 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2106 }
2107
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002108 private boolean shouldLog(long time) {
2109 synchronized (mLocks) {
2110 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2111 mWarningSpewThrottleTime = time;
2112 mWarningSpewThrottleCount = 0;
2113 return true;
2114 } else if (mWarningSpewThrottleCount < 30) {
2115 mWarningSpewThrottleCount++;
2116 return true;
2117 } else {
2118 return false;
2119 }
2120 }
2121 }
2122
Mike Lockwood200b30b2009-09-20 00:23:59 -04002123 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002124 if (isScreenTurningOffLocked()) {
2125 // cancel animation so userActivity will succeed
2126 mScreenBrightness.animating = false;
2127 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002128 boolean savedActivityAllowed = mUserActivityAllowed;
2129 mUserActivityAllowed = true;
2130 userActivity(SystemClock.uptimeMillis(), false);
2131 mUserActivityAllowed = savedActivityAllowed;
2132 }
2133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2135 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002136 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
2138
2139 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002140 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2141 != PackageManager.PERMISSION_GRANTED) {
2142 if (shouldLog(time)) {
2143 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2144 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2145 }
2146 return;
2147 }
2148
Joe Onorato7999bff2010-07-24 11:50:05 -04002149 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
2151
2152 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002153 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155
2156 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002157 userActivity(time, -1, noChangeLights, eventType, force);
2158 }
2159
2160 /*
2161 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2162 * on with user activity. Don't use this function.
2163 */
2164 public void clearUserActivityTimeout(long now, long timeout) {
2165 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2166 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2167 userActivity(now, timeout, false, OTHER_EVENT, false);
2168 }
2169
2170 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2171 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172
2173 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002174 && (eventType == CHEEK_EVENT || eventType == TOUCH_EVENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002176 Slog.d(TAG, "dropping cheek or short event mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
2178 return;
2179 }
2180
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002181 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS) != 0)
2182 && (eventType == TOUCH_EVENT || eventType == TOUCH_UP_EVENT
2183 || eventType == LONG_TOUCH_EVENT || eventType == CHEEK_EVENT)) {
2184 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002185 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002186 }
2187 return;
2188 }
2189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 if (false) {
2191 if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002192 Slog.d(TAG, "userActivity !!!");//, new RuntimeException());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 Slog.d(TAG, "mPokey=0x" + Integer.toHexString(mPokey));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196 }
2197
2198 synchronized (mLocks) {
2199 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002200 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 + " mUserActivityAllowed=" + mUserActivityAllowed
2202 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002203 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2204 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002205 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002206 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 }
Mike Lockwood05067122009-10-27 23:07:25 -04002208 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002209 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002210 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002211 return;
2212 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002213 // Disable proximity sensor if if user presses power key while we are in the
2214 // "waiting for proximity sensor to go negative" state.
2215 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2216 mProximitySensorActive = false;
2217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 if (mLastEventTime <= time || force) {
2219 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002220 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002221 // Only turn on button backlights if a button was pressed
2222 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002223 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2225 } else {
2226 // don't clear button/keyboard backlights when the screen is touched.
2227 mUserState |= SCREEN_BRIGHT;
2228 }
2229
Dianne Hackborn617f8772009-03-31 15:04:46 -07002230 int uid = Binder.getCallingUid();
2231 long ident = Binder.clearCallingIdentity();
2232 try {
2233 mBatteryStats.noteUserActivity(uid, eventType);
2234 } catch (RemoteException e) {
2235 // Ignore
2236 } finally {
2237 Binder.restoreCallingIdentity(ident);
2238 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002239
Michael Chane96440f2009-05-06 10:27:36 -07002240 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002241 setPowerState(mUserState | mWakeLockState, noChangeLights,
2242 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002243 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245 }
2246 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002247
2248 if (mPolicy != null) {
2249 mPolicy.userActivity();
2250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 }
2252
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002253 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2254 try {
2255 int i;
2256 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2257 if (sensorValue < mAutoBrightnessLevels[i]) {
2258 break;
2259 }
2260 }
2261 return values[i];
2262 } catch (Exception e) {
2263 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002264 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002265 return 255;
2266 }
2267 }
2268
Mike Lockwood20f87d72009-11-05 16:08:51 -05002269 private Runnable mProximityTask = new Runnable() {
2270 public void run() {
2271 synchronized (mLocks) {
2272 if (mProximityPendingValue != -1) {
2273 proximityChangedLocked(mProximityPendingValue == 1);
2274 mProximityPendingValue = -1;
2275 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002276 if (mProximityPartialLock.isHeld()) {
2277 mProximityPartialLock.release();
2278 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002279 }
2280 }
2281 };
2282
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002283 private Runnable mAutoBrightnessTask = new Runnable() {
2284 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002285 synchronized (mLocks) {
2286 int value = (int)mLightSensorPendingValue;
2287 if (value >= 0) {
2288 mLightSensorPendingValue = -1;
2289 lightSensorChangedLocked(value);
2290 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002291 }
2292 }
2293 };
2294
Mike Lockwoodb2865412010-02-02 22:40:33 -05002295 private void dockStateChanged(int state) {
2296 synchronized (mLocks) {
2297 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2298 if (mIsDocked) {
2299 mHighestLightSensorValue = -1;
2300 }
2301 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2302 // force lights recalculation
2303 int value = (int)mLightSensorValue;
2304 mLightSensorValue = -1;
2305 lightSensorChangedLocked(value);
2306 }
2307 }
2308 }
2309
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002310 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002311 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002312 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002313 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002314
Mike Lockwoodb2865412010-02-02 22:40:33 -05002315 // do not allow light sensor value to decrease
2316 if (mHighestLightSensorValue < value) {
2317 mHighestLightSensorValue = value;
2318 }
2319
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002320 if (mLightSensorValue != value) {
2321 mLightSensorValue = value;
2322 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002323 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2324 // we only do this if we are undocked, since lighting should be stable when
2325 // stationary in a dock.
2326 int lcdValue = getAutoBrightnessValue(
2327 (mIsDocked ? value : mHighestLightSensorValue),
2328 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002329 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002330 int keyboardValue;
2331 if (mKeyboardVisible) {
2332 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2333 } else {
2334 keyboardValue = 0;
2335 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002336 mLightSensorScreenBrightness = lcdValue;
2337 mLightSensorButtonBrightness = buttonValue;
2338 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002339
2340 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002341 Slog.d(TAG, "lcdValue " + lcdValue);
2342 Slog.d(TAG, "buttonValue " + buttonValue);
2343 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002344 }
2345
Mike Lockwood4984e732009-11-01 08:16:33 -05002346 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002347 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2348 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002349 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002350 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002351 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002352 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002353 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002354 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002355 }
2356 }
2357 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002358 }
2359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 /**
2361 * The user requested that we go to sleep (probably with the power button).
2362 * This overrides all wake locks that are held.
2363 */
2364 public void goToSleep(long time)
2365 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002366 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2367 }
2368
2369 /**
2370 * The user requested that we go to sleep (probably with the power button).
2371 * This overrides all wake locks that are held.
2372 */
2373 public void goToSleepWithReason(long time, int reason)
2374 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2376 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002377 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 }
2379 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002382 * Reboot the device immediately, passing 'reason' (may be null)
2383 * to the underlying __reboot system call. Should not return.
2384 */
2385 public void reboot(String reason)
2386 {
2387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002388
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002389 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2390 throw new IllegalStateException("Too early to call reboot()");
2391 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002392
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002393 final String finalReason = reason;
2394 Runnable runnable = new Runnable() {
2395 public void run() {
2396 synchronized (this) {
2397 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002398 }
2399
San Mehat1e512792010-01-07 10:40:29 -08002400 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002401 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002402 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002403 mHandler.post(runnable);
2404
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002405 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002406 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002407 while (true) {
2408 try {
2409 runnable.wait();
2410 } catch (InterruptedException e) {
2411 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002412 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002413 }
2414 }
2415
Dan Egnor60d87622009-12-16 16:32:58 -08002416 /**
2417 * Crash the runtime (causing a complete restart of the Android framework).
2418 * Requires REBOOT permission. Mostly for testing. Should not return.
2419 */
2420 public void crash(final String message)
2421 {
2422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2423 Thread t = new Thread("PowerManagerService.crash()") {
2424 public void run() { throw new RuntimeException(message); }
2425 };
2426 try {
2427 t.start();
2428 t.join();
2429 } catch (InterruptedException e) {
2430 Log.wtf(TAG, e);
2431 }
2432 }
2433
Mike Lockwood435eb642009-12-03 08:40:18 -05002434 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435
2436 if (mLastEventTime <= time) {
2437 mLastEventTime = time;
2438 // cancel all of the wake locks
2439 mWakeLockState = SCREEN_OFF;
2440 int N = mLocks.size();
2441 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002442 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 for (int i=0; i<N; i++) {
2444 WakeLock wl = mLocks.get(i);
2445 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002446 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2447 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2448 proxLock = true;
2449 } else {
2450 mLocks.get(i).activated = false;
2451 numCleared++;
2452 }
2453 }
2454 }
2455 if (!proxLock) {
2456 mProxIgnoredBecauseScreenTurnedOff = true;
2457 if (mDebugProximitySensor) {
2458 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 }
2460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002461 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002462 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002464 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 cancelTimerLocked();
2466 }
2467 }
2468
2469 public long timeSinceScreenOn() {
2470 synchronized (mLocks) {
2471 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2472 return 0;
2473 }
2474 return SystemClock.elapsedRealtime() - mScreenOffTime;
2475 }
2476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002479 synchronized (mLocks) {
2480 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002481 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002482 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002483 if (mKeyboardVisible != visible) {
2484 mKeyboardVisible = visible;
2485 // don't signal user activity if the screen is off; other code
2486 // will take care of turning on due to a true change to the lid
2487 // switch and synchronized with the lock screen.
2488 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002489 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002490 // force recompute of backlight values
2491 if (mLightSensorValue >= 0) {
2492 int value = (int)mLightSensorValue;
2493 mLightSensorValue = -1;
2494 lightSensorChangedLocked(value);
2495 }
2496 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002497 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2498 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002499 }
2500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502
2503 /**
2504 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002505 * When disabling user activity we also reset user power state so the keyguard can reset its
2506 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 */
2508 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002509 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002510 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 synchronized (mLocks) {
2513 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002514 if (!enabled) {
2515 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2516 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 }
2519 }
2520
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002521 private void setScreenBrightnessMode(int mode) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002522 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Mike Lockwoodf90ffcc2009-11-03 11:41:27 -05002523 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
Mike Lockwood2d155d22009-10-27 09:32:30 -04002524 mAutoBrightessEnabled = enabled;
Charles Mendis322591c2009-10-29 11:06:59 -07002525 if (isScreenOn()) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002526 // force recompute of backlight values
2527 if (mLightSensorValue >= 0) {
2528 int value = (int)mLightSensorValue;
2529 mLightSensorValue = -1;
2530 lightSensorChangedLocked(value);
2531 }
Mike Lockwood2d155d22009-10-27 09:32:30 -04002532 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002533 }
2534 }
2535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 /** Sets the screen off timeouts:
2537 * mKeylightDelay
2538 * mDimDelay
2539 * mScreenOffDelay
2540 * */
2541 private void setScreenOffTimeoutsLocked() {
2542 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002543 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 mDimDelay = -1;
2545 mScreenOffDelay = 0;
2546 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2547 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2548 mDimDelay = -1;
2549 mScreenOffDelay = 0;
2550 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002551 int totalDelay = mScreenOffTimeoutSetting;
2552 if (totalDelay > mMaximumScreenOffTimeout) {
2553 totalDelay = mMaximumScreenOffTimeout;
2554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2556 if (totalDelay < 0) {
2557 mScreenOffDelay = Integer.MAX_VALUE;
2558 } else if (mKeylightDelay < totalDelay) {
2559 // subtract the time that the keylight delay. This will give us the
2560 // remainder of the time that we need to sleep to get the accurate
2561 // screen off timeout.
2562 mScreenOffDelay = totalDelay - mKeylightDelay;
2563 } else {
2564 mScreenOffDelay = 0;
2565 }
2566 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2567 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2568 mScreenOffDelay = LONG_DIM_TIME;
2569 } else {
2570 mDimDelay = -1;
2571 }
2572 }
2573 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002574 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2576 + " mDimScreen=" + mDimScreen);
2577 }
2578 }
2579
2580 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002581 * Refreshes cached secure settings. Called once on startup, and
2582 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 */
Doug Zongker43866e02010-01-07 12:09:54 -08002584 private void updateSettingsValues() {
2585 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002587 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002589 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591
2592 private class LockList extends ArrayList<WakeLock>
2593 {
2594 void addLock(WakeLock wl)
2595 {
2596 int index = getIndex(wl.binder);
2597 if (index < 0) {
2598 this.add(wl);
2599 }
2600 }
2601
2602 WakeLock removeLock(IBinder binder)
2603 {
2604 int index = getIndex(binder);
2605 if (index >= 0) {
2606 return this.remove(index);
2607 } else {
2608 return null;
2609 }
2610 }
2611
2612 int getIndex(IBinder binder)
2613 {
2614 int N = this.size();
2615 for (int i=0; i<N; i++) {
2616 if (this.get(i).binder == binder) {
2617 return i;
2618 }
2619 }
2620 return -1;
2621 }
2622
2623 int gatherState()
2624 {
2625 int result = 0;
2626 int N = this.size();
2627 for (int i=0; i<N; i++) {
2628 WakeLock wl = this.get(i);
2629 if (wl.activated) {
2630 if (isScreenLock(wl.flags)) {
2631 result |= wl.minState;
2632 }
2633 }
2634 }
2635 return result;
2636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002637
Michael Chane96440f2009-05-06 10:27:36 -07002638 int reactivateScreenLocksLocked()
2639 {
2640 int result = 0;
2641 int N = this.size();
2642 for (int i=0; i<N; i++) {
2643 WakeLock wl = this.get(i);
2644 if (isScreenLock(wl.flags)) {
2645 wl.activated = true;
2646 result |= wl.minState;
2647 }
2648 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002649 if (mDebugProximitySensor) {
2650 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2651 + mProxIgnoredBecauseScreenTurnedOff);
2652 }
2653 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002654 return result;
2655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657
2658 void setPolicy(WindowManagerPolicy p) {
2659 synchronized (mLocks) {
2660 mPolicy = p;
2661 mLocks.notifyAll();
2662 }
2663 }
2664
2665 WindowManagerPolicy getPolicyLocked() {
2666 while (mPolicy == null || !mDoneBooting) {
2667 try {
2668 mLocks.wait();
2669 } catch (InterruptedException e) {
2670 // Ignore
2671 }
2672 }
2673 return mPolicy;
2674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002677 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2678 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2679 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002680 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002681 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood4984e732009-11-01 08:16:33 -05002682 enableLightSensor(true);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002683 }
2684
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002685 // wait until sensors are enabled before turning on screen.
2686 // some devices will not activate the light sensor properly on boot
2687 // unless we do this.
2688 if (mUseSoftwareAutoBrightness) {
2689 // turn the screen on
2690 setPowerState(SCREEN_BRIGHT);
2691 } else {
2692 // turn everything on
2693 setPowerState(ALL_BRIGHT);
2694 }
2695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002697 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002699
Dianne Hackborn617f8772009-03-31 15:04:46 -07002700 long identity = Binder.clearCallingIdentity();
2701 try {
2702 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2703 mBatteryStats.noteScreenOn();
2704 } catch (RemoteException e) {
2705 // Nothing interesting to do.
2706 } finally {
2707 Binder.restoreCallingIdentity(identity);
2708 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002709 }
2710 }
2711
2712 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002713 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002714 synchronized (mLocks) {
2715 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2717 updateWakeLockLocked();
2718 mLocks.notifyAll();
2719 }
2720 }
2721
Joe Onoratob08a1af2010-10-11 19:28:58 -07002722 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 public void monitor() {
2724 synchronized (mLocks) { }
2725 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002726
2727 public int getSupportedWakeLockFlags() {
2728 int result = PowerManager.PARTIAL_WAKE_LOCK
2729 | PowerManager.FULL_WAKE_LOCK
2730 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2731
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002732 if (mProximitySensor != null) {
2733 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2734 }
2735
2736 return result;
2737 }
2738
Mike Lockwood237a2992009-09-15 14:42:16 -04002739 public void setBacklightBrightness(int brightness) {
2740 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2741 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002742 synchronized (mLocks) {
2743 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2744 mLcdLight.setBrightness(brightness);
2745 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2746 mButtonLight.setBrightness(brightness);
2747 long identity = Binder.clearCallingIdentity();
2748 try {
2749 mBatteryStats.noteScreenBrightness(brightness);
2750 } catch (RemoteException e) {
2751 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2752 } finally {
2753 Binder.restoreCallingIdentity(identity);
2754 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002755
Joe Onoratob08a1af2010-10-11 19:28:58 -07002756 // update our animation state
2757 mScreenBrightness.targetValue = brightness;
2758 mScreenBrightness.jumpToTarget();
Mike Lockwood237a2992009-09-15 14:42:16 -04002759 }
2760 }
2761
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002762 public void setAttentionLight(boolean on, int color) {
2763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002764 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002765 }
2766
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002767 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002768 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002769 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002770 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002771 if (!mProximitySensorEnabled) {
2772 // clear calling identity so sensor manager battery stats are accurate
2773 long identity = Binder.clearCallingIdentity();
2774 try {
2775 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2776 SensorManager.SENSOR_DELAY_NORMAL);
2777 mProximitySensorEnabled = true;
2778 } finally {
2779 Binder.restoreCallingIdentity(identity);
2780 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002781 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002782 }
2783
2784 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002785 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002786 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002787 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002788 if (mProximitySensorEnabled) {
2789 // clear calling identity so sensor manager battery stats are accurate
2790 long identity = Binder.clearCallingIdentity();
2791 try {
2792 mSensorManager.unregisterListener(mProximityListener);
2793 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002794 if (mProximityPartialLock.isHeld()) {
2795 mProximityPartialLock.release();
2796 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002797 mProximitySensorEnabled = false;
2798 } finally {
2799 Binder.restoreCallingIdentity(identity);
2800 }
2801 if (mProximitySensorActive) {
2802 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002803 if (mDebugProximitySensor) {
2804 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2805 + mProxIgnoredBecauseScreenTurnedOff);
2806 }
2807 if (!mProxIgnoredBecauseScreenTurnedOff) {
2808 forceUserActivityLocked();
2809 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002810 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002811 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002812 }
2813
Mike Lockwood20f87d72009-11-05 16:08:51 -05002814 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002815 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002816 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002817 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002818 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002819 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002820 return;
2821 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002822 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002823 if (mDebugProximitySensor) {
2824 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2825 + mProxIgnoredBecauseScreenTurnedOff);
2826 }
2827 if (!mProxIgnoredBecauseScreenTurnedOff) {
2828 goToSleepLocked(SystemClock.uptimeMillis(),
2829 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2830 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002831 mProximitySensorActive = true;
2832 } else {
2833 // proximity sensor negative events trigger as user activity.
2834 // temporarily set mUserActivityAllowed to true so this will work
2835 // even when the keyguard is on.
2836 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002837 if (mDebugProximitySensor) {
2838 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2839 + mProxIgnoredBecauseScreenTurnedOff);
2840 }
2841 if (!mProxIgnoredBecauseScreenTurnedOff) {
2842 forceUserActivityLocked();
2843 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002844
2845 if (mProximityWakeLockCount == 0) {
2846 // disable sensor if we have no listeners left after proximity negative
2847 disableProximityLockLocked();
2848 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002849 }
2850 }
2851
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002852 private void enableLightSensor(boolean enable) {
2853 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002854 Slog.d(TAG, "enableLightSensor " + enable);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002855 }
2856 if (mSensorManager != null && mLightSensorEnabled != enable) {
2857 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002858 // clear calling identity so sensor manager battery stats are accurate
2859 long identity = Binder.clearCallingIdentity();
2860 try {
2861 if (enable) {
2862 mSensorManager.registerListener(mLightListener, mLightSensor,
2863 SensorManager.SENSOR_DELAY_NORMAL);
2864 } else {
2865 mSensorManager.unregisterListener(mLightListener);
2866 mHandler.removeCallbacks(mAutoBrightnessTask);
2867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002870 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002871 }
2872 }
2873
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002874 SensorEventListener mProximityListener = new SensorEventListener() {
2875 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002876 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002877 synchronized (mLocks) {
2878 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002879 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2880 mLastProximityEventTime = milliseconds;
2881 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002882 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002883
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002884 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002885 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2886 distance < mProximitySensor.getMaximumRange());
2887
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002888 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002889 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002890 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002891 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2892 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2893 mProximityPendingValue = (active ? 1 : 0);
2894 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002895 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002896 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002897 // process the value immediately
2898 mProximityPendingValue = -1;
2899 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002900 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002901
2902 // update mProximityPartialLock state
2903 boolean held = mProximityPartialLock.isHeld();
2904 if (!held && proximityTaskQueued) {
2905 // hold wakelock until mProximityTask runs
2906 mProximityPartialLock.acquire();
2907 } else if (held && !proximityTaskQueued) {
2908 mProximityPartialLock.release();
2909 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002910 }
2911 }
2912
2913 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2914 // ignore
2915 }
2916 };
2917
2918 SensorEventListener mLightListener = new SensorEventListener() {
2919 public void onSensorChanged(SensorEvent event) {
2920 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002921 // ignore light sensor while screen is turning off
2922 if (isScreenTurningOffLocked()) {
2923 return;
2924 }
2925
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002926 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002927 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002928 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002929 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002930 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002931 mHandler.removeCallbacks(mAutoBrightnessTask);
2932 if (mLightSensorValue != value) {
Mike Lockwood20ee6f22009-11-07 20:33:47 -05002933 if (mLightSensorValue == -1 ||
2934 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
2935 // process the value immediately if screen has just turned on
Mike Lockwood6c97fca2009-10-20 08:10:00 -04002936 lightSensorChangedLocked(value);
2937 } else {
2938 // delay processing to debounce the sensor
2939 mLightSensorPendingValue = value;
2940 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
2941 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002942 } else {
2943 mLightSensorPendingValue = -1;
2944 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002945 }
2946 }
2947
2948 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2949 // ignore
2950 }
2951 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952}