blob: bb21d81f3cd17e04e04b5e7a8eb8f01447e73ad3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070040import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.BatteryStats;
42import android.os.Binder;
43import android.os.Handler;
44import android.os.HandlerThread;
45import android.os.IBinder;
46import android.os.IPowerManager;
47import android.os.LocalPowerManager;
48import android.os.Power;
49import android.os.PowerManager;
50import android.os.Process;
51import android.os.RemoteException;
52import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070053import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings.SettingNotFoundException;
55import android.provider.Settings;
56import android.util.EventLog;
57import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.WindowManagerPolicy;
60import static android.provider.Settings.System.DIM_SCREEN;
61import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070063import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
65import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070066import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
67import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69import java.io.FileDescriptor;
70import java.io.PrintWriter;
71import java.util.ArrayList;
72import java.util.HashMap;
73import java.util.Observable;
74import java.util.Observer;
75
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080076public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040077 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79 private static final String TAG = "PowerManagerService";
80 static final String PARTIAL_NAME = "PowerManagerService";
81
82 private static final boolean LOG_PARTIAL_WL = false;
83
84 // Indicates whether touch-down cycles should be logged as part of the
85 // LOG_POWER_SCREEN_STATE log events
86 private static final boolean LOG_TOUCH_DOWNS = true;
87
88 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
89 | PowerManager.SCREEN_DIM_WAKE_LOCK
90 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070091 | PowerManager.FULL_WAKE_LOCK
92 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080095 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
97 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
98 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
99 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
100
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500102 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700103
Mike Lockwood20f87d72009-11-05 16:08:51 -0500104 // For debouncing the proximity sensor.
105 private static final int PROXIMITY_SENSOR_DELAY = 1000;
106
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400107 // trigger proximity if distance is less than 5 cm
108 private static final float PROXIMITY_THRESHOLD = 5.0f;
109
Doug Zongker43866e02010-01-07 12:09:54 -0800110 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
112
Amith Yamasani8b619832010-09-22 16:11:59 -0700113 // Default timeout for screen off, if not found in settings database = 15 seconds.
114 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 // flags for setPowerState
117 private static final int SCREEN_ON_BIT = 0x00000001;
118 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
119 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
120 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
121 private static final int BATTERY_LOW_BIT = 0x00000010;
122
123 // values for setPowerState
124
125 // SCREEN_OFF == everything off
126 private static final int SCREEN_OFF = 0x00000000;
127
128 // SCREEN_DIM == screen on, screen backlight dim
129 private static final int SCREEN_DIM = SCREEN_ON_BIT;
130
131 // SCREEN_BRIGHT == screen on, screen backlight bright
132 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
133
134 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
135 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
136
137 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
138 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
139
140 // used for noChangeLights in setPowerState()
141 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
142
Joe Onoratob08a1af2010-10-11 19:28:58 -0700143 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400146 // Slower animation for autobrightness changes
147 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 // These magic numbers are the initial state of the LEDs at boot. Ideally
150 // we should read them from the driver, but our current hardware returns 0
151 // for the initial value. Oops!
152 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
153 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
154 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700157 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
159 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500160 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500162 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
163 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn29aae6f2011-08-18 18:30:09 -0700164 private boolean mBroadcastingScreenOff = false;
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;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500220 private boolean mLightSensorPendingDecrease = false;
221 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700222 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500223 private int mLightSensorScreenBrightness = -1;
224 private int mLightSensorButtonBrightness = -1;
225 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500227 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private long mNextTimeout;
229 private volatile int mPokey = 0;
230 private volatile boolean mPokeAwakeOnSet = false;
231 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500232 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500233 // mLastScreenOnTime is the time the screen was last turned on
234 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private boolean mPreventScreenOn;
236 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500237 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400238 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400239 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700240 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700241 private int[] mAutoBrightnessLevels;
242 private int[] mLcdBacklightValues;
243 private int[] mButtonBacklightValues;
244 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500245 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700246 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700247 private int mWarningSpewThrottleCount;
248 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700249 private int mAnimationSetting = ANIM_SETTING_OFF;
250
251 // Must match with the ISurfaceComposer constants in C++.
252 private static final int ANIM_SETTING_ON = 0x01;
253 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
255 // Used when logging number and duration of touch-down cycles
256 private long mTotalTouchDownTime;
257 private long mLastTouchDown;
258 private int mTouchCycles;
259
260 // could be either static or controllable at runtime
261 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400262 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400263 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700264
265 private native void nativeInit();
266 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700267 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 /*
270 static PrintStream mLog;
271 static {
272 try {
273 mLog = new PrintStream("/data/power.log");
274 }
275 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800276 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278 }
279 static class Log {
280 static void d(String tag, String s) {
281 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800282 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284 static void i(String tag, String s) {
285 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800286 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 static void w(String tag, String s) {
289 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800290 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292 static void e(String tag, String s) {
293 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800294 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 }
296 }
297 */
298
299 /**
300 * This class works around a deadlock between the lock in PowerManager.WakeLock
301 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
302 * mToken object so it can be accessed from any thread, but it calls into here
303 * with its lock held. This class is essentially a reimplementation of
304 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
305 * only call it with our own locks held.
306 */
307 private class UnsynchronizedWakeLock {
308 int mFlags;
309 String mTag;
310 IBinder mToken;
311 int mCount = 0;
312 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500313 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314
315 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
316 mFlags = flags;
317 mTag = tag;
318 mToken = new Binder();
319 mRefCounted = refCounted;
320 }
321
322 public void acquire() {
323 if (!mRefCounted || mCount++ == 0) {
324 long ident = Binder.clearCallingIdentity();
325 try {
326 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700327 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500328 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 } finally {
330 Binder.restoreCallingIdentity(ident);
331 }
332 }
333 }
334
335 public void release() {
336 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500337 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500338 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340 if (mCount < 0) {
341 throw new RuntimeException("WakeLock under-locked " + mTag);
342 }
343 }
344
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500345 public boolean isHeld()
346 {
347 return mHeld;
348 }
349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 public String toString() {
351 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500352 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354 }
355
356 private final class BatteryReceiver extends BroadcastReceiver {
357 @Override
358 public void onReceive(Context context, Intent intent) {
359 synchronized (mLocks) {
360 boolean wasPowered = mIsPowered;
361 mIsPowered = mBatteryService.isPowered();
362
363 if (mIsPowered != wasPowered) {
364 // update mStayOnWhilePluggedIn wake lock
365 updateWakeLockLocked();
366
367 // treat plugging and unplugging the devices as a user activity.
368 // users find it disconcerting when they unplug the device
369 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500370 // to avoid turning on the screen when unplugging, we only trigger
371 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 // temporarily set mUserActivityAllowed to true so this will work
373 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700374 // However, you can also set config_unplugTurnsOnScreen to have it
375 // turn on. Some devices want this because they don't have a
376 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700378 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
379 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500380 forceUserActivityLocked();
381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383 }
384 }
385 }
386 }
387
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500388 private final class BootCompletedReceiver extends BroadcastReceiver {
389 @Override
390 public void onReceive(Context context, Intent intent) {
391 bootCompleted();
392 }
393 }
394
Mike Lockwoodb2865412010-02-02 22:40:33 -0500395 private final class DockReceiver extends BroadcastReceiver {
396 @Override
397 public void onReceive(Context context, Intent intent) {
398 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
399 Intent.EXTRA_DOCK_STATE_UNDOCKED);
400 dockStateChanged(state);
401 }
402 }
403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 /**
405 * Set the setting that determines whether the device stays on when plugged in.
406 * The argument is a bit string, with each bit specifying a power source that,
407 * when the device is connected to that source, causes the device to stay on.
408 * See {@link android.os.BatteryManager} for the list of power sources that
409 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
410 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
411 * @param val an {@code int} containing the bits that specify which power sources
412 * should cause the device to stay on.
413 */
414 public void setStayOnSetting(int val) {
415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
416 Settings.System.putInt(mContext.getContentResolver(),
417 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
418 }
419
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800420 public void setMaximumScreenOffTimeount(int timeMs) {
421 mContext.enforceCallingOrSelfPermission(
422 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
423 synchronized (mLocks) {
424 mMaximumScreenOffTimeout = timeMs;
425 // recalculate everything
426 setScreenOffTimeoutsLocked();
427 }
428 }
429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700431 private int getInt(String name, int defValue) {
432 ContentValues values = mSettings.getValues(name);
433 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
434 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436
Joe Onorato609695d2010-10-14 14:57:49 -0700437 private float getFloat(String name, float defValue) {
438 ContentValues values = mSettings.getValues(name);
439 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
440 return fVal != null ? fVal : defValue;
441 }
442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 public void update(Observable o, Object arg) {
444 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700445 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
446 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
447 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 updateWakeLockLocked();
449
Amith Yamasani8b619832010-09-22 16:11:59 -0700450 // SCREEN_OFF_TIMEOUT, default to 15 seconds
451 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452
Joe Onorato609695d2010-10-14 14:57:49 -0700453 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 //mDimScreen = getInt(DIM_SCREEN) != 0;
455
Amith Yamasani8b619832010-09-22 16:11:59 -0700456 // SCREEN_BRIGHTNESS_MODE, default to manual
457 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
458 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 // recalculate everything
461 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700462
463 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
464 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
465 mAnimationSetting = 0;
466 if (windowScale > 0.5f) {
467 mAnimationSetting |= ANIM_SETTING_OFF;
468 }
469 if (transitionScale > 0.5f) {
470 // Uncomment this if you want the screen-on animation.
471 // mAnimationSetting |= ANIM_SETTING_ON;
472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 }
474 }
475 }
476
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700477 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 // Hack to get our uid... should have a func for this.
479 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700480 MY_UID = Process.myUid();
481 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 Binder.restoreCallingIdentity(token);
483
484 // XXX remove this when the kernel doesn't timeout wake locks
485 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
486
487 // assume nothing is on yet
488 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 // Add ourself to the Watchdog monitors.
491 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493
494 private ContentQueryMap mSettings;
495
Mike Lockwood3a322132009-11-24 00:30:52 -0500496 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700497 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500498 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 mContext = context;
500 mActivityService = activity;
501 mBatteryStats = BatteryStatsService.getService();
502 mBatteryService = battery;
503
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500504 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
505 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
506 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
507 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
508
Joe Onoratob08a1af2010-10-11 19:28:58 -0700509 nativeInit();
510 synchronized (mLocks) {
511 updateNativePowerStateLocked();
512 }
513
514 mInitComplete = false;
515 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
516 @Override
517 protected void onLooperPrepared() {
518 mScreenOffHandler = new Handler();
519 synchronized (mScreenOffThread) {
520 mInitComplete = true;
521 mScreenOffThread.notifyAll();
522 }
523 }
524 };
525 mScreenOffThread.start();
526
527 synchronized (mScreenOffThread) {
528 while (!mInitComplete) {
529 try {
530 mScreenOffThread.wait();
531 } catch (InterruptedException e) {
532 // Ignore
533 }
534 }
535 }
536
537 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 mHandlerThread = new HandlerThread("PowerManagerService") {
539 @Override
540 protected void onLooperPrepared() {
541 super.onLooperPrepared();
542 initInThread();
543 }
544 };
545 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 synchronized (mHandlerThread) {
548 while (!mInitComplete) {
549 try {
550 mHandlerThread.wait();
551 } catch (InterruptedException e) {
552 // Ignore
553 }
554 }
555 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700556
557 nativeInit();
558 synchronized (mLocks) {
559 updateNativePowerStateLocked();
560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 void initInThread() {
564 mHandler = new Handler();
565
566 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700567 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
569 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
570 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
571 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
572 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
573 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500574 mProximityPartialLock = new UnsynchronizedWakeLock(
575 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576
577 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
578 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
579 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
580 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
581
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700582 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400583
Joe Onoratob08a1af2010-10-11 19:28:58 -0700584 mAnimateScreenLights = resources.getBoolean(
585 com.android.internal.R.bool.config_animateScreenLights);
586
Joe Onorato6d747652010-10-11 15:15:31 -0700587 mUnplugTurnsOnScreen = resources.getBoolean(
588 com.android.internal.R.bool.config_unplugTurnsOnScreen);
589
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400590 mScreenBrightnessDim = resources.getInteger(
591 com.android.internal.R.integer.config_screenBrightnessDim);
592
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400593 // read settings for auto-brightness
594 mUseSoftwareAutoBrightness = resources.getBoolean(
595 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400596 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700597 mAutoBrightnessLevels = resources.getIntArray(
598 com.android.internal.R.array.config_autoBrightnessLevels);
599 mLcdBacklightValues = resources.getIntArray(
600 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
601 mButtonBacklightValues = resources.getIntArray(
602 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
603 mKeyboardBacklightValues = resources.getIntArray(
604 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500605 mLightSensorWarmupTime = resources.getInteger(
606 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700607 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700608
609 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
611 "(" + Settings.System.NAME + "=?) or ("
612 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700613 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700614 + Settings.System.NAME + "=?) or ("
615 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700617 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700618 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 null);
620 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
621 SettingsObserver settingsObserver = new SettingsObserver();
622 mSettings.addObserver(settingsObserver);
623
624 // pretend that the settings changed so we will get their initial state
625 settingsObserver.update(mSettings, null);
626
627 // register for the battery changed notifications
628 IntentFilter filter = new IntentFilter();
629 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
630 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500631 filter = new IntentFilter();
632 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
633 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500634 filter = new IntentFilter();
635 filter.addAction(Intent.ACTION_DOCK_EVENT);
636 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637
Doug Zongker43866e02010-01-07 12:09:54 -0800638 // Listen for secure settings changes
639 mContext.getContentResolver().registerContentObserver(
640 Settings.Secure.CONTENT_URI, true,
641 new ContentObserver(new Handler()) {
642 public void onChange(boolean selfChange) {
643 updateSettingsValues();
644 }
645 });
646 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 synchronized (mHandlerThread) {
649 mInitComplete = true;
650 mHandlerThread.notifyAll();
651 }
652 }
653
654 private class WakeLock implements IBinder.DeathRecipient
655 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700656 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 super();
658 flags = f;
659 binder = b;
660 tag = t;
661 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700662 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 if (u != MY_UID || (
664 !"KEEP_SCREEN_ON_FLAG".equals(tag)
665 && !"KeyInputQueue".equals(tag))) {
666 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
667 ? BatteryStats.WAKE_TYPE_PARTIAL
668 : BatteryStats.WAKE_TYPE_FULL;
669 } else {
670 monitorType = -1;
671 }
672 try {
673 b.linkToDeath(this, 0);
674 } catch (RemoteException e) {
675 binderDied();
676 }
677 }
678 public void binderDied() {
679 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500680 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682 }
683 final int flags;
684 final IBinder binder;
685 final String tag;
686 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400687 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700689 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 boolean activated = true;
691 int minState;
692 }
693
694 private void updateWakeLockLocked() {
695 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
696 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
697 mStayOnWhilePluggedInScreenDimLock.acquire();
698 mStayOnWhilePluggedInPartialLock.acquire();
699 } else {
700 mStayOnWhilePluggedInScreenDimLock.release();
701 mStayOnWhilePluggedInPartialLock.release();
702 }
703 }
704
705 private boolean isScreenLock(int flags)
706 {
707 int n = flags & LOCK_MASK;
708 return n == PowerManager.FULL_WAKE_LOCK
709 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400710 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
711 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700714 void enforceWakeSourcePermission(int uid, int pid) {
715 if (uid == Process.myUid()) {
716 return;
717 }
718 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
719 pid, uid, null);
720 }
721
722 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700724 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700725 if (uid != Process.myUid()) {
726 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
727 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700728 if (ws != null) {
729 enforceWakeSourcePermission(uid, pid);
730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 long ident = Binder.clearCallingIdentity();
732 try {
733 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700734 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736 } finally {
737 Binder.restoreCallingIdentity(ident);
738 }
739 }
740
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700741 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700742 if (wl.monitorType >= 0) {
743 long origId = Binder.clearCallingIdentity();
744 try {
745 if (ws != null) {
746 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
747 wl.monitorType);
748 } else {
749 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
750 }
751 } catch (RemoteException e) {
752 // Ignore
753 } finally {
754 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700755 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700756 }
757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700759 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700760 if (wl.monitorType >= 0) {
761 long origId = Binder.clearCallingIdentity();
762 try {
763 if (ws != null) {
764 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
765 wl.monitorType);
766 } else {
767 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
768 }
769 } catch (RemoteException e) {
770 // Ignore
771 } finally {
772 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700773 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700774 }
775 }
776
777 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
778 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800780 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700783 if (ws != null && ws.size() == 0) {
784 ws = null;
785 }
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 int index = mLocks.getIndex(lock);
788 WakeLock wl;
789 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 boolean diffsource;
791 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700793 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 switch (wl.flags & LOCK_MASK)
795 {
796 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500797 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400798 wl.minState = SCREEN_BRIGHT;
799 } else {
800 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 break;
803 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
804 wl.minState = SCREEN_BRIGHT;
805 break;
806 case PowerManager.SCREEN_DIM_WAKE_LOCK:
807 wl.minState = SCREEN_DIM;
808 break;
809 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700810 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 break;
812 default:
813 // just log and bail. we're in the server, so don't
814 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800815 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 + " flags=" + flags);
817 return;
818 }
819 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700820 if (ws != null) {
821 wl.ws = new WorkSource(ws);
822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700824 diffsource = false;
825 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 } else {
827 wl = mLocks.get(index);
828 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700829 oldsource = wl.ws;
830 if (oldsource != null) {
831 if (ws == null) {
832 wl.ws = null;
833 diffsource = true;
834 } else {
835 diffsource = oldsource.diff(ws);
836 }
837 } else if (ws != null) {
838 diffsource = true;
839 } else {
840 diffsource = false;
841 }
842 if (diffsource) {
843 wl.ws = new WorkSource(ws);
844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846 if (isScreenLock(flags)) {
847 // if this causes a wakeup, we reactivate all of the locks and
848 // set it to whatever they want. otherwise, we modulate that
849 // by the current state so we never turn it more on than
850 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400851 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
852 mProximityWakeLockCount++;
853 if (mProximityWakeLockCount == 1) {
854 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400857 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
858 int oldWakeLockState = mWakeLockState;
859 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400860
861 // Disable proximity sensor if if user presses power key while we are in the
862 // "waiting for proximity sensor to go negative" state.
863 if ((mWakeLockState & SCREEN_ON_BIT) != 0
864 && mProximitySensorActive && mProximityWakeLockCount == 0) {
865 mProximitySensorActive = false;
866 }
867
Joe Onorato8274a0e2010-10-05 17:38:09 -0400868 if (mSpew) {
869 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
870 + " mWakeLockState=0x"
871 + Integer.toHexString(mWakeLockState)
872 + " previous wakeLockState=0x"
873 + Integer.toHexString(oldWakeLockState));
874 }
875 } else {
876 if (mSpew) {
877 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
878 + " mLocks.gatherState()=0x"
879 + Integer.toHexString(mLocks.gatherState())
880 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
881 }
882 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400884 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
887 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
888 if (newlock) {
889 mPartialCount++;
890 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800891 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
893 }
894 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700897 if (diffsource) {
898 // If the lock sources have changed, need to first release the
899 // old ones.
900 noteStopWakeLocked(wl, oldsource);
901 }
902 if (newlock || diffsource) {
903 noteStartWakeLocked(wl, ws);
904 }
905 }
906
907 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
908 int uid = Binder.getCallingUid();
909 int pid = Binder.getCallingPid();
910 if (ws != null && ws.size() == 0) {
911 ws = null;
912 }
913 if (ws != null) {
914 enforceWakeSourcePermission(uid, pid);
915 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700916 synchronized (mLocks) {
917 int index = mLocks.getIndex(lock);
918 if (index < 0) {
919 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700921 WakeLock wl = mLocks.get(index);
922 WorkSource oldsource = wl.ws;
923 wl.ws = ws != null ? new WorkSource(ws) : null;
924 noteStopWakeLocked(wl, oldsource);
925 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927 }
928
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500929 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700930 int uid = Binder.getCallingUid();
931 if (uid != Process.myUid()) {
932 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934
935 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500936 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938 }
939
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500940 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 WakeLock wl = mLocks.removeLock(lock);
942 if (wl == null) {
943 return;
944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800947 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
949 }
950
951 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400952 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
953 mProximityWakeLockCount--;
954 if (mProximityWakeLockCount == 0) {
955 if (mProximitySensorActive &&
956 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
957 // wait for proximity sensor to go negative before disabling sensor
958 if (mDebugProximitySensor) {
959 Slog.d(TAG, "waiting for proximity sensor to go negative");
960 }
961 } else {
962 disableProximityLockLocked();
963 }
964 }
965 } else {
966 mWakeLockState = mLocks.gatherState();
967 // goes in the middle to reduce flicker
968 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
969 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
970 }
971 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
975 mPartialCount--;
976 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800977 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 Power.releaseWakeLock(PARTIAL_NAME);
979 }
980 }
981 // Unlink the lock from the binder.
982 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983
Dianne Hackborn70be1672010-09-14 11:13:03 -0700984 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 private class PokeLock implements IBinder.DeathRecipient
988 {
989 PokeLock(int p, IBinder b, String t) {
990 super();
991 this.pokey = p;
992 this.binder = b;
993 this.tag = t;
994 try {
995 b.linkToDeath(this, 0);
996 } catch (RemoteException e) {
997 binderDied();
998 }
999 }
1000 public void binderDied() {
1001 setPokeLock(0, this.binder, this.tag);
1002 }
1003 int pokey;
1004 IBinder binder;
1005 String tag;
1006 boolean awakeOnSet;
1007 }
1008
1009 public void setPokeLock(int pokey, IBinder token, String tag) {
1010 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1011 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001012 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 return;
1014 }
1015
1016 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1017 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1018 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1019 }
1020
1021 synchronized (mLocks) {
1022 if (pokey != 0) {
1023 PokeLock p = mPokeLocks.get(token);
1024 int oldPokey = 0;
1025 if (p != null) {
1026 oldPokey = p.pokey;
1027 p.pokey = pokey;
1028 } else {
1029 p = new PokeLock(pokey, token, tag);
1030 mPokeLocks.put(token, p);
1031 }
1032 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1033 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1034 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1035 p.awakeOnSet = true;
1036 }
1037 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001038 PokeLock rLock = mPokeLocks.remove(token);
1039 if (rLock != null) {
1040 token.unlinkToDeath(rLock, 0);
1041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
1044 int oldPokey = mPokey;
1045 int cumulative = 0;
1046 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1047 boolean awakeOnSet = false;
1048 for (PokeLock p: mPokeLocks.values()) {
1049 cumulative |= p.pokey;
1050 if (p.awakeOnSet) {
1051 awakeOnSet = true;
1052 }
1053 }
1054 mPokey = cumulative;
1055 mPokeAwakeOnSet = awakeOnSet;
1056
1057 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1058 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 if (oldCumulativeTimeout != newCumulativeTimeout) {
1061 setScreenOffTimeoutsLocked();
1062 // reset the countdown timer, but use the existing nextState so it doesn't
1063 // change anything
1064 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1065 }
1066 }
1067 }
1068
1069 private static String lockType(int type)
1070 {
1071 switch (type)
1072 {
1073 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001074 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001076 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001078 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001080 return "PARTIAL_WAKE_LOCK ";
1081 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1082 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 default:
David Brown251faa62009-08-02 22:04:36 -07001084 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086 }
1087
1088 private static String dumpPowerState(int state) {
1089 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1090 ? "KEYBOARD_BRIGHT_BIT " : "")
1091 + (((state & SCREEN_BRIGHT_BIT) != 0)
1092 ? "SCREEN_BRIGHT_BIT " : "")
1093 + (((state & SCREEN_ON_BIT) != 0)
1094 ? "SCREEN_ON_BIT " : "")
1095 + (((state & BATTERY_LOW_BIT) != 0)
1096 ? "BATTERY_LOW_BIT " : "");
1097 }
1098
1099 @Override
1100 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1101 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1102 != PackageManager.PERMISSION_GRANTED) {
1103 pw.println("Permission Denial: can't dump PowerManager from from pid="
1104 + Binder.getCallingPid()
1105 + ", uid=" + Binder.getCallingUid());
1106 return;
1107 }
1108
1109 long now = SystemClock.uptimeMillis();
1110
Mike Lockwoodca44df82010-02-25 13:48:49 -05001111 synchronized (mLocks) {
1112 pw.println("Power Manager State:");
1113 pw.println(" mIsPowered=" + mIsPowered
1114 + " mPowerState=" + mPowerState
1115 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1116 + " ms");
1117 pw.println(" mPartialCount=" + mPartialCount);
1118 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1119 pw.println(" mUserState=" + dumpPowerState(mUserState));
1120 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1121 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1122 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1123 + " " + ((mNextTimeout-now)/1000) + "s from now");
1124 pw.println(" mDimScreen=" + mDimScreen
1125 + " mStayOnConditions=" + mStayOnConditions);
1126 pw.println(" mScreenOffReason=" + mScreenOffReason
1127 + " mUserState=" + mUserState);
1128 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1129 + ',' + mBroadcastQueue[2] + "}");
1130 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1131 + ',' + mBroadcastWhy[2] + "}");
1132 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1133 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1134 + " mUserActivityAllowed=" + mUserActivityAllowed);
1135 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1136 + " mScreenOffDelay=" + mScreenOffDelay);
1137 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1138 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1139 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1140 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1141 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1142 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1143 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1144 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1145 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1146 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1147 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1148 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1149 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1150 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1151 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1152 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1153 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1154 pw.println(" mLightSensorValue=" + mLightSensorValue
1155 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001156 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1157 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001158 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1159 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1160 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1161 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1162 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1163 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001164
Mike Lockwoodca44df82010-02-25 13:48:49 -05001165 int N = mLocks.size();
1166 pw.println();
1167 pw.println("mLocks.size=" + N + ":");
1168 for (int i=0; i<N; i++) {
1169 WakeLock wl = mLocks.get(i);
1170 String type = lockType(wl.flags & LOCK_MASK);
1171 String acquireCausesWakeup = "";
1172 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1173 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1174 }
1175 String activated = "";
1176 if (wl.activated) {
1177 activated = " activated";
1178 }
1179 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001180 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1181 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001183
1184 pw.println();
1185 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1186 for (PokeLock p: mPokeLocks.values()) {
1187 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001188 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1189 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001190 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1191 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1192 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1193 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001195
Mike Lockwoodca44df82010-02-25 13:48:49 -05001196 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199
Joe Onorato7999bff2010-07-24 11:50:05 -04001200 private void setTimeoutLocked(long now, int nextState) {
1201 setTimeoutLocked(now, -1, nextState);
1202 }
1203
1204 // If they gave a timeoutOverride it is the number of seconds
1205 // to screen-off. Figure out where in the countdown cycle we
1206 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001207 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1208 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001209 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001210 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001211 long when = 0;
1212 if (timeoutOverride <= 0) {
1213 switch (nextState)
1214 {
1215 case SCREEN_BRIGHT:
1216 when = now + mKeylightDelay;
1217 break;
1218 case SCREEN_DIM:
1219 if (mDimDelay >= 0) {
1220 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001221 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001222 } else {
1223 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1224 }
1225 case SCREEN_OFF:
1226 synchronized (mLocks) {
1227 when = now + mScreenOffDelay;
1228 }
1229 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001230 default:
1231 when = now;
1232 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001234 } else {
1235 override: {
1236 if (timeoutOverride <= mScreenOffDelay) {
1237 when = now + timeoutOverride;
1238 nextState = SCREEN_OFF;
1239 break override;
1240 }
1241 timeoutOverride -= mScreenOffDelay;
1242
1243 if (mDimDelay >= 0) {
1244 if (timeoutOverride <= mDimDelay) {
1245 when = now + timeoutOverride;
1246 nextState = SCREEN_DIM;
1247 break override;
1248 }
1249 timeoutOverride -= mDimDelay;
1250 }
1251
1252 when = now + timeoutOverride;
1253 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001255 }
1256 if (mSpew) {
1257 Slog.d(TAG, "setTimeoutLocked now=" + now
1258 + " timeoutOverride=" + timeoutOverride
1259 + " nextState=" + nextState + " when=" + when);
1260 }
Joe Onorato797e6882010-08-26 14:46:01 -04001261
1262 mHandler.removeCallbacks(mTimeoutTask);
1263 mTimeoutTask.nextState = nextState;
1264 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1265 ? (originalTimeoutOverride - timeoutOverride)
1266 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001267 mHandler.postAtTime(mTimeoutTask, when);
1268 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271 }
1272
1273 private void cancelTimerLocked()
1274 {
1275 mHandler.removeCallbacks(mTimeoutTask);
1276 mTimeoutTask.nextState = -1;
1277 }
1278
1279 private class TimeoutTask implements Runnable
1280 {
1281 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001282 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 public void run()
1284 {
1285 synchronized (mLocks) {
1286 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001287 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
1289
1290 if (nextState == -1) {
1291 return;
1292 }
1293
1294 mUserState = this.nextState;
1295 setPowerState(this.nextState | mWakeLockState);
1296
1297 long now = SystemClock.uptimeMillis();
1298
1299 switch (this.nextState)
1300 {
1301 case SCREEN_BRIGHT:
1302 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001303 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 break;
1305 }
1306 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001307 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 break;
1309 }
1310 }
1311 }
1312 }
1313
1314 private void sendNotificationLocked(boolean on, int why)
1315 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001316 if (!on) {
1317 mStillNeedSleepNotification = false;
1318 }
1319
Joe Onorato128e7292009-03-24 18:41:31 -07001320 // Add to the queue.
1321 int index = 0;
1322 while (mBroadcastQueue[index] != -1) {
1323 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
Joe Onorato128e7292009-03-24 18:41:31 -07001325 mBroadcastQueue[index] = on ? 1 : 0;
1326 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327
Joe Onorato128e7292009-03-24 18:41:31 -07001328 // If we added it position 2, then there is a pair that can be stripped.
1329 // If we added it position 1 and we're turning the screen off, we can strip
1330 // the pair and do nothing, because the screen is already off, and therefore
1331 // keyguard has already been enabled.
1332 // However, if we added it at position 1 and we're turning it on, then position
1333 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1334 // on, so have to run the queue then.
1335 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001336 // While we're collapsing them, if it's going off, and the new reason
1337 // is more significant than the first, then use the new one.
1338 if (!on && mBroadcastWhy[0] > why) {
1339 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001340 }
1341 mBroadcastQueue[0] = on ? 1 : 0;
1342 mBroadcastQueue[1] = -1;
1343 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001344 mBroadcastWakeLock.release();
1345 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001346 index = 0;
1347 }
1348 if (index == 1 && !on) {
1349 mBroadcastQueue[0] = -1;
1350 mBroadcastQueue[1] = -1;
1351 index = -1;
1352 // The wake lock was being held, but we're not actually going to do any
1353 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001354 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001356 }
1357
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001358 // The broadcast queue has changed; make sure the screen is on if it
1359 // is now possible for it to be.
1360 updateNativePowerStateLocked();
1361
Joe Onorato128e7292009-03-24 18:41:31 -07001362 // Now send the message.
1363 if (index >= 0) {
1364 // Acquire the broadcast wake lock before changing the power
1365 // state. It will be release after the broadcast is sent.
1366 // We always increment the ref count for each notification in the queue
1367 // and always decrement when that notification is handled.
1368 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001369 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001370 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 }
1372 }
1373
1374 private Runnable mNotificationTask = new Runnable()
1375 {
1376 public void run()
1377 {
Joe Onorato128e7292009-03-24 18:41:31 -07001378 while (true) {
1379 int value;
1380 int why;
1381 WindowManagerPolicy policy;
1382 synchronized (mLocks) {
1383 value = mBroadcastQueue[0];
1384 why = mBroadcastWhy[0];
1385 for (int i=0; i<2; i++) {
1386 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1387 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1388 }
1389 policy = getPolicyLocked();
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001390 if (value == 0) {
1391 mBroadcastingScreenOff = true;
1392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
Joe Onorato128e7292009-03-24 18:41:31 -07001394 if (value == 1) {
1395 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001396
Joe Onorato128e7292009-03-24 18:41:31 -07001397 policy.screenTurnedOn();
1398 try {
1399 ActivityManagerNative.getDefault().wakingUp();
1400 } catch (RemoteException e) {
1401 // ignore it
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403
Joe Onorato128e7292009-03-24 18:41:31 -07001404 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001405 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001406 }
1407 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1408 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1409 mScreenOnBroadcastDone, mHandler, 0, null, null);
1410 } else {
1411 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001412 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001413 mBroadcastWakeLock.mCount);
1414 mBroadcastWakeLock.release();
1415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417 }
Joe Onorato128e7292009-03-24 18:41:31 -07001418 else if (value == 0) {
1419 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001420
Joe Onorato128e7292009-03-24 18:41:31 -07001421 policy.screenTurnedOff(why);
1422 try {
1423 ActivityManagerNative.getDefault().goingToSleep();
1424 } catch (RemoteException e) {
1425 // ignore it.
1426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
Joe Onorato128e7292009-03-24 18:41:31 -07001428 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1429 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1430 mScreenOffBroadcastDone, mHandler, 0, null, null);
1431 } else {
1432 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001433 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001434 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001435 mBroadcastingScreenOff = false;
1436 updateNativePowerStateLocked();
Joe Onorato128e7292009-03-24 18:41:31 -07001437 mBroadcastWakeLock.release();
1438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 }
Joe Onorato128e7292009-03-24 18:41:31 -07001441 else {
1442 // If we're in this case, then this handler is running for a previous
1443 // paired transaction. mBroadcastWakeLock will already have been released.
1444 break;
1445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447 }
1448 };
1449
1450 long mScreenOnStart;
1451 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1452 public void onReceive(Context context, Intent intent) {
1453 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1456 mBroadcastWakeLock.release();
1457 }
1458 }
1459 };
1460
1461 long mScreenOffStart;
1462 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1463 public void onReceive(Context context, Intent intent) {
1464 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001467 synchronized (mLocks) {
1468 mBroadcastingScreenOff = false;
1469 updateNativePowerStateLocked();
1470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 mBroadcastWakeLock.release();
1472 }
1473 }
1474 };
1475
1476 void logPointerUpEvent() {
1477 if (LOG_TOUCH_DOWNS) {
1478 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1479 mLastTouchDown = 0;
1480 }
1481 }
1482
1483 void logPointerDownEvent() {
1484 if (LOG_TOUCH_DOWNS) {
1485 // If we are not already timing a down/up sequence
1486 if (mLastTouchDown == 0) {
1487 mLastTouchDown = SystemClock.elapsedRealtime();
1488 mTouchCycles++;
1489 }
1490 }
1491 }
1492
1493 /**
1494 * Prevents the screen from turning on even if it *should* turn on due
1495 * to a subsequent full wake lock being acquired.
1496 * <p>
1497 * This is a temporary hack that allows an activity to "cover up" any
1498 * display glitches that happen during the activity's startup
1499 * sequence. (Specifically, this API was added to work around a
1500 * cosmetic bug in the "incoming call" sequence, where the lock screen
1501 * would flicker briefly before the incoming call UI became visible.)
1502 * TODO: There ought to be a more elegant way of doing this,
1503 * probably by having the PowerManager and ActivityManager
1504 * work together to let apps specify that the screen on/off
1505 * state should be synchronized with the Activity lifecycle.
1506 * <p>
1507 * Note that calling preventScreenOn(true) will NOT turn the screen
1508 * off if it's currently on. (This API only affects *future*
1509 * acquisitions of full wake locks.)
1510 * But calling preventScreenOn(false) WILL turn the screen on if
1511 * it's currently off because of a prior preventScreenOn(true) call.
1512 * <p>
1513 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1514 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1515 * call doesn't occur within 5 seconds, we'll turn the screen back on
1516 * ourselves (and log a warning about it); this prevents a buggy app
1517 * from disabling the screen forever.)
1518 * <p>
1519 * TODO: this feature should really be controlled by a new type of poke
1520 * lock (rather than an IPowerManager call).
1521 */
1522 public void preventScreenOn(boolean prevent) {
1523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1524
1525 synchronized (mLocks) {
1526 if (prevent) {
1527 // First of all, grab a partial wake lock to
1528 // make sure the CPU stays on during the entire
1529 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1530 mPreventScreenOnPartialLock.acquire();
1531
1532 // Post a forceReenableScreen() call (for 5 seconds in the
1533 // future) to make sure the matching preventScreenOn(false) call
1534 // has happened by then.
1535 mHandler.removeCallbacks(mForceReenableScreenTask);
1536 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1537
1538 // Finally, set the flag that prevents the screen from turning on.
1539 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001540 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 mPreventScreenOn = true;
1542 } else {
1543 // (Re)enable the screen.
1544 mPreventScreenOn = false;
1545
1546 // We're "undoing" a the prior preventScreenOn(true) call, so we
1547 // no longer need the 5-second safeguard.
1548 mHandler.removeCallbacks(mForceReenableScreenTask);
1549
1550 // Forcibly turn on the screen if it's supposed to be on. (This
1551 // handles the case where the screen is currently off because of
1552 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001553 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001555 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1557 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001558 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562 }
1563
1564 // Release the partial wake lock that we held during the
1565 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1566 mPreventScreenOnPartialLock.release();
1567 }
1568 }
1569 }
1570
1571 public void setScreenBrightnessOverride(int brightness) {
1572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1573
Mike Lockwoodf527c712010-06-10 14:12:33 -04001574 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 synchronized (mLocks) {
1576 if (mScreenBrightnessOverride != brightness) {
1577 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001578 if (isScreenOn()) {
1579 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
1582 }
1583 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001584
1585 public void setButtonBrightnessOverride(int brightness) {
1586 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1587
Mike Lockwoodf527c712010-06-10 14:12:33 -04001588 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001589 synchronized (mLocks) {
1590 if (mButtonBrightnessOverride != brightness) {
1591 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001592 if (isScreenOn()) {
1593 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1594 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001595 }
1596 }
1597 }
1598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 /**
1600 * Sanity-check that gets called 5 seconds after any call to
1601 * preventScreenOn(true). This ensures that the original call
1602 * is followed promptly by a call to preventScreenOn(false).
1603 */
1604 private void forceReenableScreen() {
1605 // We shouldn't get here at all if mPreventScreenOn is false, since
1606 // we should have already removed any existing
1607 // mForceReenableScreenTask messages...
1608 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001609 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 return;
1611 }
1612
1613 // Uh oh. It's been 5 seconds since a call to
1614 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1615 // This means the app that called preventScreenOn(true) is either
1616 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1617 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1618 // crashed before doing so.)
1619
1620 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 + "Forcing the screen back on...");
1623 preventScreenOn(false);
1624 }
1625
1626 private Runnable mForceReenableScreenTask = new Runnable() {
1627 public void run() {
1628 forceReenableScreen();
1629 }
1630 };
1631
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001632 private int setScreenStateLocked(boolean on) {
1633 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001634 if (err == 0) {
1635 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1636 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001637 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001638 if (!on) {
1639 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001640 mButtonLight.turnOff();
1641 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001642 // clear current value so we will update based on the new conditions
1643 // when the sensor is reenabled.
1644 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001645 // reset our highest light sensor value when the screen turns off
1646 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001647 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001648 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001649 }
1650 return err;
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 private void setPowerState(int state)
1654 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001655 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
Mike Lockwood435eb642009-12-03 08:40:18 -05001658 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 {
1660 synchronized (mLocks) {
1661 int err;
1662
1663 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001664 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001666 + " noChangeLights=" + noChangeLights
1667 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
1670 if (noChangeLights) {
1671 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1672 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001673 if (mProximitySensorActive) {
1674 // don't turn on the screen when the proximity sensor lock is held
1675 newState = (newState & ~SCREEN_BRIGHT);
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677
1678 if (batteryIsLow()) {
1679 newState |= BATTERY_LOW_BIT;
1680 } else {
1681 newState &= ~BATTERY_LOW_BIT;
1682 }
1683 if (newState == mPowerState) {
1684 return;
1685 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001686
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001687 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 newState |= ALL_BRIGHT;
1689 }
1690
1691 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1692 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1693
Mike Lockwood51b844962009-11-16 21:51:18 -05001694 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001695 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001699 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001701 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1707 }
1708
1709 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001710 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1712 }
1713
1714 if (oldScreenOn != newScreenOn) {
1715 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001716 // When the user presses the power button, we need to always send out the
1717 // notification that it's going to sleep so the keyguard goes on. But
1718 // we can't do that until the screen fades out, so we don't show the keyguard
1719 // too early.
1720 if (mStillNeedSleepNotification) {
1721 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1722 }
1723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 // Turn on the screen UNLESS there was a prior
1725 // preventScreenOn(true) request. (Note that the lifetime
1726 // of a single preventScreenOn() request is limited to 5
1727 // seconds to prevent a buggy app from disabling the
1728 // screen forever; see forceReenableScreen().)
1729 boolean reallyTurnScreenOn = true;
1730 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001731 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 + mPreventScreenOn);
1733 }
1734
1735 if (mPreventScreenOn) {
1736 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001737 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739 reallyTurnScreenOn = false;
1740 }
1741 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001742 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 long identity = Binder.clearCallingIdentity();
1744 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001745 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 mBatteryStats.noteScreenOn();
1747 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001748 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 } finally {
1750 Binder.restoreCallingIdentity(identity);
1751 }
1752 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001753 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 // But continue as if we really did turn the screen on...
1755 err = 0;
1756 }
1757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 mLastTouchDown = 0;
1759 mTotalTouchDownTime = 0;
1760 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001761 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 mTotalTouchDownTime, mTouchCycles);
1763 if (err == 0) {
1764 mPowerState |= SCREEN_ON_BIT;
1765 sendNotificationLocked(true, -1);
1766 }
1767 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001768 // cancel light sensor task
1769 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001770 mLightSensorPendingDecrease = false;
1771 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 mScreenOffTime = SystemClock.elapsedRealtime();
1773 long identity = Binder.clearCallingIdentity();
1774 try {
1775 mBatteryStats.noteScreenOff();
1776 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001777 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 } finally {
1779 Binder.restoreCallingIdentity(identity);
1780 }
1781 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001782 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001784 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 err = 0;
1787 mLastTouchDown = 0;
1788 }
1789 }
1790 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001791
1792 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
1794 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001795
1796 private void updateNativePowerStateLocked() {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001797 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1798 // Don't turn screen on if we are currently reporting a screen off.
1799 // This is to avoid letting the screen go on before things like the
1800 // lock screen have been displayed due to it going off.
1801 if (mBroadcastingScreenOff) {
1802 // Currently broadcasting that the screen is off. Don't
1803 // allow screen to go on until that is done.
1804 return;
1805 }
1806 for (int i=0; i<mBroadcastQueue.length; i++) {
1807 if (mBroadcastQueue[i] == 0) {
1808 // A screen off is currently enqueued.
1809 return;
1810 }
1811 }
1812 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001813 nativeSetPowerState(
1814 (mPowerState & SCREEN_ON_BIT) != 0,
1815 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001817
Mike Lockwood435eb642009-12-03 08:40:18 -05001818 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001822 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1823 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001825 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001827 mScreenOffReason = reason;
1828 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 return err;
1831 }
1832
1833 private boolean batteryIsLow() {
1834 return (!mIsPowered &&
1835 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1836 }
1837
The Android Open Source Project10592532009-03-18 17:39:46 -07001838 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001839 final int oldState = mPowerState;
Joe Onorato60607a902010-10-23 14:49:30 -07001840 if ((newState & SCREEN_ON_BIT) != 0) {
1841 // Only turn on the buttons or keyboard if the screen is also on.
1842 // We should never see the buttons on but not the screen.
1843 newState = applyButtonState(newState);
1844 newState = applyKeyboardState(newState);
1845 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001846 final int realDifference = (newState ^ oldState);
1847 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001849 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 int offMask = 0;
1853 int dimMask = 0;
1854 int onMask = 0;
1855
1856 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001859 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1860 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001862 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864 }
1865
1866 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001867 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1868 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001870 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
1872 }
1873
1874 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001875 int nominalCurrentValue = -1;
1876 // If there was an actual difference in the light state, then
1877 // figure out the "ideal" current value based on the previous
1878 // state. Otherwise, this is a change due to the brightness
1879 // override, so we want to animate from whatever the current
1880 // value is.
1881 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1882 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1883 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1884 nominalCurrentValue = preferredBrightness;
1885 break;
1886 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001887 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001888 break;
1889 case 0:
1890 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1891 break;
1892 case SCREEN_BRIGHT_BIT:
1893 default:
1894 // not possible
1895 nominalCurrentValue = (int)mScreenBrightness.curValue;
1896 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001897 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001898 }
1899 int brightness = preferredBrightness;
1900 int steps = ANIM_STEPS;
1901 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1902 // dim or turn off backlight, depending on if the screen is on
1903 // the scale is because the brightness ramp isn't linear and this biases
1904 // it so the later parts take longer.
1905 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001906 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07001907 if (ratio > 1.0f) ratio = 1.0f;
1908 if ((newState & SCREEN_ON_BIT) == 0) {
1909 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1910 // was bright
1911 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001913 // was dim
1914 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001916 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001918 if ((oldState & SCREEN_ON_BIT) != 0) {
1919 // was bright
1920 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1921 } else {
1922 // was dim
1923 steps = (int)(ANIM_STEPS*ratio);
1924 }
1925 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1926 // If the "stay on while plugged in" option is
1927 // turned on, then the screen will often not
1928 // automatically turn off while plugged in. To
1929 // still have a sense of when it is inactive, we
1930 // will then count going dim as turning off.
1931 mScreenOffTime = SystemClock.elapsedRealtime();
1932 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001933 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
1935 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001936 long identity = Binder.clearCallingIdentity();
1937 try {
1938 mBatteryStats.noteScreenBrightness(brightness);
1939 } catch (RemoteException e) {
1940 // Nothing interesting to do.
1941 } finally {
1942 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001944 mScreenBrightness.setTargetLocked(brightness, steps,
1945 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001947
Joe Onorato60607a902010-10-23 14:49:30 -07001948 if (mSpew) {
1949 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1950 + " dimMask=0x" + Integer.toHexString(dimMask)
1951 + " onMask=0x" + Integer.toHexString(onMask)
1952 + " difference=0x" + Integer.toHexString(difference)
1953 + " realDifference=0x" + Integer.toHexString(realDifference)
1954 + " forceState=0x" + Integer.toHexString(forceState)
1955 );
1956 }
1957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001959 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001960 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
1962 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001963 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 if ((newState & BATTERY_LOW_BIT) != 0 &&
1965 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1966 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1967 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001968 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001969 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
1971 if (onMask != 0) {
1972 int brightness = getPreferredBrightness();
1973 if ((newState & BATTERY_LOW_BIT) != 0 &&
1974 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1975 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1976 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001977 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001978 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981
The Android Open Source Project10592532009-03-18 17:39:46 -07001982 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001983 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001984 ? LightsService.BRIGHTNESS_MODE_SENSOR
1985 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001986 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001987 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001988 }
1989 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001990 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001991 }
1992 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001993 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
1996
Joe Onoratob08a1af2010-10-11 19:28:58 -07001997 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 boolean initialized;
2001 int targetValue;
2002 float curValue;
2003 float delta;
2004 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 BrightnessState(int m) {
2007 mask = m;
2008 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 public void dump(PrintWriter pw, String prefix) {
2011 pw.println(prefix + "animating=" + animating
2012 + " targetValue=" + targetValue
2013 + " curValue=" + curValue
2014 + " delta=" + delta);
2015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002016
Joe Onoratob08a1af2010-10-11 19:28:58 -07002017 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002018 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 if (!initialized) {
2020 initialized = true;
2021 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002022 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002023 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
2025 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002026 delta = (targetValue -
2027 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2028 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07002030 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002031 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2032 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002033 + " nominalCurrentValue=" + nominalCurrentValue
2034 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
2036 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002037
2038 if (mSpew) {
2039 Slog.i(TAG, "scheduling light animator");
2040 }
2041 mScreenOffHandler.removeCallbacks(this);
2042 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 boolean stepLocked() {
2046 if (!animating) return false;
2047 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002048 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 + " target=" + targetValue + " delta=" + delta);
2050 }
2051 curValue += delta;
2052 int curIntValue = (int)curValue;
2053 boolean more = true;
2054 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002055 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 more = false;
2057 } else if (delta > 0) {
2058 if (curIntValue >= targetValue) {
2059 curValue = curIntValue = targetValue;
2060 more = false;
2061 }
2062 } else {
2063 if (curIntValue <= targetValue) {
2064 curValue = curIntValue = targetValue;
2065 more = false;
2066 }
2067 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002068 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002069 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002070 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002071 return more;
2072 }
2073
Joe Onorato3d3db602010-10-18 16:08:16 -04002074 void jumpToTargetLocked() {
2075 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002076 setLightBrightness(mask, targetValue);
2077 final int tv = targetValue;
2078 curValue = tv;
2079 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002080 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002081 }
2082
Joe Onorato3d3db602010-10-18 16:08:16 -04002083 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 animating = more;
2085 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002086 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002087 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002093 if (mAnimateScreenLights) {
2094 synchronized (mLocks) {
2095 long now = SystemClock.uptimeMillis();
2096 boolean more = mScreenBrightness.stepLocked();
2097 if (more) {
2098 mScreenOffHandler.postAtTime(this, now+(1000/60));
2099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002101 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002102 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002103 // we're turning off
2104 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2105 if (animate) {
2106 // It's pretty scary to hold mLocks for this long, and we should
2107 // redesign this, but it works for now.
2108 nativeStartSurfaceFlingerAnimation(
2109 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2110 ? 0 : mAnimationSetting);
2111 }
2112 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115 }
2116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 private int getPreferredBrightness() {
2119 try {
2120 if (mScreenBrightnessOverride >= 0) {
2121 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002122 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002123 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002124 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2127 SCREEN_BRIGHTNESS);
2128 // Don't let applications turn the screen all the way off
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002129 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 } catch (SettingNotFoundException snfe) {
2131 return Power.BRIGHTNESS_ON;
2132 }
2133 }
2134
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002135 private int applyButtonState(int state) {
2136 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002137 if ((state & BATTERY_LOW_BIT) != 0) {
2138 // do not override brightness if the battery is low
2139 return state;
2140 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002141 if (mButtonBrightnessOverride >= 0) {
2142 brightness = mButtonBrightnessOverride;
2143 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2144 brightness = mLightSensorButtonBrightness;
2145 }
2146 if (brightness > 0) {
2147 return state | BUTTON_BRIGHT_BIT;
2148 } else if (brightness == 0) {
2149 return state & ~BUTTON_BRIGHT_BIT;
2150 } else {
2151 return state;
2152 }
2153 }
2154
2155 private int applyKeyboardState(int state) {
2156 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002157 if ((state & BATTERY_LOW_BIT) != 0) {
2158 // do not override brightness if the battery is low
2159 return state;
2160 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002161 if (!mKeyboardVisible) {
2162 brightness = 0;
2163 } else if (mButtonBrightnessOverride >= 0) {
2164 brightness = mButtonBrightnessOverride;
2165 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2166 brightness = mLightSensorKeyboardBrightness;
2167 }
2168 if (brightness > 0) {
2169 return state | KEYBOARD_BRIGHT_BIT;
2170 } else if (brightness == 0) {
2171 return state & ~KEYBOARD_BRIGHT_BIT;
2172 } else {
2173 return state;
2174 }
2175 }
2176
Charles Mendis322591c2009-10-29 11:06:59 -07002177 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 synchronized (mLocks) {
2179 return (mPowerState & SCREEN_ON_BIT) != 0;
2180 }
2181 }
2182
Charles Mendis322591c2009-10-29 11:06:59 -07002183 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 synchronized (mLocks) {
2185 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2186 }
2187 }
2188
Mike Lockwood497087e32009-11-08 18:33:03 -05002189 private boolean isScreenTurningOffLocked() {
2190 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2191 }
2192
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002193 private boolean shouldLog(long time) {
2194 synchronized (mLocks) {
2195 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2196 mWarningSpewThrottleTime = time;
2197 mWarningSpewThrottleCount = 0;
2198 return true;
2199 } else if (mWarningSpewThrottleCount < 30) {
2200 mWarningSpewThrottleCount++;
2201 return true;
2202 } else {
2203 return false;
2204 }
2205 }
2206 }
2207
Mike Lockwood200b30b2009-09-20 00:23:59 -04002208 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002209 if (isScreenTurningOffLocked()) {
2210 // cancel animation so userActivity will succeed
2211 mScreenBrightness.animating = false;
2212 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002213 boolean savedActivityAllowed = mUserActivityAllowed;
2214 mUserActivityAllowed = true;
2215 userActivity(SystemClock.uptimeMillis(), false);
2216 mUserActivityAllowed = savedActivityAllowed;
2217 }
2218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2220 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002221 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 }
2223
2224 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002225 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2226 != PackageManager.PERMISSION_GRANTED) {
2227 if (shouldLog(time)) {
2228 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2229 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2230 }
2231 return;
2232 }
2233
Joe Onorato7999bff2010-07-24 11:50:05 -04002234 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236
2237 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002238 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240
2241 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002242 userActivity(time, -1, noChangeLights, eventType, force);
2243 }
2244
2245 /*
2246 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2247 * on with user activity. Don't use this function.
2248 */
2249 public void clearUserActivityTimeout(long now, long timeout) {
2250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2251 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2252 userActivity(now, timeout, false, OTHER_EVENT, false);
2253 }
2254
2255 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2256 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257
Joe Onorato1a542c72010-11-08 09:48:20 -08002258 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002259 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002260 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002261 }
2262 return;
2263 }
2264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 synchronized (mLocks) {
2266 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002267 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 + " mUserActivityAllowed=" + mUserActivityAllowed
2269 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002270 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2271 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002272 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002273 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 }
Mike Lockwood05067122009-10-27 23:07:25 -04002275 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002276 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002277 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002278 return;
2279 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002280 // Disable proximity sensor if if user presses power key while we are in the
2281 // "waiting for proximity sensor to go negative" state.
2282 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2283 mProximitySensorActive = false;
2284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 if (mLastEventTime <= time || force) {
2286 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002287 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002288 // Only turn on button backlights if a button was pressed
2289 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002290 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2292 } else {
2293 // don't clear button/keyboard backlights when the screen is touched.
2294 mUserState |= SCREEN_BRIGHT;
2295 }
2296
Dianne Hackborn617f8772009-03-31 15:04:46 -07002297 int uid = Binder.getCallingUid();
2298 long ident = Binder.clearCallingIdentity();
2299 try {
2300 mBatteryStats.noteUserActivity(uid, eventType);
2301 } catch (RemoteException e) {
2302 // Ignore
2303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002306
Michael Chane96440f2009-05-06 10:27:36 -07002307 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002308 setPowerState(mUserState | mWakeLockState, noChangeLights,
2309 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002310 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312 }
2313 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002314
2315 if (mPolicy != null) {
2316 mPolicy.userActivity();
2317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002320 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2321 try {
2322 int i;
2323 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2324 if (sensorValue < mAutoBrightnessLevels[i]) {
2325 break;
2326 }
2327 }
2328 return values[i];
2329 } catch (Exception e) {
2330 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002331 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002332 return 255;
2333 }
2334 }
2335
Mike Lockwood20f87d72009-11-05 16:08:51 -05002336 private Runnable mProximityTask = new Runnable() {
2337 public void run() {
2338 synchronized (mLocks) {
2339 if (mProximityPendingValue != -1) {
2340 proximityChangedLocked(mProximityPendingValue == 1);
2341 mProximityPendingValue = -1;
2342 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002343 if (mProximityPartialLock.isHeld()) {
2344 mProximityPartialLock.release();
2345 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002346 }
2347 }
2348 };
2349
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002350 private Runnable mAutoBrightnessTask = new Runnable() {
2351 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002352 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002353 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2354 int value = (int)mLightSensorPendingValue;
2355 mLightSensorPendingDecrease = false;
2356 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002357 lightSensorChangedLocked(value);
2358 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002359 }
2360 }
2361 };
2362
Mike Lockwoodb2865412010-02-02 22:40:33 -05002363 private void dockStateChanged(int state) {
2364 synchronized (mLocks) {
2365 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2366 if (mIsDocked) {
2367 mHighestLightSensorValue = -1;
2368 }
2369 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2370 // force lights recalculation
2371 int value = (int)mLightSensorValue;
2372 mLightSensorValue = -1;
2373 lightSensorChangedLocked(value);
2374 }
2375 }
2376 }
2377
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002378 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002379 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002380 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002381 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002382
Joe Onorato06eb33a2010-10-25 14:09:21 -07002383 // Don't do anything if the screen is off.
2384 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2385 if (mDebugLightSensor) {
2386 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2387 }
2388 return;
2389 }
2390
Mike Lockwoodb2865412010-02-02 22:40:33 -05002391 // do not allow light sensor value to decrease
2392 if (mHighestLightSensorValue < value) {
2393 mHighestLightSensorValue = value;
2394 }
2395
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002396 if (mLightSensorValue != value) {
2397 mLightSensorValue = value;
2398 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002399 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2400 // we only do this if we are undocked, since lighting should be stable when
2401 // stationary in a dock.
2402 int lcdValue = getAutoBrightnessValue(
2403 (mIsDocked ? value : mHighestLightSensorValue),
2404 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002405 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002406 int keyboardValue;
2407 if (mKeyboardVisible) {
2408 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2409 } else {
2410 keyboardValue = 0;
2411 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002412 mLightSensorScreenBrightness = lcdValue;
2413 mLightSensorButtonBrightness = buttonValue;
2414 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002415
2416 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002417 Slog.d(TAG, "lcdValue " + lcdValue);
2418 Slog.d(TAG, "buttonValue " + buttonValue);
2419 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002420 }
2421
Mike Lockwood4984e732009-11-01 08:16:33 -05002422 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002423 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2424 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002425 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002426 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002427 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002428 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002429 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002430 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002431 }
2432 }
2433 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002434 }
2435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 /**
2437 * The user requested that we go to sleep (probably with the power button).
2438 * This overrides all wake locks that are held.
2439 */
2440 public void goToSleep(long time)
2441 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002442 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2443 }
2444
2445 /**
2446 * The user requested that we go to sleep (probably with the power button).
2447 * This overrides all wake locks that are held.
2448 */
2449 public void goToSleepWithReason(long time, int reason)
2450 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2452 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002453 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002458 * Reboot the device immediately, passing 'reason' (may be null)
2459 * to the underlying __reboot system call. Should not return.
2460 */
2461 public void reboot(String reason)
2462 {
2463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002464
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002465 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2466 throw new IllegalStateException("Too early to call reboot()");
2467 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002468
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002469 final String finalReason = reason;
2470 Runnable runnable = new Runnable() {
2471 public void run() {
2472 synchronized (this) {
2473 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002474 }
2475
San Mehat1e512792010-01-07 10:40:29 -08002476 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002477 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002478 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002479 mHandler.post(runnable);
2480
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002481 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002482 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002483 while (true) {
2484 try {
2485 runnable.wait();
2486 } catch (InterruptedException e) {
2487 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002488 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002489 }
2490 }
2491
Dan Egnor60d87622009-12-16 16:32:58 -08002492 /**
2493 * Crash the runtime (causing a complete restart of the Android framework).
2494 * Requires REBOOT permission. Mostly for testing. Should not return.
2495 */
2496 public void crash(final String message)
2497 {
2498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2499 Thread t = new Thread("PowerManagerService.crash()") {
2500 public void run() { throw new RuntimeException(message); }
2501 };
2502 try {
2503 t.start();
2504 t.join();
2505 } catch (InterruptedException e) {
2506 Log.wtf(TAG, e);
2507 }
2508 }
2509
Mike Lockwood435eb642009-12-03 08:40:18 -05002510 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511
2512 if (mLastEventTime <= time) {
2513 mLastEventTime = time;
2514 // cancel all of the wake locks
2515 mWakeLockState = SCREEN_OFF;
2516 int N = mLocks.size();
2517 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002518 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 for (int i=0; i<N; i++) {
2520 WakeLock wl = mLocks.get(i);
2521 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002522 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2523 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2524 proxLock = true;
2525 } else {
2526 mLocks.get(i).activated = false;
2527 numCleared++;
2528 }
2529 }
2530 }
2531 if (!proxLock) {
2532 mProxIgnoredBecauseScreenTurnedOff = true;
2533 if (mDebugProximitySensor) {
2534 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002537 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002538 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002540 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 cancelTimerLocked();
2542 }
2543 }
2544
2545 public long timeSinceScreenOn() {
2546 synchronized (mLocks) {
2547 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2548 return 0;
2549 }
2550 return SystemClock.elapsedRealtime() - mScreenOffTime;
2551 }
2552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002555 synchronized (mLocks) {
2556 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002557 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002558 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002559 if (mKeyboardVisible != visible) {
2560 mKeyboardVisible = visible;
2561 // don't signal user activity if the screen is off; other code
2562 // will take care of turning on due to a true change to the lid
2563 // switch and synchronized with the lock screen.
2564 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002565 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002566 // force recompute of backlight values
2567 if (mLightSensorValue >= 0) {
2568 int value = (int)mLightSensorValue;
2569 mLightSensorValue = -1;
2570 lightSensorChangedLocked(value);
2571 }
2572 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002573 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2574 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002575 }
2576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 }
2578
2579 /**
2580 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002581 * When disabling user activity we also reset user power state so the keyguard can reset its
2582 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 */
2584 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002585 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002586 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 synchronized (mLocks) {
2589 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002590 if (!enabled) {
2591 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2592 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595 }
2596
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002597 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002598 synchronized (mLocks) {
2599 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2600 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2601 mAutoBrightessEnabled = enabled;
2602 // This will get us a new value
2603 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002604 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002605 }
2606 }
2607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 /** Sets the screen off timeouts:
2609 * mKeylightDelay
2610 * mDimDelay
2611 * mScreenOffDelay
2612 * */
2613 private void setScreenOffTimeoutsLocked() {
2614 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002615 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 mDimDelay = -1;
2617 mScreenOffDelay = 0;
2618 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2619 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2620 mDimDelay = -1;
2621 mScreenOffDelay = 0;
2622 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002623 int totalDelay = mScreenOffTimeoutSetting;
2624 if (totalDelay > mMaximumScreenOffTimeout) {
2625 totalDelay = mMaximumScreenOffTimeout;
2626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2628 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002629 // negative number means stay on as long as possible.
2630 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 } else if (mKeylightDelay < totalDelay) {
2632 // subtract the time that the keylight delay. This will give us the
2633 // remainder of the time that we need to sleep to get the accurate
2634 // screen off timeout.
2635 mScreenOffDelay = totalDelay - mKeylightDelay;
2636 } else {
2637 mScreenOffDelay = 0;
2638 }
2639 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2640 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2641 mScreenOffDelay = LONG_DIM_TIME;
2642 } else {
2643 mDimDelay = -1;
2644 }
2645 }
2646 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002647 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2649 + " mDimScreen=" + mDimScreen);
2650 }
2651 }
2652
2653 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002654 * Refreshes cached secure settings. Called once on startup, and
2655 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 */
Doug Zongker43866e02010-01-07 12:09:54 -08002657 private void updateSettingsValues() {
2658 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002660 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002662 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664
2665 private class LockList extends ArrayList<WakeLock>
2666 {
2667 void addLock(WakeLock wl)
2668 {
2669 int index = getIndex(wl.binder);
2670 if (index < 0) {
2671 this.add(wl);
2672 }
2673 }
2674
2675 WakeLock removeLock(IBinder binder)
2676 {
2677 int index = getIndex(binder);
2678 if (index >= 0) {
2679 return this.remove(index);
2680 } else {
2681 return null;
2682 }
2683 }
2684
2685 int getIndex(IBinder binder)
2686 {
2687 int N = this.size();
2688 for (int i=0; i<N; i++) {
2689 if (this.get(i).binder == binder) {
2690 return i;
2691 }
2692 }
2693 return -1;
2694 }
2695
2696 int gatherState()
2697 {
2698 int result = 0;
2699 int N = this.size();
2700 for (int i=0; i<N; i++) {
2701 WakeLock wl = this.get(i);
2702 if (wl.activated) {
2703 if (isScreenLock(wl.flags)) {
2704 result |= wl.minState;
2705 }
2706 }
2707 }
2708 return result;
2709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002710
Michael Chane96440f2009-05-06 10:27:36 -07002711 int reactivateScreenLocksLocked()
2712 {
2713 int result = 0;
2714 int N = this.size();
2715 for (int i=0; i<N; i++) {
2716 WakeLock wl = this.get(i);
2717 if (isScreenLock(wl.flags)) {
2718 wl.activated = true;
2719 result |= wl.minState;
2720 }
2721 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002722 if (mDebugProximitySensor) {
2723 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2724 + mProxIgnoredBecauseScreenTurnedOff);
2725 }
2726 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002727 return result;
2728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 }
2730
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002731 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 synchronized (mLocks) {
2733 mPolicy = p;
2734 mLocks.notifyAll();
2735 }
2736 }
2737
2738 WindowManagerPolicy getPolicyLocked() {
2739 while (mPolicy == null || !mDoneBooting) {
2740 try {
2741 mLocks.wait();
2742 } catch (InterruptedException e) {
2743 // Ignore
2744 }
2745 }
2746 return mPolicy;
2747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002750 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2751 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2752 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002753 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002754 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002755 }
2756
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002757 // wait until sensors are enabled before turning on screen.
2758 // some devices will not activate the light sensor properly on boot
2759 // unless we do this.
2760 if (mUseSoftwareAutoBrightness) {
2761 // turn the screen on
2762 setPowerState(SCREEN_BRIGHT);
2763 } else {
2764 // turn everything on
2765 setPowerState(ALL_BRIGHT);
2766 }
2767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002769 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002771
Joe Onoratod28f7532010-11-06 12:56:53 -07002772 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2773
Dianne Hackborn617f8772009-03-31 15:04:46 -07002774 long identity = Binder.clearCallingIdentity();
2775 try {
2776 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2777 mBatteryStats.noteScreenOn();
2778 } catch (RemoteException e) {
2779 // Nothing interesting to do.
2780 } finally {
2781 Binder.restoreCallingIdentity(identity);
2782 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002783 }
2784 }
2785
2786 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002787 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002788 synchronized (mLocks) {
2789 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2791 updateWakeLockLocked();
2792 mLocks.notifyAll();
2793 }
2794 }
2795
Joe Onoratob08a1af2010-10-11 19:28:58 -07002796 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 public void monitor() {
2798 synchronized (mLocks) { }
2799 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002800
2801 public int getSupportedWakeLockFlags() {
2802 int result = PowerManager.PARTIAL_WAKE_LOCK
2803 | PowerManager.FULL_WAKE_LOCK
2804 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2805
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002806 if (mProximitySensor != null) {
2807 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2808 }
2809
2810 return result;
2811 }
2812
Mike Lockwood237a2992009-09-15 14:42:16 -04002813 public void setBacklightBrightness(int brightness) {
2814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2815 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002816 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002817 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002818 mLcdLight.setBrightness(brightness);
2819 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2820 mButtonLight.setBrightness(brightness);
2821 long identity = Binder.clearCallingIdentity();
2822 try {
2823 mBatteryStats.noteScreenBrightness(brightness);
2824 } catch (RemoteException e) {
2825 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2826 } finally {
2827 Binder.restoreCallingIdentity(identity);
2828 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002829
Joe Onoratob08a1af2010-10-11 19:28:58 -07002830 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002831 synchronized (mLocks) {
2832 mScreenBrightness.targetValue = brightness;
2833 mScreenBrightness.jumpToTargetLocked();
2834 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002835 }
2836 }
2837
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002838 public void setAttentionLight(boolean on, int color) {
2839 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002840 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002841 }
2842
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002843 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002844 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002845 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002846 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002847 if (!mProximitySensorEnabled) {
2848 // clear calling identity so sensor manager battery stats are accurate
2849 long identity = Binder.clearCallingIdentity();
2850 try {
2851 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2852 SensorManager.SENSOR_DELAY_NORMAL);
2853 mProximitySensorEnabled = true;
2854 } finally {
2855 Binder.restoreCallingIdentity(identity);
2856 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002857 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002858 }
2859
2860 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002861 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002862 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002863 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002864 if (mProximitySensorEnabled) {
2865 // clear calling identity so sensor manager battery stats are accurate
2866 long identity = Binder.clearCallingIdentity();
2867 try {
2868 mSensorManager.unregisterListener(mProximityListener);
2869 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002870 if (mProximityPartialLock.isHeld()) {
2871 mProximityPartialLock.release();
2872 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002873 mProximitySensorEnabled = false;
2874 } finally {
2875 Binder.restoreCallingIdentity(identity);
2876 }
2877 if (mProximitySensorActive) {
2878 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002879 if (mDebugProximitySensor) {
2880 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2881 + mProxIgnoredBecauseScreenTurnedOff);
2882 }
2883 if (!mProxIgnoredBecauseScreenTurnedOff) {
2884 forceUserActivityLocked();
2885 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002886 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002887 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002888 }
2889
Mike Lockwood20f87d72009-11-05 16:08:51 -05002890 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002891 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002892 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002893 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002894 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002895 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002896 return;
2897 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002898 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002899 if (mDebugProximitySensor) {
2900 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2901 + mProxIgnoredBecauseScreenTurnedOff);
2902 }
2903 if (!mProxIgnoredBecauseScreenTurnedOff) {
2904 goToSleepLocked(SystemClock.uptimeMillis(),
2905 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2906 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002907 mProximitySensorActive = true;
2908 } else {
2909 // proximity sensor negative events trigger as user activity.
2910 // temporarily set mUserActivityAllowed to true so this will work
2911 // even when the keyguard is on.
2912 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002913 if (mDebugProximitySensor) {
2914 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2915 + mProxIgnoredBecauseScreenTurnedOff);
2916 }
2917 if (!mProxIgnoredBecauseScreenTurnedOff) {
2918 forceUserActivityLocked();
2919 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002920
2921 if (mProximityWakeLockCount == 0) {
2922 // disable sensor if we have no listeners left after proximity negative
2923 disableProximityLockLocked();
2924 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002925 }
2926 }
2927
Joe Onoratod28f7532010-11-06 12:56:53 -07002928 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002929 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002930 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2931 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2932 }
2933 if (!mAutoBrightessEnabled) {
2934 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002935 }
2936 if (mSensorManager != null && mLightSensorEnabled != enable) {
2937 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002938 // clear calling identity so sensor manager battery stats are accurate
2939 long identity = Binder.clearCallingIdentity();
2940 try {
2941 if (enable) {
2942 mSensorManager.registerListener(mLightListener, mLightSensor,
2943 SensorManager.SENSOR_DELAY_NORMAL);
2944 } else {
2945 mSensorManager.unregisterListener(mLightListener);
2946 mHandler.removeCallbacks(mAutoBrightnessTask);
2947 }
2948 } finally {
2949 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002950 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002951 }
2952 }
2953
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002954 SensorEventListener mProximityListener = new SensorEventListener() {
2955 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002956 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002957 synchronized (mLocks) {
2958 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002959 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2960 mLastProximityEventTime = milliseconds;
2961 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002962 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002963
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002964 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002965 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2966 distance < mProximitySensor.getMaximumRange());
2967
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002968 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002969 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002970 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002971 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2972 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2973 mProximityPendingValue = (active ? 1 : 0);
2974 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002975 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002976 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002977 // process the value immediately
2978 mProximityPendingValue = -1;
2979 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002980 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002981
2982 // update mProximityPartialLock state
2983 boolean held = mProximityPartialLock.isHeld();
2984 if (!held && proximityTaskQueued) {
2985 // hold wakelock until mProximityTask runs
2986 mProximityPartialLock.acquire();
2987 } else if (held && !proximityTaskQueued) {
2988 mProximityPartialLock.release();
2989 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002990 }
2991 }
2992
2993 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2994 // ignore
2995 }
2996 };
2997
2998 SensorEventListener mLightListener = new SensorEventListener() {
2999 public void onSensorChanged(SensorEvent event) {
3000 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003001 // ignore light sensor while screen is turning off
3002 if (isScreenTurningOffLocked()) {
3003 return;
3004 }
3005
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003006 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003007 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003008 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003009 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003010 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05003011 if (mLightSensorValue == -1 ||
3012 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3013 // process the value immediately if screen has just turned on
3014 mHandler.removeCallbacks(mAutoBrightnessTask);
3015 mLightSensorPendingDecrease = false;
3016 mLightSensorPendingIncrease = false;
3017 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003018 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003019 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3020 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3021 (value == mLightSensorValue) ||
3022 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3023 // delay processing to debounce the sensor
3024 mHandler.removeCallbacks(mAutoBrightnessTask);
3025 mLightSensorPendingDecrease = (value < mLightSensorValue);
3026 mLightSensorPendingIncrease = (value > mLightSensorValue);
3027 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3028 mLightSensorPendingValue = value;
3029 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3030 }
3031 } else {
3032 mLightSensorPendingValue = value;
3033 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003034 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003035 }
3036 }
3037
3038 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3039 // ignore
3040 }
3041 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042}