blob: 0934cd02f8bd0dc439270a2f8fb2ebace6b0cce1 [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 Hackborn38e29a62011-09-18 14:43:08 -0700164 private boolean mPreparingForScreenOn = 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
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001125 + " mStayOnConditions=" + mStayOnConditions
1126 + " mPreparingForScreenOn=" + mPreparingForScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001127 pw.println(" mScreenOffReason=" + mScreenOffReason
1128 + " mUserState=" + mUserState);
1129 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1130 + ',' + mBroadcastQueue[2] + "}");
1131 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1132 + ',' + mBroadcastWhy[2] + "}");
1133 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1134 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1135 + " mUserActivityAllowed=" + mUserActivityAllowed);
1136 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1137 + " mScreenOffDelay=" + mScreenOffDelay);
1138 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1139 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1140 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1141 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1142 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1143 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1144 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1145 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1146 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1147 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1148 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1149 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1150 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1151 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1152 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1153 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1154 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1155 pw.println(" mLightSensorValue=" + mLightSensorValue
1156 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001157 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1158 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001159 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1160 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1161 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1162 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1163 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1164 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001165
Mike Lockwoodca44df82010-02-25 13:48:49 -05001166 int N = mLocks.size();
1167 pw.println();
1168 pw.println("mLocks.size=" + N + ":");
1169 for (int i=0; i<N; i++) {
1170 WakeLock wl = mLocks.get(i);
1171 String type = lockType(wl.flags & LOCK_MASK);
1172 String acquireCausesWakeup = "";
1173 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1174 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1175 }
1176 String activated = "";
1177 if (wl.activated) {
1178 activated = " activated";
1179 }
1180 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001181 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1182 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001184
1185 pw.println();
1186 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1187 for (PokeLock p: mPokeLocks.values()) {
1188 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001189 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1190 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001191 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1192 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1193 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1194 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001196
Mike Lockwoodca44df82010-02-25 13:48:49 -05001197 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
1200
Joe Onorato7999bff2010-07-24 11:50:05 -04001201 private void setTimeoutLocked(long now, int nextState) {
1202 setTimeoutLocked(now, -1, nextState);
1203 }
1204
1205 // If they gave a timeoutOverride it is the number of seconds
1206 // to screen-off. Figure out where in the countdown cycle we
1207 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001208 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1209 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001210 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001211 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001212 long when = 0;
1213 if (timeoutOverride <= 0) {
1214 switch (nextState)
1215 {
1216 case SCREEN_BRIGHT:
1217 when = now + mKeylightDelay;
1218 break;
1219 case SCREEN_DIM:
1220 if (mDimDelay >= 0) {
1221 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001222 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001223 } else {
1224 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1225 }
1226 case SCREEN_OFF:
1227 synchronized (mLocks) {
1228 when = now + mScreenOffDelay;
1229 }
1230 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001231 default:
1232 when = now;
1233 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001235 } else {
1236 override: {
1237 if (timeoutOverride <= mScreenOffDelay) {
1238 when = now + timeoutOverride;
1239 nextState = SCREEN_OFF;
1240 break override;
1241 }
1242 timeoutOverride -= mScreenOffDelay;
1243
1244 if (mDimDelay >= 0) {
1245 if (timeoutOverride <= mDimDelay) {
1246 when = now + timeoutOverride;
1247 nextState = SCREEN_DIM;
1248 break override;
1249 }
1250 timeoutOverride -= mDimDelay;
1251 }
1252
1253 when = now + timeoutOverride;
1254 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001256 }
1257 if (mSpew) {
1258 Slog.d(TAG, "setTimeoutLocked now=" + now
1259 + " timeoutOverride=" + timeoutOverride
1260 + " nextState=" + nextState + " when=" + when);
1261 }
Joe Onorato797e6882010-08-26 14:46:01 -04001262
1263 mHandler.removeCallbacks(mTimeoutTask);
1264 mTimeoutTask.nextState = nextState;
1265 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1266 ? (originalTimeoutOverride - timeoutOverride)
1267 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001268 mHandler.postAtTime(mTimeoutTask, when);
1269 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 }
1273
1274 private void cancelTimerLocked()
1275 {
1276 mHandler.removeCallbacks(mTimeoutTask);
1277 mTimeoutTask.nextState = -1;
1278 }
1279
1280 private class TimeoutTask implements Runnable
1281 {
1282 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001283 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 public void run()
1285 {
1286 synchronized (mLocks) {
1287 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001288 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
1290
1291 if (nextState == -1) {
1292 return;
1293 }
1294
1295 mUserState = this.nextState;
1296 setPowerState(this.nextState | mWakeLockState);
1297
1298 long now = SystemClock.uptimeMillis();
1299
1300 switch (this.nextState)
1301 {
1302 case SCREEN_BRIGHT:
1303 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001304 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 break;
1306 }
1307 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001308 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 break;
1310 }
1311 }
1312 }
1313 }
1314
1315 private void sendNotificationLocked(boolean on, int why)
1316 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001317 if (!on) {
1318 mStillNeedSleepNotification = false;
1319 }
1320
Joe Onorato128e7292009-03-24 18:41:31 -07001321 // Add to the queue.
1322 int index = 0;
1323 while (mBroadcastQueue[index] != -1) {
1324 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Joe Onorato128e7292009-03-24 18:41:31 -07001326 mBroadcastQueue[index] = on ? 1 : 0;
1327 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328
Joe Onorato128e7292009-03-24 18:41:31 -07001329 // If we added it position 2, then there is a pair that can be stripped.
1330 // If we added it position 1 and we're turning the screen off, we can strip
1331 // the pair and do nothing, because the screen is already off, and therefore
1332 // keyguard has already been enabled.
1333 // However, if we added it at position 1 and we're turning it on, then position
1334 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1335 // on, so have to run the queue then.
1336 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001337 // While we're collapsing them, if it's going off, and the new reason
1338 // is more significant than the first, then use the new one.
1339 if (!on && mBroadcastWhy[0] > why) {
1340 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001341 }
1342 mBroadcastQueue[0] = on ? 1 : 0;
1343 mBroadcastQueue[1] = -1;
1344 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001345 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001346 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001347 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001348 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001349 index = 0;
1350 }
1351 if (index == 1 && !on) {
1352 mBroadcastQueue[0] = -1;
1353 mBroadcastQueue[1] = -1;
1354 index = -1;
1355 // The wake lock was being held, but we're not actually going to do any
1356 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001357 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001359 }
1360
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001361 // The broadcast queue has changed; make sure the screen is on if it
1362 // is now possible for it to be.
1363 updateNativePowerStateLocked();
1364
Joe Onorato128e7292009-03-24 18:41:31 -07001365 // Now send the message.
1366 if (index >= 0) {
1367 // Acquire the broadcast wake lock before changing the power
1368 // state. It will be release after the broadcast is sent.
1369 // We always increment the ref count for each notification in the queue
1370 // and always decrement when that notification is handled.
1371 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001372 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001373 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375 }
1376
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001377 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1378 new WindowManagerPolicy.ScreenOnListener() {
1379 @Override public void onScreenOn() {
1380 synchronized (mLocks) {
1381 if (mPreparingForScreenOn) {
1382 mPreparingForScreenOn = false;
1383 updateNativePowerStateLocked();
1384 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1385 4, mBroadcastWakeLock.mCount);
1386 mBroadcastWakeLock.release();
1387 }
1388 }
1389 }
1390 };
1391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 private Runnable mNotificationTask = new Runnable()
1393 {
1394 public void run()
1395 {
Joe Onorato128e7292009-03-24 18:41:31 -07001396 while (true) {
1397 int value;
1398 int why;
1399 WindowManagerPolicy policy;
1400 synchronized (mLocks) {
1401 value = mBroadcastQueue[0];
1402 why = mBroadcastWhy[0];
1403 for (int i=0; i<2; i++) {
1404 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1405 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1406 }
1407 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001408 if (value == 1 && !mPreparingForScreenOn) {
1409 mPreparingForScreenOn = true;
1410 mBroadcastWakeLock.acquire();
1411 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1412 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
Joe Onorato128e7292009-03-24 18:41:31 -07001415 if (value == 1) {
1416 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001417
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001418 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001419 try {
1420 ActivityManagerNative.getDefault().wakingUp();
1421 } catch (RemoteException e) {
1422 // ignore it
1423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Joe Onorato128e7292009-03-24 18:41:31 -07001425 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001426 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001427 }
1428 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1429 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1430 mScreenOnBroadcastDone, mHandler, 0, null, null);
1431 } else {
1432 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001433 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001434 mBroadcastWakeLock.mCount);
1435 mBroadcastWakeLock.release();
1436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438 }
Joe Onorato128e7292009-03-24 18:41:31 -07001439 else if (value == 0) {
1440 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
Joe Onorato128e7292009-03-24 18:41:31 -07001442 policy.screenTurnedOff(why);
1443 try {
1444 ActivityManagerNative.getDefault().goingToSleep();
1445 } catch (RemoteException e) {
1446 // ignore it.
1447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448
Joe Onorato128e7292009-03-24 18:41:31 -07001449 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1450 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1451 mScreenOffBroadcastDone, mHandler, 0, null, null);
1452 } else {
1453 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001455 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001456 updateNativePowerStateLocked();
Joe Onorato128e7292009-03-24 18:41:31 -07001457 mBroadcastWakeLock.release();
1458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460 }
Joe Onorato128e7292009-03-24 18:41:31 -07001461 else {
1462 // If we're in this case, then this handler is running for a previous
1463 // paired transaction. mBroadcastWakeLock will already have been released.
1464 break;
1465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467 }
1468 };
1469
1470 long mScreenOnStart;
1471 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1472 public void onReceive(Context context, Intent intent) {
1473 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001474 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1476 mBroadcastWakeLock.release();
1477 }
1478 }
1479 };
1480
1481 long mScreenOffStart;
1482 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1483 public void onReceive(Context context, Intent intent) {
1484 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001485 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1487 mBroadcastWakeLock.release();
1488 }
1489 }
1490 };
1491
1492 void logPointerUpEvent() {
1493 if (LOG_TOUCH_DOWNS) {
1494 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1495 mLastTouchDown = 0;
1496 }
1497 }
1498
1499 void logPointerDownEvent() {
1500 if (LOG_TOUCH_DOWNS) {
1501 // If we are not already timing a down/up sequence
1502 if (mLastTouchDown == 0) {
1503 mLastTouchDown = SystemClock.elapsedRealtime();
1504 mTouchCycles++;
1505 }
1506 }
1507 }
1508
1509 /**
1510 * Prevents the screen from turning on even if it *should* turn on due
1511 * to a subsequent full wake lock being acquired.
1512 * <p>
1513 * This is a temporary hack that allows an activity to "cover up" any
1514 * display glitches that happen during the activity's startup
1515 * sequence. (Specifically, this API was added to work around a
1516 * cosmetic bug in the "incoming call" sequence, where the lock screen
1517 * would flicker briefly before the incoming call UI became visible.)
1518 * TODO: There ought to be a more elegant way of doing this,
1519 * probably by having the PowerManager and ActivityManager
1520 * work together to let apps specify that the screen on/off
1521 * state should be synchronized with the Activity lifecycle.
1522 * <p>
1523 * Note that calling preventScreenOn(true) will NOT turn the screen
1524 * off if it's currently on. (This API only affects *future*
1525 * acquisitions of full wake locks.)
1526 * But calling preventScreenOn(false) WILL turn the screen on if
1527 * it's currently off because of a prior preventScreenOn(true) call.
1528 * <p>
1529 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1530 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1531 * call doesn't occur within 5 seconds, we'll turn the screen back on
1532 * ourselves (and log a warning about it); this prevents a buggy app
1533 * from disabling the screen forever.)
1534 * <p>
1535 * TODO: this feature should really be controlled by a new type of poke
1536 * lock (rather than an IPowerManager call).
1537 */
1538 public void preventScreenOn(boolean prevent) {
1539 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1540
1541 synchronized (mLocks) {
1542 if (prevent) {
1543 // First of all, grab a partial wake lock to
1544 // make sure the CPU stays on during the entire
1545 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1546 mPreventScreenOnPartialLock.acquire();
1547
1548 // Post a forceReenableScreen() call (for 5 seconds in the
1549 // future) to make sure the matching preventScreenOn(false) call
1550 // has happened by then.
1551 mHandler.removeCallbacks(mForceReenableScreenTask);
1552 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1553
1554 // Finally, set the flag that prevents the screen from turning on.
1555 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001556 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 mPreventScreenOn = true;
1558 } else {
1559 // (Re)enable the screen.
1560 mPreventScreenOn = false;
1561
1562 // We're "undoing" a the prior preventScreenOn(true) call, so we
1563 // no longer need the 5-second safeguard.
1564 mHandler.removeCallbacks(mForceReenableScreenTask);
1565
1566 // Forcibly turn on the screen if it's supposed to be on. (This
1567 // handles the case where the screen is currently off because of
1568 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001569 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1573 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001574 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001576 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 }
1579
1580 // Release the partial wake lock that we held during the
1581 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1582 mPreventScreenOnPartialLock.release();
1583 }
1584 }
1585 }
1586
1587 public void setScreenBrightnessOverride(int brightness) {
1588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1589
Mike Lockwoodf527c712010-06-10 14:12:33 -04001590 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 synchronized (mLocks) {
1592 if (mScreenBrightnessOverride != brightness) {
1593 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001594 if (isScreenOn()) {
1595 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 }
1599 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001600
1601 public void setButtonBrightnessOverride(int brightness) {
1602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1603
Mike Lockwoodf527c712010-06-10 14:12:33 -04001604 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001605 synchronized (mLocks) {
1606 if (mButtonBrightnessOverride != brightness) {
1607 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001608 if (isScreenOn()) {
1609 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1610 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001611 }
1612 }
1613 }
1614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 /**
1616 * Sanity-check that gets called 5 seconds after any call to
1617 * preventScreenOn(true). This ensures that the original call
1618 * is followed promptly by a call to preventScreenOn(false).
1619 */
1620 private void forceReenableScreen() {
1621 // We shouldn't get here at all if mPreventScreenOn is false, since
1622 // we should have already removed any existing
1623 // mForceReenableScreenTask messages...
1624 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001625 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 return;
1627 }
1628
1629 // Uh oh. It's been 5 seconds since a call to
1630 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1631 // This means the app that called preventScreenOn(true) is either
1632 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1633 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1634 // crashed before doing so.)
1635
1636 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001637 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 + "Forcing the screen back on...");
1639 preventScreenOn(false);
1640 }
1641
1642 private Runnable mForceReenableScreenTask = new Runnable() {
1643 public void run() {
1644 forceReenableScreen();
1645 }
1646 };
1647
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001648 private int setScreenStateLocked(boolean on) {
1649 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001650 if (err == 0) {
1651 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1652 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001653 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001654 if (!on) {
1655 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001656 mButtonLight.turnOff();
1657 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001658 // clear current value so we will update based on the new conditions
1659 // when the sensor is reenabled.
1660 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001661 // reset our highest light sensor value when the screen turns off
1662 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001663 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001664 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001665 }
1666 return err;
1667 }
1668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 private void setPowerState(int state)
1670 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001671 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673
Mike Lockwood435eb642009-12-03 08:40:18 -05001674 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 {
1676 synchronized (mLocks) {
1677 int err;
1678
1679 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001682 + " noChangeLights=" + noChangeLights
1683 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685
1686 if (noChangeLights) {
1687 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1688 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001689 if (mProximitySensorActive) {
1690 // don't turn on the screen when the proximity sensor lock is held
1691 newState = (newState & ~SCREEN_BRIGHT);
1692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693
1694 if (batteryIsLow()) {
1695 newState |= BATTERY_LOW_BIT;
1696 } else {
1697 newState &= ~BATTERY_LOW_BIT;
1698 }
1699 if (newState == mPowerState) {
1700 return;
1701 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001702
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001703 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 newState |= ALL_BRIGHT;
1705 }
1706
1707 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1708 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1709
Mike Lockwood51b844962009-11-16 21:51:18 -05001710 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001711 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001713 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001715 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001717 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001719 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001721 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1723 }
1724
1725 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001726 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1728 }
1729
1730 if (oldScreenOn != newScreenOn) {
1731 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001732 // When the user presses the power button, we need to always send out the
1733 // notification that it's going to sleep so the keyguard goes on. But
1734 // we can't do that until the screen fades out, so we don't show the keyguard
1735 // too early.
1736 if (mStillNeedSleepNotification) {
1737 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1738 }
1739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 // Turn on the screen UNLESS there was a prior
1741 // preventScreenOn(true) request. (Note that the lifetime
1742 // of a single preventScreenOn() request is limited to 5
1743 // seconds to prevent a buggy app from disabling the
1744 // screen forever; see forceReenableScreen().)
1745 boolean reallyTurnScreenOn = true;
1746 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001747 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 + mPreventScreenOn);
1749 }
1750
1751 if (mPreventScreenOn) {
1752 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001753 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
1755 reallyTurnScreenOn = false;
1756 }
1757 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001758 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 long identity = Binder.clearCallingIdentity();
1760 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001761 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 mBatteryStats.noteScreenOn();
1763 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001764 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 } finally {
1766 Binder.restoreCallingIdentity(identity);
1767 }
1768 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001769 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 // But continue as if we really did turn the screen on...
1771 err = 0;
1772 }
1773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 mLastTouchDown = 0;
1775 mTotalTouchDownTime = 0;
1776 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001777 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 mTotalTouchDownTime, mTouchCycles);
1779 if (err == 0) {
1780 mPowerState |= SCREEN_ON_BIT;
1781 sendNotificationLocked(true, -1);
1782 }
1783 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001784 // cancel light sensor task
1785 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001786 mLightSensorPendingDecrease = false;
1787 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 mScreenOffTime = SystemClock.elapsedRealtime();
1789 long identity = Binder.clearCallingIdentity();
1790 try {
1791 mBatteryStats.noteScreenOff();
1792 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 } finally {
1795 Binder.restoreCallingIdentity(identity);
1796 }
1797 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001798 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001800 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 err = 0;
1803 mLastTouchDown = 0;
1804 }
1805 }
1806 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001807
1808 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001811
1812 private void updateNativePowerStateLocked() {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001813 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001814 // Don't turn screen on until we know we are really ready to.
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001815 // This is to avoid letting the screen go on before things like the
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001816 // lock screen have been displayed.
1817 if (mPreparingForScreenOn) {
1818 // Currently waiting for confirmation from the policy that it
1819 // is okay to turn on the screen. Don't allow the screen to go
1820 // on until that is done.
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001821 return;
1822 }
1823 for (int i=0; i<mBroadcastQueue.length; i++) {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001824 if (mBroadcastQueue[i] == 1) {
1825 // A screen on is currently enqueued.
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001826 return;
1827 }
1828 }
1829 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001830 nativeSetPowerState(
1831 (mPowerState & SCREEN_ON_BIT) != 0,
1832 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001834
Mike Lockwood435eb642009-12-03 08:40:18 -05001835 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001837 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001839 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1840 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001842 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001844 mScreenOffReason = reason;
1845 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847 return err;
1848 }
1849
1850 private boolean batteryIsLow() {
1851 return (!mIsPowered &&
1852 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1853 }
1854
The Android Open Source Project10592532009-03-18 17:39:46 -07001855 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001856 final int oldState = mPowerState;
Joe Onorato60607a902010-10-23 14:49:30 -07001857 if ((newState & SCREEN_ON_BIT) != 0) {
1858 // Only turn on the buttons or keyboard if the screen is also on.
1859 // We should never see the buttons on but not the screen.
1860 newState = applyButtonState(newState);
1861 newState = applyKeyboardState(newState);
1862 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001863 final int realDifference = (newState ^ oldState);
1864 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001866 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 int offMask = 0;
1870 int dimMask = 0;
1871 int onMask = 0;
1872
1873 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001876 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1877 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001879 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
1881 }
1882
1883 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001884 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1885 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001887 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889 }
1890
1891 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001892 int nominalCurrentValue = -1;
1893 // If there was an actual difference in the light state, then
1894 // figure out the "ideal" current value based on the previous
1895 // state. Otherwise, this is a change due to the brightness
1896 // override, so we want to animate from whatever the current
1897 // value is.
1898 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1899 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1900 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1901 nominalCurrentValue = preferredBrightness;
1902 break;
1903 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001904 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001905 break;
1906 case 0:
1907 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1908 break;
1909 case SCREEN_BRIGHT_BIT:
1910 default:
1911 // not possible
1912 nominalCurrentValue = (int)mScreenBrightness.curValue;
1913 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001914 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001915 }
1916 int brightness = preferredBrightness;
1917 int steps = ANIM_STEPS;
1918 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1919 // dim or turn off backlight, depending on if the screen is on
1920 // the scale is because the brightness ramp isn't linear and this biases
1921 // it so the later parts take longer.
1922 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001923 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07001924 if (ratio > 1.0f) ratio = 1.0f;
1925 if ((newState & SCREEN_ON_BIT) == 0) {
1926 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1927 // was bright
1928 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001930 // was dim
1931 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001933 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001935 if ((oldState & SCREEN_ON_BIT) != 0) {
1936 // was bright
1937 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1938 } else {
1939 // was dim
1940 steps = (int)(ANIM_STEPS*ratio);
1941 }
1942 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1943 // If the "stay on while plugged in" option is
1944 // turned on, then the screen will often not
1945 // automatically turn off while plugged in. To
1946 // still have a sense of when it is inactive, we
1947 // will then count going dim as turning off.
1948 mScreenOffTime = SystemClock.elapsedRealtime();
1949 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001950 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001953 long identity = Binder.clearCallingIdentity();
1954 try {
1955 mBatteryStats.noteScreenBrightness(brightness);
1956 } catch (RemoteException e) {
1957 // Nothing interesting to do.
1958 } finally {
1959 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001961 mScreenBrightness.setTargetLocked(brightness, steps,
1962 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001964
Joe Onorato60607a902010-10-23 14:49:30 -07001965 if (mSpew) {
1966 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1967 + " dimMask=0x" + Integer.toHexString(dimMask)
1968 + " onMask=0x" + Integer.toHexString(onMask)
1969 + " difference=0x" + Integer.toHexString(difference)
1970 + " realDifference=0x" + Integer.toHexString(realDifference)
1971 + " forceState=0x" + Integer.toHexString(forceState)
1972 );
1973 }
1974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001976 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001977 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001980 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 if ((newState & BATTERY_LOW_BIT) != 0 &&
1982 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1983 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1984 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001985 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001986 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988 if (onMask != 0) {
1989 int brightness = getPreferredBrightness();
1990 if ((newState & BATTERY_LOW_BIT) != 0 &&
1991 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1992 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1993 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001994 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001995 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998
The Android Open Source Project10592532009-03-18 17:39:46 -07001999 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002000 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002001 ? LightsService.BRIGHTNESS_MODE_SENSOR
2002 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07002003 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002004 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07002005 }
2006 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002007 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002008 }
2009 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002010 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013
Joe Onoratob08a1af2010-10-11 19:28:58 -07002014 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 boolean initialized;
2018 int targetValue;
2019 float curValue;
2020 float delta;
2021 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 BrightnessState(int m) {
2024 mask = m;
2025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 public void dump(PrintWriter pw, String prefix) {
2028 pw.println(prefix + "animating=" + animating
2029 + " targetValue=" + targetValue
2030 + " curValue=" + curValue
2031 + " delta=" + delta);
2032 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002033
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002035 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 if (!initialized) {
2037 initialized = true;
2038 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002039 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002040 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002043 delta = (targetValue -
2044 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2045 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07002047 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002048 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2049 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002050 + " nominalCurrentValue=" + nominalCurrentValue
2051 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
2053 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002054
2055 if (mSpew) {
2056 Slog.i(TAG, "scheduling light animator");
2057 }
2058 mScreenOffHandler.removeCallbacks(this);
2059 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 boolean stepLocked() {
2063 if (!animating) return false;
2064 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002065 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 + " target=" + targetValue + " delta=" + delta);
2067 }
2068 curValue += delta;
2069 int curIntValue = (int)curValue;
2070 boolean more = true;
2071 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002072 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 more = false;
2074 } else if (delta > 0) {
2075 if (curIntValue >= targetValue) {
2076 curValue = curIntValue = targetValue;
2077 more = false;
2078 }
2079 } else {
2080 if (curIntValue <= targetValue) {
2081 curValue = curIntValue = targetValue;
2082 more = false;
2083 }
2084 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002085 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002086 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002087 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002088 return more;
2089 }
2090
Joe Onorato3d3db602010-10-18 16:08:16 -04002091 void jumpToTargetLocked() {
2092 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002093 setLightBrightness(mask, targetValue);
2094 final int tv = targetValue;
2095 curValue = tv;
2096 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002097 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002098 }
2099
Joe Onorato3d3db602010-10-18 16:08:16 -04002100 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 animating = more;
2102 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002103 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002104 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002110 if (mAnimateScreenLights) {
2111 synchronized (mLocks) {
2112 long now = SystemClock.uptimeMillis();
2113 boolean more = mScreenBrightness.stepLocked();
2114 if (more) {
2115 mScreenOffHandler.postAtTime(this, now+(1000/60));
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002118 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002119 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002120 // we're turning off
2121 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2122 if (animate) {
2123 // It's pretty scary to hold mLocks for this long, and we should
2124 // redesign this, but it works for now.
2125 nativeStartSurfaceFlingerAnimation(
2126 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2127 ? 0 : mAnimationSetting);
2128 }
2129 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132 }
2133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 private int getPreferredBrightness() {
2136 try {
2137 if (mScreenBrightnessOverride >= 0) {
2138 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002139 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002140 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002141 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2144 SCREEN_BRIGHTNESS);
2145 // Don't let applications turn the screen all the way off
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002146 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 } catch (SettingNotFoundException snfe) {
2148 return Power.BRIGHTNESS_ON;
2149 }
2150 }
2151
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002152 private int applyButtonState(int state) {
2153 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002154 if ((state & BATTERY_LOW_BIT) != 0) {
2155 // do not override brightness if the battery is low
2156 return state;
2157 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002158 if (mButtonBrightnessOverride >= 0) {
2159 brightness = mButtonBrightnessOverride;
2160 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2161 brightness = mLightSensorButtonBrightness;
2162 }
2163 if (brightness > 0) {
2164 return state | BUTTON_BRIGHT_BIT;
2165 } else if (brightness == 0) {
2166 return state & ~BUTTON_BRIGHT_BIT;
2167 } else {
2168 return state;
2169 }
2170 }
2171
2172 private int applyKeyboardState(int state) {
2173 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002174 if ((state & BATTERY_LOW_BIT) != 0) {
2175 // do not override brightness if the battery is low
2176 return state;
2177 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002178 if (!mKeyboardVisible) {
2179 brightness = 0;
2180 } else if (mButtonBrightnessOverride >= 0) {
2181 brightness = mButtonBrightnessOverride;
2182 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2183 brightness = mLightSensorKeyboardBrightness;
2184 }
2185 if (brightness > 0) {
2186 return state | KEYBOARD_BRIGHT_BIT;
2187 } else if (brightness == 0) {
2188 return state & ~KEYBOARD_BRIGHT_BIT;
2189 } else {
2190 return state;
2191 }
2192 }
2193
Charles Mendis322591c2009-10-29 11:06:59 -07002194 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 synchronized (mLocks) {
2196 return (mPowerState & SCREEN_ON_BIT) != 0;
2197 }
2198 }
2199
Charles Mendis322591c2009-10-29 11:06:59 -07002200 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 synchronized (mLocks) {
2202 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2203 }
2204 }
2205
Mike Lockwood497087e32009-11-08 18:33:03 -05002206 private boolean isScreenTurningOffLocked() {
2207 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2208 }
2209
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002210 private boolean shouldLog(long time) {
2211 synchronized (mLocks) {
2212 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2213 mWarningSpewThrottleTime = time;
2214 mWarningSpewThrottleCount = 0;
2215 return true;
2216 } else if (mWarningSpewThrottleCount < 30) {
2217 mWarningSpewThrottleCount++;
2218 return true;
2219 } else {
2220 return false;
2221 }
2222 }
2223 }
2224
Mike Lockwood200b30b2009-09-20 00:23:59 -04002225 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002226 if (isScreenTurningOffLocked()) {
2227 // cancel animation so userActivity will succeed
2228 mScreenBrightness.animating = false;
2229 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002230 boolean savedActivityAllowed = mUserActivityAllowed;
2231 mUserActivityAllowed = true;
2232 userActivity(SystemClock.uptimeMillis(), false);
2233 mUserActivityAllowed = savedActivityAllowed;
2234 }
2235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2237 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002238 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240
2241 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002242 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2243 != PackageManager.PERMISSION_GRANTED) {
2244 if (shouldLog(time)) {
2245 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2246 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2247 }
2248 return;
2249 }
2250
Joe Onorato7999bff2010-07-24 11:50:05 -04002251 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
2253
2254 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002255 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 }
2257
2258 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002259 userActivity(time, -1, noChangeLights, eventType, force);
2260 }
2261
2262 /*
2263 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2264 * on with user activity. Don't use this function.
2265 */
2266 public void clearUserActivityTimeout(long now, long timeout) {
2267 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2268 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2269 userActivity(now, timeout, false, OTHER_EVENT, false);
2270 }
2271
2272 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2273 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274
Joe Onorato1a542c72010-11-08 09:48:20 -08002275 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002276 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002277 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002278 }
2279 return;
2280 }
2281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 synchronized (mLocks) {
2283 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002284 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 + " mUserActivityAllowed=" + mUserActivityAllowed
2286 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002287 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2288 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002289 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002290 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
Mike Lockwood05067122009-10-27 23:07:25 -04002292 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002293 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002294 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002295 return;
2296 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002297 // Disable proximity sensor if if user presses power key while we are in the
2298 // "waiting for proximity sensor to go negative" state.
2299 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2300 mProximitySensorActive = false;
2301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 if (mLastEventTime <= time || force) {
2303 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002304 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002305 // Only turn on button backlights if a button was pressed
2306 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002307 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2309 } else {
2310 // don't clear button/keyboard backlights when the screen is touched.
2311 mUserState |= SCREEN_BRIGHT;
2312 }
2313
Dianne Hackborn617f8772009-03-31 15:04:46 -07002314 int uid = Binder.getCallingUid();
2315 long ident = Binder.clearCallingIdentity();
2316 try {
2317 mBatteryStats.noteUserActivity(uid, eventType);
2318 } catch (RemoteException e) {
2319 // Ignore
2320 } finally {
2321 Binder.restoreCallingIdentity(ident);
2322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002323
Michael Chane96440f2009-05-06 10:27:36 -07002324 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002325 setPowerState(mUserState | mWakeLockState, noChangeLights,
2326 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002327 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
2329 }
2330 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002331
2332 if (mPolicy != null) {
2333 mPolicy.userActivity();
2334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 }
2336
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002337 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2338 try {
2339 int i;
2340 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2341 if (sensorValue < mAutoBrightnessLevels[i]) {
2342 break;
2343 }
2344 }
2345 return values[i];
2346 } catch (Exception e) {
2347 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002348 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002349 return 255;
2350 }
2351 }
2352
Mike Lockwood20f87d72009-11-05 16:08:51 -05002353 private Runnable mProximityTask = new Runnable() {
2354 public void run() {
2355 synchronized (mLocks) {
2356 if (mProximityPendingValue != -1) {
2357 proximityChangedLocked(mProximityPendingValue == 1);
2358 mProximityPendingValue = -1;
2359 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002360 if (mProximityPartialLock.isHeld()) {
2361 mProximityPartialLock.release();
2362 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002363 }
2364 }
2365 };
2366
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002367 private Runnable mAutoBrightnessTask = new Runnable() {
2368 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002369 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002370 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2371 int value = (int)mLightSensorPendingValue;
2372 mLightSensorPendingDecrease = false;
2373 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002374 lightSensorChangedLocked(value);
2375 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002376 }
2377 }
2378 };
2379
Mike Lockwoodb2865412010-02-02 22:40:33 -05002380 private void dockStateChanged(int state) {
2381 synchronized (mLocks) {
2382 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2383 if (mIsDocked) {
2384 mHighestLightSensorValue = -1;
2385 }
2386 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2387 // force lights recalculation
2388 int value = (int)mLightSensorValue;
2389 mLightSensorValue = -1;
2390 lightSensorChangedLocked(value);
2391 }
2392 }
2393 }
2394
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002395 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002396 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002397 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002398 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002399
Joe Onorato06eb33a2010-10-25 14:09:21 -07002400 // Don't do anything if the screen is off.
2401 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2402 if (mDebugLightSensor) {
2403 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2404 }
2405 return;
2406 }
2407
Mike Lockwoodb2865412010-02-02 22:40:33 -05002408 // do not allow light sensor value to decrease
2409 if (mHighestLightSensorValue < value) {
2410 mHighestLightSensorValue = value;
2411 }
2412
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002413 if (mLightSensorValue != value) {
2414 mLightSensorValue = value;
2415 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002416 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2417 // we only do this if we are undocked, since lighting should be stable when
2418 // stationary in a dock.
2419 int lcdValue = getAutoBrightnessValue(
2420 (mIsDocked ? value : mHighestLightSensorValue),
2421 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002422 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002423 int keyboardValue;
2424 if (mKeyboardVisible) {
2425 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2426 } else {
2427 keyboardValue = 0;
2428 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002429 mLightSensorScreenBrightness = lcdValue;
2430 mLightSensorButtonBrightness = buttonValue;
2431 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002432
2433 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002434 Slog.d(TAG, "lcdValue " + lcdValue);
2435 Slog.d(TAG, "buttonValue " + buttonValue);
2436 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002437 }
2438
Mike Lockwood4984e732009-11-01 08:16:33 -05002439 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002440 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2441 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002442 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002443 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002444 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002445 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002446 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002447 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002448 }
2449 }
2450 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002451 }
2452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 /**
2454 * The user requested that we go to sleep (probably with the power button).
2455 * This overrides all wake locks that are held.
2456 */
2457 public void goToSleep(long time)
2458 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002459 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2460 }
2461
2462 /**
2463 * The user requested that we go to sleep (probably with the power button).
2464 * This overrides all wake locks that are held.
2465 */
2466 public void goToSleepWithReason(long time, int reason)
2467 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2469 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002470 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002475 * Reboot the device immediately, passing 'reason' (may be null)
2476 * to the underlying __reboot system call. Should not return.
2477 */
2478 public void reboot(String reason)
2479 {
2480 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002481
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002482 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2483 throw new IllegalStateException("Too early to call reboot()");
2484 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002485
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002486 final String finalReason = reason;
2487 Runnable runnable = new Runnable() {
2488 public void run() {
2489 synchronized (this) {
2490 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002491 }
2492
San Mehat1e512792010-01-07 10:40:29 -08002493 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002494 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002495 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002496 mHandler.post(runnable);
2497
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002498 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002499 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002500 while (true) {
2501 try {
2502 runnable.wait();
2503 } catch (InterruptedException e) {
2504 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002505 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002506 }
2507 }
2508
Dan Egnor60d87622009-12-16 16:32:58 -08002509 /**
2510 * Crash the runtime (causing a complete restart of the Android framework).
2511 * Requires REBOOT permission. Mostly for testing. Should not return.
2512 */
2513 public void crash(final String message)
2514 {
2515 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2516 Thread t = new Thread("PowerManagerService.crash()") {
2517 public void run() { throw new RuntimeException(message); }
2518 };
2519 try {
2520 t.start();
2521 t.join();
2522 } catch (InterruptedException e) {
2523 Log.wtf(TAG, e);
2524 }
2525 }
2526
Mike Lockwood435eb642009-12-03 08:40:18 -05002527 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528
2529 if (mLastEventTime <= time) {
2530 mLastEventTime = time;
2531 // cancel all of the wake locks
2532 mWakeLockState = SCREEN_OFF;
2533 int N = mLocks.size();
2534 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002535 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 for (int i=0; i<N; i++) {
2537 WakeLock wl = mLocks.get(i);
2538 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002539 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2540 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2541 proxLock = true;
2542 } else {
2543 mLocks.get(i).activated = false;
2544 numCleared++;
2545 }
2546 }
2547 }
2548 if (!proxLock) {
2549 mProxIgnoredBecauseScreenTurnedOff = true;
2550 if (mDebugProximitySensor) {
2551 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
2553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002555 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002557 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 cancelTimerLocked();
2559 }
2560 }
2561
2562 public long timeSinceScreenOn() {
2563 synchronized (mLocks) {
2564 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2565 return 0;
2566 }
2567 return SystemClock.elapsedRealtime() - mScreenOffTime;
2568 }
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002572 synchronized (mLocks) {
2573 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002574 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002575 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002576 if (mKeyboardVisible != visible) {
2577 mKeyboardVisible = visible;
2578 // don't signal user activity if the screen is off; other code
2579 // will take care of turning on due to a true change to the lid
2580 // switch and synchronized with the lock screen.
2581 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002582 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002583 // force recompute of backlight values
2584 if (mLightSensorValue >= 0) {
2585 int value = (int)mLightSensorValue;
2586 mLightSensorValue = -1;
2587 lightSensorChangedLocked(value);
2588 }
2589 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002590 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2591 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002592 }
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595
2596 /**
2597 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002598 * When disabling user activity we also reset user power state so the keyguard can reset its
2599 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 */
2601 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002602 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002603 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 synchronized (mLocks) {
2606 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002607 if (!enabled) {
2608 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2609 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
2613
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002614 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002615 synchronized (mLocks) {
2616 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2617 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2618 mAutoBrightessEnabled = enabled;
2619 // This will get us a new value
2620 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002621 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002622 }
2623 }
2624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 /** Sets the screen off timeouts:
2626 * mKeylightDelay
2627 * mDimDelay
2628 * mScreenOffDelay
2629 * */
2630 private void setScreenOffTimeoutsLocked() {
2631 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002632 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002633 mDimDelay = -1;
2634 mScreenOffDelay = 0;
2635 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2636 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2637 mDimDelay = -1;
2638 mScreenOffDelay = 0;
2639 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002640 int totalDelay = mScreenOffTimeoutSetting;
2641 if (totalDelay > mMaximumScreenOffTimeout) {
2642 totalDelay = mMaximumScreenOffTimeout;
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2645 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002646 // negative number means stay on as long as possible.
2647 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 } else if (mKeylightDelay < totalDelay) {
2649 // subtract the time that the keylight delay. This will give us the
2650 // remainder of the time that we need to sleep to get the accurate
2651 // screen off timeout.
2652 mScreenOffDelay = totalDelay - mKeylightDelay;
2653 } else {
2654 mScreenOffDelay = 0;
2655 }
2656 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2657 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2658 mScreenOffDelay = LONG_DIM_TIME;
2659 } else {
2660 mDimDelay = -1;
2661 }
2662 }
2663 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002664 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2666 + " mDimScreen=" + mDimScreen);
2667 }
2668 }
2669
2670 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002671 * Refreshes cached secure settings. Called once on startup, and
2672 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 */
Doug Zongker43866e02010-01-07 12:09:54 -08002674 private void updateSettingsValues() {
2675 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002677 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002679 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 }
2681
2682 private class LockList extends ArrayList<WakeLock>
2683 {
2684 void addLock(WakeLock wl)
2685 {
2686 int index = getIndex(wl.binder);
2687 if (index < 0) {
2688 this.add(wl);
2689 }
2690 }
2691
2692 WakeLock removeLock(IBinder binder)
2693 {
2694 int index = getIndex(binder);
2695 if (index >= 0) {
2696 return this.remove(index);
2697 } else {
2698 return null;
2699 }
2700 }
2701
2702 int getIndex(IBinder binder)
2703 {
2704 int N = this.size();
2705 for (int i=0; i<N; i++) {
2706 if (this.get(i).binder == binder) {
2707 return i;
2708 }
2709 }
2710 return -1;
2711 }
2712
2713 int gatherState()
2714 {
2715 int result = 0;
2716 int N = this.size();
2717 for (int i=0; i<N; i++) {
2718 WakeLock wl = this.get(i);
2719 if (wl.activated) {
2720 if (isScreenLock(wl.flags)) {
2721 result |= wl.minState;
2722 }
2723 }
2724 }
2725 return result;
2726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Michael Chane96440f2009-05-06 10:27:36 -07002728 int reactivateScreenLocksLocked()
2729 {
2730 int result = 0;
2731 int N = this.size();
2732 for (int i=0; i<N; i++) {
2733 WakeLock wl = this.get(i);
2734 if (isScreenLock(wl.flags)) {
2735 wl.activated = true;
2736 result |= wl.minState;
2737 }
2738 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002739 if (mDebugProximitySensor) {
2740 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2741 + mProxIgnoredBecauseScreenTurnedOff);
2742 }
2743 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002744 return result;
2745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002748 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 synchronized (mLocks) {
2750 mPolicy = p;
2751 mLocks.notifyAll();
2752 }
2753 }
2754
2755 WindowManagerPolicy getPolicyLocked() {
2756 while (mPolicy == null || !mDoneBooting) {
2757 try {
2758 mLocks.wait();
2759 } catch (InterruptedException e) {
2760 // Ignore
2761 }
2762 }
2763 return mPolicy;
2764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002767 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2768 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2769 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002770 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002771 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002772 }
2773
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002774 // wait until sensors are enabled before turning on screen.
2775 // some devices will not activate the light sensor properly on boot
2776 // unless we do this.
2777 if (mUseSoftwareAutoBrightness) {
2778 // turn the screen on
2779 setPowerState(SCREEN_BRIGHT);
2780 } else {
2781 // turn everything on
2782 setPowerState(ALL_BRIGHT);
2783 }
2784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002786 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002788
Joe Onoratod28f7532010-11-06 12:56:53 -07002789 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2790
Dianne Hackborn617f8772009-03-31 15:04:46 -07002791 long identity = Binder.clearCallingIdentity();
2792 try {
2793 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2794 mBatteryStats.noteScreenOn();
2795 } catch (RemoteException e) {
2796 // Nothing interesting to do.
2797 } finally {
2798 Binder.restoreCallingIdentity(identity);
2799 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002800 }
2801 }
2802
2803 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002804 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002805 synchronized (mLocks) {
2806 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2808 updateWakeLockLocked();
2809 mLocks.notifyAll();
2810 }
2811 }
2812
Joe Onoratob08a1af2010-10-11 19:28:58 -07002813 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 public void monitor() {
2815 synchronized (mLocks) { }
2816 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002817
2818 public int getSupportedWakeLockFlags() {
2819 int result = PowerManager.PARTIAL_WAKE_LOCK
2820 | PowerManager.FULL_WAKE_LOCK
2821 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2822
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002823 if (mProximitySensor != null) {
2824 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2825 }
2826
2827 return result;
2828 }
2829
Mike Lockwood237a2992009-09-15 14:42:16 -04002830 public void setBacklightBrightness(int brightness) {
2831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2832 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002833 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002834 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002835 mLcdLight.setBrightness(brightness);
2836 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2837 mButtonLight.setBrightness(brightness);
2838 long identity = Binder.clearCallingIdentity();
2839 try {
2840 mBatteryStats.noteScreenBrightness(brightness);
2841 } catch (RemoteException e) {
2842 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2843 } finally {
2844 Binder.restoreCallingIdentity(identity);
2845 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002846
Joe Onoratob08a1af2010-10-11 19:28:58 -07002847 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002848 synchronized (mLocks) {
2849 mScreenBrightness.targetValue = brightness;
2850 mScreenBrightness.jumpToTargetLocked();
2851 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002852 }
2853 }
2854
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002855 public void setAttentionLight(boolean on, int color) {
2856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002857 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002858 }
2859
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002860 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002861 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002862 Slog.d(TAG, "enableProximityLockLocked");
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.registerListener(mProximityListener, mProximitySensor,
2869 SensorManager.SENSOR_DELAY_NORMAL);
2870 mProximitySensorEnabled = true;
2871 } finally {
2872 Binder.restoreCallingIdentity(identity);
2873 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002874 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002875 }
2876
2877 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002878 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002879 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002880 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002881 if (mProximitySensorEnabled) {
2882 // clear calling identity so sensor manager battery stats are accurate
2883 long identity = Binder.clearCallingIdentity();
2884 try {
2885 mSensorManager.unregisterListener(mProximityListener);
2886 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002887 if (mProximityPartialLock.isHeld()) {
2888 mProximityPartialLock.release();
2889 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002890 mProximitySensorEnabled = false;
2891 } finally {
2892 Binder.restoreCallingIdentity(identity);
2893 }
2894 if (mProximitySensorActive) {
2895 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002896 if (mDebugProximitySensor) {
2897 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2898 + mProxIgnoredBecauseScreenTurnedOff);
2899 }
2900 if (!mProxIgnoredBecauseScreenTurnedOff) {
2901 forceUserActivityLocked();
2902 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002903 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002904 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002905 }
2906
Mike Lockwood20f87d72009-11-05 16:08:51 -05002907 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002908 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002909 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002910 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002911 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002912 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002913 return;
2914 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002915 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002916 if (mDebugProximitySensor) {
2917 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2918 + mProxIgnoredBecauseScreenTurnedOff);
2919 }
2920 if (!mProxIgnoredBecauseScreenTurnedOff) {
2921 goToSleepLocked(SystemClock.uptimeMillis(),
2922 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2923 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002924 mProximitySensorActive = true;
2925 } else {
2926 // proximity sensor negative events trigger as user activity.
2927 // temporarily set mUserActivityAllowed to true so this will work
2928 // even when the keyguard is on.
2929 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002930 if (mDebugProximitySensor) {
2931 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2932 + mProxIgnoredBecauseScreenTurnedOff);
2933 }
2934 if (!mProxIgnoredBecauseScreenTurnedOff) {
2935 forceUserActivityLocked();
2936 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002937
2938 if (mProximityWakeLockCount == 0) {
2939 // disable sensor if we have no listeners left after proximity negative
2940 disableProximityLockLocked();
2941 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002942 }
2943 }
2944
Joe Onoratod28f7532010-11-06 12:56:53 -07002945 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002946 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002947 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2948 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2949 }
2950 if (!mAutoBrightessEnabled) {
2951 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002952 }
2953 if (mSensorManager != null && mLightSensorEnabled != enable) {
2954 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002955 // clear calling identity so sensor manager battery stats are accurate
2956 long identity = Binder.clearCallingIdentity();
2957 try {
2958 if (enable) {
2959 mSensorManager.registerListener(mLightListener, mLightSensor,
2960 SensorManager.SENSOR_DELAY_NORMAL);
2961 } else {
2962 mSensorManager.unregisterListener(mLightListener);
2963 mHandler.removeCallbacks(mAutoBrightnessTask);
2964 }
2965 } finally {
2966 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002967 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002968 }
2969 }
2970
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002971 SensorEventListener mProximityListener = new SensorEventListener() {
2972 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002973 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002974 synchronized (mLocks) {
2975 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002976 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2977 mLastProximityEventTime = milliseconds;
2978 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002979 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002980
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002981 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002982 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2983 distance < mProximitySensor.getMaximumRange());
2984
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002985 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002987 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002988 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2989 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2990 mProximityPendingValue = (active ? 1 : 0);
2991 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002992 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002993 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002994 // process the value immediately
2995 mProximityPendingValue = -1;
2996 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002997 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002998
2999 // update mProximityPartialLock state
3000 boolean held = mProximityPartialLock.isHeld();
3001 if (!held && proximityTaskQueued) {
3002 // hold wakelock until mProximityTask runs
3003 mProximityPartialLock.acquire();
3004 } else if (held && !proximityTaskQueued) {
3005 mProximityPartialLock.release();
3006 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003007 }
3008 }
3009
3010 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3011 // ignore
3012 }
3013 };
3014
3015 SensorEventListener mLightListener = new SensorEventListener() {
3016 public void onSensorChanged(SensorEvent event) {
3017 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003018 // ignore light sensor while screen is turning off
3019 if (isScreenTurningOffLocked()) {
3020 return;
3021 }
3022
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003023 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003024 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003025 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003026 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003027 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05003028 if (mLightSensorValue == -1 ||
3029 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3030 // process the value immediately if screen has just turned on
3031 mHandler.removeCallbacks(mAutoBrightnessTask);
3032 mLightSensorPendingDecrease = false;
3033 mLightSensorPendingIncrease = false;
3034 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003035 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003036 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3037 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3038 (value == mLightSensorValue) ||
3039 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3040 // delay processing to debounce the sensor
3041 mHandler.removeCallbacks(mAutoBrightnessTask);
3042 mLightSensorPendingDecrease = (value < mLightSensorValue);
3043 mLightSensorPendingIncrease = (value > mLightSensorValue);
3044 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3045 mLightSensorPendingValue = value;
3046 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3047 }
3048 } else {
3049 mLightSensorPendingValue = value;
3050 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003051 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003052 }
3053 }
3054
3055 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3056 // ignore
3057 }
3058 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059}