blob: 774495ac76342a01f8ea83a48038a1ec29276edc [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
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -070082 static final boolean DEBUG_SCREEN_ON = false;
83
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final boolean LOG_PARTIAL_WL = false;
85
86 // Indicates whether touch-down cycles should be logged as part of the
87 // LOG_POWER_SCREEN_STATE log events
88 private static final boolean LOG_TOUCH_DOWNS = true;
89
90 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
91 | PowerManager.SCREEN_DIM_WAKE_LOCK
92 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070093 | PowerManager.FULL_WAKE_LOCK
94 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
96 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080097 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
99 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
100 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
101 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
102
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800103 // How long to wait to debounce light sensor changes in milliseconds
Mike Lockwood9b8136922009-11-06 15:53:59 -0500104 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700105
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800106 // light sensor events rate in microseconds
107 private static final int LIGHT_SENSOR_RATE = 1000000;
108
109 // For debouncing the proximity sensor in milliseconds
Mike Lockwood20f87d72009-11-05 16:08:51 -0500110 private static final int PROXIMITY_SENSOR_DELAY = 1000;
111
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400112 // trigger proximity if distance is less than 5 cm
113 private static final float PROXIMITY_THRESHOLD = 5.0f;
114
Doug Zongker43866e02010-01-07 12:09:54 -0800115 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
117
Amith Yamasani8b619832010-09-22 16:11:59 -0700118 // Default timeout for screen off, if not found in settings database = 15 seconds.
119 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 // flags for setPowerState
122 private static final int SCREEN_ON_BIT = 0x00000001;
123 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
124 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
125 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
126 private static final int BATTERY_LOW_BIT = 0x00000010;
127
128 // values for setPowerState
129
130 // SCREEN_OFF == everything off
131 private static final int SCREEN_OFF = 0x00000000;
132
133 // SCREEN_DIM == screen on, screen backlight dim
134 private static final int SCREEN_DIM = SCREEN_ON_BIT;
135
136 // SCREEN_BRIGHT == screen on, screen backlight bright
137 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
138
139 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
140 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
141
142 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
143 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
144
145 // used for noChangeLights in setPowerState()
146 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
147
Joe Onoratob08a1af2010-10-11 19:28:58 -0700148 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400151 // Slower animation for autobrightness changes
152 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154 // These magic numbers are the initial state of the LEDs at boot. Ideally
155 // we should read them from the driver, but our current hardware returns 0
156 // for the initial value. Oops!
157 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
158 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
159 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700162 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
164 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500165 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500167 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
168 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700169 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700170 private boolean mSkippedScreenOn = false;
171 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private int mPartialCount = 0;
173 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500174 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
175 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
176 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private int mUserState;
178 private boolean mKeyboardVisible = false;
179 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500180 private int mProximityWakeLockCount = 0;
181 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700182 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500183 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
184 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800185 private int mScreenOffTimeoutSetting;
186 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private int mKeylightDelay;
188 private int mDimDelay;
189 private int mScreenOffDelay;
190 private int mWakeLockState;
191 private long mLastEventTime = 0;
192 private long mScreenOffTime;
193 private volatile WindowManagerPolicy mPolicy;
194 private final LockList mLocks = new LockList();
195 private Intent mScreenOffIntent;
196 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500197 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500199 private LightsService.Light mLcdLight;
200 private LightsService.Light mButtonLight;
201 private LightsService.Light mKeyboardLight;
202 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private UnsynchronizedWakeLock mBroadcastWakeLock;
204 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
205 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
206 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500207 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700209 private HandlerThread mScreenOffThread;
210 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500212 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700214 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700215 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 private boolean mIsPowered = false;
217 private IActivityManager mActivityService;
218 private IBatteryStats mBatteryStats;
219 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700220 private SensorManager mSensorManager;
221 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400222 private Sensor mLightSensor;
223 private boolean mLightSensorEnabled;
224 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400225 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500226 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500227 private boolean mLightSensorPendingDecrease = false;
228 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700229 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500230 private int mLightSensorScreenBrightness = -1;
231 private int mLightSensorButtonBrightness = -1;
232 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500234 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private long mNextTimeout;
236 private volatile int mPokey = 0;
237 private volatile boolean mPokeAwakeOnSet = false;
238 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500239 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500240 // mLastScreenOnTime is the time the screen was last turned on
241 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 private boolean mPreventScreenOn;
243 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500244 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400245 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400246 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700247 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700248 private int[] mAutoBrightnessLevels;
249 private int[] mLcdBacklightValues;
250 private int[] mButtonBacklightValues;
251 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500252 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700253 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700254 private int mWarningSpewThrottleCount;
255 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700256 private int mAnimationSetting = ANIM_SETTING_OFF;
257
258 // Must match with the ISurfaceComposer constants in C++.
259 private static final int ANIM_SETTING_ON = 0x01;
260 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
262 // Used when logging number and duration of touch-down cycles
263 private long mTotalTouchDownTime;
264 private long mLastTouchDown;
265 private int mTouchCycles;
266
267 // could be either static or controllable at runtime
268 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400269 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwoodae92eb32011-10-25 10:11:46 -0400270 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700271
272 private native void nativeInit();
273 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700274 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275
276 /*
277 static PrintStream mLog;
278 static {
279 try {
280 mLog = new PrintStream("/data/power.log");
281 }
282 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800283 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285 }
286 static class Log {
287 static void d(String tag, String s) {
288 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800289 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291 static void i(String tag, String s) {
292 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800293 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295 static void w(String tag, String s) {
296 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800297 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 }
299 static void e(String tag, String s) {
300 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800301 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 }
303 }
304 */
305
306 /**
307 * This class works around a deadlock between the lock in PowerManager.WakeLock
308 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
309 * mToken object so it can be accessed from any thread, but it calls into here
310 * with its lock held. This class is essentially a reimplementation of
311 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
312 * only call it with our own locks held.
313 */
314 private class UnsynchronizedWakeLock {
315 int mFlags;
316 String mTag;
317 IBinder mToken;
318 int mCount = 0;
319 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500320 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
323 mFlags = flags;
324 mTag = tag;
325 mToken = new Binder();
326 mRefCounted = refCounted;
327 }
328
329 public void acquire() {
330 if (!mRefCounted || mCount++ == 0) {
331 long ident = Binder.clearCallingIdentity();
332 try {
333 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700334 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500335 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 } finally {
337 Binder.restoreCallingIdentity(ident);
338 }
339 }
340 }
341
342 public void release() {
343 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500344 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500345 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
347 if (mCount < 0) {
348 throw new RuntimeException("WakeLock under-locked " + mTag);
349 }
350 }
351
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500352 public boolean isHeld()
353 {
354 return mHeld;
355 }
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 public String toString() {
358 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500359 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361 }
362
363 private final class BatteryReceiver extends BroadcastReceiver {
364 @Override
365 public void onReceive(Context context, Intent intent) {
366 synchronized (mLocks) {
367 boolean wasPowered = mIsPowered;
368 mIsPowered = mBatteryService.isPowered();
369
370 if (mIsPowered != wasPowered) {
371 // update mStayOnWhilePluggedIn wake lock
372 updateWakeLockLocked();
373
374 // treat plugging and unplugging the devices as a user activity.
375 // users find it disconcerting when they unplug the device
376 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500377 // to avoid turning on the screen when unplugging, we only trigger
378 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 // temporarily set mUserActivityAllowed to true so this will work
380 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700381 // However, you can also set config_unplugTurnsOnScreen to have it
382 // turn on. Some devices want this because they don't have a
383 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700385 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
386 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500387 forceUserActivityLocked();
388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 }
390 }
391 }
392 }
393 }
394
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500395 private final class BootCompletedReceiver extends BroadcastReceiver {
396 @Override
397 public void onReceive(Context context, Intent intent) {
398 bootCompleted();
399 }
400 }
401
Mike Lockwoodb2865412010-02-02 22:40:33 -0500402 private final class DockReceiver extends BroadcastReceiver {
403 @Override
404 public void onReceive(Context context, Intent intent) {
405 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
406 Intent.EXTRA_DOCK_STATE_UNDOCKED);
407 dockStateChanged(state);
408 }
409 }
410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 /**
412 * Set the setting that determines whether the device stays on when plugged in.
413 * The argument is a bit string, with each bit specifying a power source that,
414 * when the device is connected to that source, causes the device to stay on.
415 * See {@link android.os.BatteryManager} for the list of power sources that
416 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
417 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
418 * @param val an {@code int} containing the bits that specify which power sources
419 * should cause the device to stay on.
420 */
421 public void setStayOnSetting(int val) {
422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
423 Settings.System.putInt(mContext.getContentResolver(),
424 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
425 }
426
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800427 public void setMaximumScreenOffTimeount(int timeMs) {
428 mContext.enforceCallingOrSelfPermission(
429 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
430 synchronized (mLocks) {
431 mMaximumScreenOffTimeout = timeMs;
432 // recalculate everything
433 setScreenOffTimeoutsLocked();
434 }
435 }
436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700438 private int getInt(String name, int defValue) {
439 ContentValues values = mSettings.getValues(name);
440 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
441 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
443
Joe Onorato609695d2010-10-14 14:57:49 -0700444 private float getFloat(String name, float defValue) {
445 ContentValues values = mSettings.getValues(name);
446 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
447 return fVal != null ? fVal : defValue;
448 }
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 public void update(Observable o, Object arg) {
451 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700452 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
453 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
454 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 updateWakeLockLocked();
456
Amith Yamasani8b619832010-09-22 16:11:59 -0700457 // SCREEN_OFF_TIMEOUT, default to 15 seconds
458 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459
Joe Onorato609695d2010-10-14 14:57:49 -0700460 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 //mDimScreen = getInt(DIM_SCREEN) != 0;
462
Amith Yamasani8b619832010-09-22 16:11:59 -0700463 // SCREEN_BRIGHTNESS_MODE, default to manual
464 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
465 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 // recalculate everything
468 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700469
470 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
471 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
472 mAnimationSetting = 0;
473 if (windowScale > 0.5f) {
474 mAnimationSetting |= ANIM_SETTING_OFF;
475 }
476 if (transitionScale > 0.5f) {
477 // Uncomment this if you want the screen-on animation.
478 // mAnimationSetting |= ANIM_SETTING_ON;
479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 }
481 }
482 }
483
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700484 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 // Hack to get our uid... should have a func for this.
486 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700487 MY_UID = Process.myUid();
488 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 Binder.restoreCallingIdentity(token);
490
491 // XXX remove this when the kernel doesn't timeout wake locks
492 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
493
494 // assume nothing is on yet
495 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 // Add ourself to the Watchdog monitors.
498 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
501 private ContentQueryMap mSettings;
502
Mike Lockwood3a322132009-11-24 00:30:52 -0500503 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700504 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500505 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 mContext = context;
507 mActivityService = activity;
508 mBatteryStats = BatteryStatsService.getService();
509 mBatteryService = battery;
510
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500511 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
512 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
513 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
514 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
515
Joe Onoratob08a1af2010-10-11 19:28:58 -0700516 nativeInit();
517 synchronized (mLocks) {
518 updateNativePowerStateLocked();
519 }
520
521 mInitComplete = false;
522 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
523 @Override
524 protected void onLooperPrepared() {
525 mScreenOffHandler = new Handler();
526 synchronized (mScreenOffThread) {
527 mInitComplete = true;
528 mScreenOffThread.notifyAll();
529 }
530 }
531 };
532 mScreenOffThread.start();
533
534 synchronized (mScreenOffThread) {
535 while (!mInitComplete) {
536 try {
537 mScreenOffThread.wait();
538 } catch (InterruptedException e) {
539 // Ignore
540 }
541 }
542 }
543
544 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mHandlerThread = new HandlerThread("PowerManagerService") {
546 @Override
547 protected void onLooperPrepared() {
548 super.onLooperPrepared();
549 initInThread();
550 }
551 };
552 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 synchronized (mHandlerThread) {
555 while (!mInitComplete) {
556 try {
557 mHandlerThread.wait();
558 } catch (InterruptedException e) {
559 // Ignore
560 }
561 }
562 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700563
564 nativeInit();
565 synchronized (mLocks) {
566 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700567 // We make sure to start out with the screen on due to user activity.
568 // (They did just boot their device, after all.)
569 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700570 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 void initInThread() {
575 mHandler = new Handler();
576
577 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700578 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
580 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
581 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
582 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
583 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
584 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500585 mProximityPartialLock = new UnsynchronizedWakeLock(
586 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
589 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
590 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
591 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
592
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700593 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400594
Joe Onoratob08a1af2010-10-11 19:28:58 -0700595 mAnimateScreenLights = resources.getBoolean(
596 com.android.internal.R.bool.config_animateScreenLights);
597
Joe Onorato6d747652010-10-11 15:15:31 -0700598 mUnplugTurnsOnScreen = resources.getBoolean(
599 com.android.internal.R.bool.config_unplugTurnsOnScreen);
600
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400601 mScreenBrightnessDim = resources.getInteger(
602 com.android.internal.R.integer.config_screenBrightnessDim);
603
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400604 // read settings for auto-brightness
605 mUseSoftwareAutoBrightness = resources.getBoolean(
606 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400607 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700608 mAutoBrightnessLevels = resources.getIntArray(
609 com.android.internal.R.array.config_autoBrightnessLevels);
610 mLcdBacklightValues = resources.getIntArray(
611 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
612 mButtonBacklightValues = resources.getIntArray(
613 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
614 mKeyboardBacklightValues = resources.getIntArray(
615 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500616 mLightSensorWarmupTime = resources.getInteger(
617 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700618 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700619
620 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
622 "(" + Settings.System.NAME + "=?) or ("
623 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700624 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700625 + Settings.System.NAME + "=?) or ("
626 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700628 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700629 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 null);
631 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
632 SettingsObserver settingsObserver = new SettingsObserver();
633 mSettings.addObserver(settingsObserver);
634
635 // pretend that the settings changed so we will get their initial state
636 settingsObserver.update(mSettings, null);
637
638 // register for the battery changed notifications
639 IntentFilter filter = new IntentFilter();
640 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
641 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500642 filter = new IntentFilter();
643 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
644 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500645 filter = new IntentFilter();
646 filter.addAction(Intent.ACTION_DOCK_EVENT);
647 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648
Doug Zongker43866e02010-01-07 12:09:54 -0800649 // Listen for secure settings changes
650 mContext.getContentResolver().registerContentObserver(
651 Settings.Secure.CONTENT_URI, true,
652 new ContentObserver(new Handler()) {
653 public void onChange(boolean selfChange) {
654 updateSettingsValues();
655 }
656 });
657 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 synchronized (mHandlerThread) {
660 mInitComplete = true;
661 mHandlerThread.notifyAll();
662 }
663 }
664
665 private class WakeLock implements IBinder.DeathRecipient
666 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700667 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 super();
669 flags = f;
670 binder = b;
671 tag = t;
672 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700673 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 if (u != MY_UID || (
675 !"KEEP_SCREEN_ON_FLAG".equals(tag)
676 && !"KeyInputQueue".equals(tag))) {
677 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
678 ? BatteryStats.WAKE_TYPE_PARTIAL
679 : BatteryStats.WAKE_TYPE_FULL;
680 } else {
681 monitorType = -1;
682 }
683 try {
684 b.linkToDeath(this, 0);
685 } catch (RemoteException e) {
686 binderDied();
687 }
688 }
689 public void binderDied() {
690 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500691 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
693 }
694 final int flags;
695 final IBinder binder;
696 final String tag;
697 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400698 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700700 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 boolean activated = true;
702 int minState;
703 }
704
705 private void updateWakeLockLocked() {
706 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
707 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
708 mStayOnWhilePluggedInScreenDimLock.acquire();
709 mStayOnWhilePluggedInPartialLock.acquire();
710 } else {
711 mStayOnWhilePluggedInScreenDimLock.release();
712 mStayOnWhilePluggedInPartialLock.release();
713 }
714 }
715
716 private boolean isScreenLock(int flags)
717 {
718 int n = flags & LOCK_MASK;
719 return n == PowerManager.FULL_WAKE_LOCK
720 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400721 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
722 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
724
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700725 void enforceWakeSourcePermission(int uid, int pid) {
726 if (uid == Process.myUid()) {
727 return;
728 }
729 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
730 pid, uid, null);
731 }
732
733 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700735 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700736 if (uid != Process.myUid()) {
737 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
738 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700739 if (ws != null) {
740 enforceWakeSourcePermission(uid, pid);
741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 long ident = Binder.clearCallingIdentity();
743 try {
744 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700745 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747 } finally {
748 Binder.restoreCallingIdentity(ident);
749 }
750 }
751
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700752 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700753 if (wl.monitorType >= 0) {
754 long origId = Binder.clearCallingIdentity();
755 try {
756 if (ws != null) {
757 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
758 wl.monitorType);
759 } else {
760 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
761 }
762 } catch (RemoteException e) {
763 // Ignore
764 } finally {
765 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700766 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700767 }
768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700770 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700771 if (wl.monitorType >= 0) {
772 long origId = Binder.clearCallingIdentity();
773 try {
774 if (ws != null) {
775 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
776 wl.monitorType);
777 } else {
778 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
779 }
780 } catch (RemoteException e) {
781 // Ignore
782 } finally {
783 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700784 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700785 }
786 }
787
788 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
789 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800791 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 }
793
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700794 if (ws != null && ws.size() == 0) {
795 ws = null;
796 }
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 int index = mLocks.getIndex(lock);
799 WakeLock wl;
800 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700801 boolean diffsource;
802 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700804 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 switch (wl.flags & LOCK_MASK)
806 {
807 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500808 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400809 wl.minState = SCREEN_BRIGHT;
810 } else {
811 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 break;
814 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
815 wl.minState = SCREEN_BRIGHT;
816 break;
817 case PowerManager.SCREEN_DIM_WAKE_LOCK:
818 wl.minState = SCREEN_DIM;
819 break;
820 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700821 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 break;
823 default:
824 // just log and bail. we're in the server, so don't
825 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800826 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 + " flags=" + flags);
828 return;
829 }
830 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700831 if (ws != null) {
832 wl.ws = new WorkSource(ws);
833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700835 diffsource = false;
836 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 } else {
838 wl = mLocks.get(index);
839 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700840 oldsource = wl.ws;
841 if (oldsource != null) {
842 if (ws == null) {
843 wl.ws = null;
844 diffsource = true;
845 } else {
846 diffsource = oldsource.diff(ws);
847 }
848 } else if (ws != null) {
849 diffsource = true;
850 } else {
851 diffsource = false;
852 }
853 if (diffsource) {
854 wl.ws = new WorkSource(ws);
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 if (isScreenLock(flags)) {
858 // if this causes a wakeup, we reactivate all of the locks and
859 // set it to whatever they want. otherwise, we modulate that
860 // by the current state so we never turn it more on than
861 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400862 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
863 mProximityWakeLockCount++;
864 if (mProximityWakeLockCount == 1) {
865 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400868 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
869 int oldWakeLockState = mWakeLockState;
870 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400871
872 // Disable proximity sensor if if user presses power key while we are in the
873 // "waiting for proximity sensor to go negative" state.
874 if ((mWakeLockState & SCREEN_ON_BIT) != 0
875 && mProximitySensorActive && mProximityWakeLockCount == 0) {
876 mProximitySensorActive = false;
877 }
878
Joe Onorato8274a0e2010-10-05 17:38:09 -0400879 if (mSpew) {
880 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
881 + " mWakeLockState=0x"
882 + Integer.toHexString(mWakeLockState)
883 + " previous wakeLockState=0x"
884 + Integer.toHexString(oldWakeLockState));
885 }
886 } else {
887 if (mSpew) {
888 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
889 + " mLocks.gatherState()=0x"
890 + Integer.toHexString(mLocks.gatherState())
891 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
892 }
893 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400895 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
899 if (newlock) {
900 mPartialCount++;
901 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800902 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904 }
905 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700908 if (diffsource) {
909 // If the lock sources have changed, need to first release the
910 // old ones.
911 noteStopWakeLocked(wl, oldsource);
912 }
913 if (newlock || diffsource) {
914 noteStartWakeLocked(wl, ws);
915 }
916 }
917
918 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
919 int uid = Binder.getCallingUid();
920 int pid = Binder.getCallingPid();
921 if (ws != null && ws.size() == 0) {
922 ws = null;
923 }
924 if (ws != null) {
925 enforceWakeSourcePermission(uid, pid);
926 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700927 synchronized (mLocks) {
928 int index = mLocks.getIndex(lock);
929 if (index < 0) {
930 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700932 WakeLock wl = mLocks.get(index);
933 WorkSource oldsource = wl.ws;
934 wl.ws = ws != null ? new WorkSource(ws) : null;
935 noteStopWakeLocked(wl, oldsource);
936 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938 }
939
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500940 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700941 int uid = Binder.getCallingUid();
942 if (uid != Process.myUid()) {
943 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945
946 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500947 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949 }
950
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500951 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 WakeLock wl = mLocks.removeLock(lock);
953 if (wl == null) {
954 return;
955 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800958 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
960 }
961
962 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400963 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
964 mProximityWakeLockCount--;
965 if (mProximityWakeLockCount == 0) {
966 if (mProximitySensorActive &&
967 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
968 // wait for proximity sensor to go negative before disabling sensor
969 if (mDebugProximitySensor) {
970 Slog.d(TAG, "waiting for proximity sensor to go negative");
971 }
972 } else {
973 disableProximityLockLocked();
974 }
975 }
976 } else {
977 mWakeLockState = mLocks.gatherState();
978 // goes in the middle to reduce flicker
979 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
980 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
981 }
982 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
986 mPartialCount--;
987 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800988 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 Power.releaseWakeLock(PARTIAL_NAME);
990 }
991 }
992 // Unlink the lock from the binder.
993 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
Dianne Hackborn70be1672010-09-14 11:13:03 -0700995 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 private class PokeLock implements IBinder.DeathRecipient
999 {
1000 PokeLock(int p, IBinder b, String t) {
1001 super();
1002 this.pokey = p;
1003 this.binder = b;
1004 this.tag = t;
1005 try {
1006 b.linkToDeath(this, 0);
1007 } catch (RemoteException e) {
1008 binderDied();
1009 }
1010 }
1011 public void binderDied() {
1012 setPokeLock(0, this.binder, this.tag);
1013 }
1014 int pokey;
1015 IBinder binder;
1016 String tag;
1017 boolean awakeOnSet;
1018 }
1019
1020 public void setPokeLock(int pokey, IBinder token, String tag) {
1021 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1022 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001023 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 return;
1025 }
1026
1027 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1028 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1029 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1030 }
1031
1032 synchronized (mLocks) {
1033 if (pokey != 0) {
1034 PokeLock p = mPokeLocks.get(token);
1035 int oldPokey = 0;
1036 if (p != null) {
1037 oldPokey = p.pokey;
1038 p.pokey = pokey;
1039 } else {
1040 p = new PokeLock(pokey, token, tag);
1041 mPokeLocks.put(token, p);
1042 }
1043 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1044 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1045 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1046 p.awakeOnSet = true;
1047 }
1048 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001049 PokeLock rLock = mPokeLocks.remove(token);
1050 if (rLock != null) {
1051 token.unlinkToDeath(rLock, 0);
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054
1055 int oldPokey = mPokey;
1056 int cumulative = 0;
1057 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1058 boolean awakeOnSet = false;
1059 for (PokeLock p: mPokeLocks.values()) {
1060 cumulative |= p.pokey;
1061 if (p.awakeOnSet) {
1062 awakeOnSet = true;
1063 }
1064 }
1065 mPokey = cumulative;
1066 mPokeAwakeOnSet = awakeOnSet;
1067
1068 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1069 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (oldCumulativeTimeout != newCumulativeTimeout) {
1072 setScreenOffTimeoutsLocked();
1073 // reset the countdown timer, but use the existing nextState so it doesn't
1074 // change anything
1075 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1076 }
1077 }
1078 }
1079
1080 private static String lockType(int type)
1081 {
1082 switch (type)
1083 {
1084 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001085 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001087 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001089 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001091 return "PARTIAL_WAKE_LOCK ";
1092 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1093 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 default:
David Brown251faa62009-08-02 22:04:36 -07001095 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 }
1097 }
1098
1099 private static String dumpPowerState(int state) {
1100 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1101 ? "KEYBOARD_BRIGHT_BIT " : "")
1102 + (((state & SCREEN_BRIGHT_BIT) != 0)
1103 ? "SCREEN_BRIGHT_BIT " : "")
1104 + (((state & SCREEN_ON_BIT) != 0)
1105 ? "SCREEN_ON_BIT " : "")
1106 + (((state & BATTERY_LOW_BIT) != 0)
1107 ? "BATTERY_LOW_BIT " : "");
1108 }
1109
1110 @Override
1111 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1112 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1113 != PackageManager.PERMISSION_GRANTED) {
1114 pw.println("Permission Denial: can't dump PowerManager from from pid="
1115 + Binder.getCallingPid()
1116 + ", uid=" + Binder.getCallingUid());
1117 return;
1118 }
1119
1120 long now = SystemClock.uptimeMillis();
1121
Mike Lockwoodca44df82010-02-25 13:48:49 -05001122 synchronized (mLocks) {
1123 pw.println("Power Manager State:");
1124 pw.println(" mIsPowered=" + mIsPowered
1125 + " mPowerState=" + mPowerState
1126 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1127 + " ms");
1128 pw.println(" mPartialCount=" + mPartialCount);
1129 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1130 pw.println(" mUserState=" + dumpPowerState(mUserState));
1131 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1132 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1133 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1134 + " " + ((mNextTimeout-now)/1000) + "s from now");
1135 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001136 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001137 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1138 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001139 pw.println(" mScreenOffReason=" + mScreenOffReason
1140 + " mUserState=" + mUserState);
1141 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1142 + ',' + mBroadcastQueue[2] + "}");
1143 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1144 + ',' + mBroadcastWhy[2] + "}");
1145 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1146 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1147 + " mUserActivityAllowed=" + mUserActivityAllowed);
1148 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1149 + " mScreenOffDelay=" + mScreenOffDelay);
1150 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1151 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1152 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1153 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1154 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1155 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1156 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1157 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1158 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1159 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1160 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1161 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1162 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1163 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1164 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1165 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1166 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1167 pw.println(" mLightSensorValue=" + mLightSensorValue
1168 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001169 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1170 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001171 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1172 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1173 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1174 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1175 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1176 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001177
Mike Lockwoodca44df82010-02-25 13:48:49 -05001178 int N = mLocks.size();
1179 pw.println();
1180 pw.println("mLocks.size=" + N + ":");
1181 for (int i=0; i<N; i++) {
1182 WakeLock wl = mLocks.get(i);
1183 String type = lockType(wl.flags & LOCK_MASK);
1184 String acquireCausesWakeup = "";
1185 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1186 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1187 }
1188 String activated = "";
1189 if (wl.activated) {
1190 activated = " activated";
1191 }
1192 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001193 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1194 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001196
1197 pw.println();
1198 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1199 for (PokeLock p: mPokeLocks.values()) {
1200 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001201 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1202 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001203 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1204 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1205 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1206 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
Mike Lockwoodca44df82010-02-25 13:48:49 -05001209 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212
Joe Onorato7999bff2010-07-24 11:50:05 -04001213 private void setTimeoutLocked(long now, int nextState) {
1214 setTimeoutLocked(now, -1, nextState);
1215 }
1216
1217 // If they gave a timeoutOverride it is the number of seconds
1218 // to screen-off. Figure out where in the countdown cycle we
1219 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001220 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1221 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001222 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001223 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001224 long when = 0;
1225 if (timeoutOverride <= 0) {
1226 switch (nextState)
1227 {
1228 case SCREEN_BRIGHT:
1229 when = now + mKeylightDelay;
1230 break;
1231 case SCREEN_DIM:
1232 if (mDimDelay >= 0) {
1233 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001234 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001235 } else {
1236 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1237 }
1238 case SCREEN_OFF:
1239 synchronized (mLocks) {
1240 when = now + mScreenOffDelay;
1241 }
1242 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001243 default:
1244 when = now;
1245 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001247 } else {
1248 override: {
1249 if (timeoutOverride <= mScreenOffDelay) {
1250 when = now + timeoutOverride;
1251 nextState = SCREEN_OFF;
1252 break override;
1253 }
1254 timeoutOverride -= mScreenOffDelay;
1255
1256 if (mDimDelay >= 0) {
1257 if (timeoutOverride <= mDimDelay) {
1258 when = now + timeoutOverride;
1259 nextState = SCREEN_DIM;
1260 break override;
1261 }
1262 timeoutOverride -= mDimDelay;
1263 }
1264
1265 when = now + timeoutOverride;
1266 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001268 }
1269 if (mSpew) {
1270 Slog.d(TAG, "setTimeoutLocked now=" + now
1271 + " timeoutOverride=" + timeoutOverride
1272 + " nextState=" + nextState + " when=" + when);
1273 }
Joe Onorato797e6882010-08-26 14:46:01 -04001274
1275 mHandler.removeCallbacks(mTimeoutTask);
1276 mTimeoutTask.nextState = nextState;
1277 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1278 ? (originalTimeoutOverride - timeoutOverride)
1279 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001280 mHandler.postAtTime(mTimeoutTask, when);
1281 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 }
1284 }
1285
1286 private void cancelTimerLocked()
1287 {
1288 mHandler.removeCallbacks(mTimeoutTask);
1289 mTimeoutTask.nextState = -1;
1290 }
1291
1292 private class TimeoutTask implements Runnable
1293 {
1294 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001295 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 public void run()
1297 {
1298 synchronized (mLocks) {
1299 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001300 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302
1303 if (nextState == -1) {
1304 return;
1305 }
1306
1307 mUserState = this.nextState;
1308 setPowerState(this.nextState | mWakeLockState);
1309
1310 long now = SystemClock.uptimeMillis();
1311
1312 switch (this.nextState)
1313 {
1314 case SCREEN_BRIGHT:
1315 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001316 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 break;
1318 }
1319 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001320 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 break;
1322 }
1323 }
1324 }
1325 }
1326
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001327 private void sendNotificationLocked(boolean on, int why) {
1328 if (!mInitialized) {
1329 // No notifications sent until first initialization is done.
1330 // This is so that when we are moving from our initial state
1331 // which looks like the screen was off to it being on, we do not
1332 // go through the process of waiting for the higher-level user
1333 // space to be ready before turning up the display brightness.
1334 // (And also do not send needless broadcasts about the screen.)
1335 return;
1336 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001337
1338 if (DEBUG_SCREEN_ON) {
1339 RuntimeException here = new RuntimeException("here");
1340 here.fillInStackTrace();
1341 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1342 }
1343
Joe Onorato64c62ba2009-03-24 20:13:57 -07001344 if (!on) {
1345 mStillNeedSleepNotification = false;
1346 }
1347
Joe Onorato128e7292009-03-24 18:41:31 -07001348 // Add to the queue.
1349 int index = 0;
1350 while (mBroadcastQueue[index] != -1) {
1351 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
Joe Onorato128e7292009-03-24 18:41:31 -07001353 mBroadcastQueue[index] = on ? 1 : 0;
1354 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355
Joe Onorato128e7292009-03-24 18:41:31 -07001356 // If we added it position 2, then there is a pair that can be stripped.
1357 // If we added it position 1 and we're turning the screen off, we can strip
1358 // the pair and do nothing, because the screen is already off, and therefore
1359 // keyguard has already been enabled.
1360 // However, if we added it at position 1 and we're turning it on, then position
1361 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1362 // on, so have to run the queue then.
1363 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001364 // While we're collapsing them, if it's going off, and the new reason
1365 // is more significant than the first, then use the new one.
1366 if (!on && mBroadcastWhy[0] > why) {
1367 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001368 }
1369 mBroadcastQueue[0] = on ? 1 : 0;
1370 mBroadcastQueue[1] = -1;
1371 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001372 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001373 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001374 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001375 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001376 index = 0;
1377 }
1378 if (index == 1 && !on) {
1379 mBroadcastQueue[0] = -1;
1380 mBroadcastQueue[1] = -1;
1381 index = -1;
1382 // The wake lock was being held, but we're not actually going to do any
1383 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001384 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001386 }
1387
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001388 // The broadcast queue has changed; make sure the screen is on if it
1389 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001390 if (mSkippedScreenOn) {
1391 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1392 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001393
Joe Onorato128e7292009-03-24 18:41:31 -07001394 // Now send the message.
1395 if (index >= 0) {
1396 // Acquire the broadcast wake lock before changing the power
1397 // state. It will be release after the broadcast is sent.
1398 // We always increment the ref count for each notification in the queue
1399 // and always decrement when that notification is handled.
1400 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001401 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001402 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 }
1405
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001406 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1407 new WindowManagerPolicy.ScreenOnListener() {
1408 @Override public void onScreenOn() {
1409 synchronized (mLocks) {
1410 if (mPreparingForScreenOn) {
1411 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001412 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001413 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1414 4, mBroadcastWakeLock.mCount);
1415 mBroadcastWakeLock.release();
1416 }
1417 }
1418 }
1419 };
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 private Runnable mNotificationTask = new Runnable()
1422 {
1423 public void run()
1424 {
Joe Onorato128e7292009-03-24 18:41:31 -07001425 while (true) {
1426 int value;
1427 int why;
1428 WindowManagerPolicy policy;
1429 synchronized (mLocks) {
1430 value = mBroadcastQueue[0];
1431 why = mBroadcastWhy[0];
1432 for (int i=0; i<2; i++) {
1433 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1434 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1435 }
1436 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001437 if (value == 1 && !mPreparingForScreenOn) {
1438 mPreparingForScreenOn = true;
1439 mBroadcastWakeLock.acquire();
1440 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1441 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
Joe Onorato128e7292009-03-24 18:41:31 -07001444 if (value == 1) {
1445 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001447 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001448 try {
1449 ActivityManagerNative.getDefault().wakingUp();
1450 } catch (RemoteException e) {
1451 // ignore it
1452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453
Joe Onorato128e7292009-03-24 18:41:31 -07001454 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001455 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001456 }
1457 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1458 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1459 mScreenOnBroadcastDone, mHandler, 0, null, null);
1460 } else {
1461 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001462 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001463 mBroadcastWakeLock.mCount);
1464 mBroadcastWakeLock.release();
1465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467 }
Joe Onorato128e7292009-03-24 18:41:31 -07001468 else if (value == 0) {
1469 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001470
Joe Onorato128e7292009-03-24 18:41:31 -07001471 policy.screenTurnedOff(why);
1472 try {
1473 ActivityManagerNative.getDefault().goingToSleep();
1474 } catch (RemoteException e) {
1475 // ignore it.
1476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477
Joe Onorato128e7292009-03-24 18:41:31 -07001478 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1479 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1480 mScreenOffBroadcastDone, mHandler, 0, null, null);
1481 } else {
1482 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001483 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001484 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001485 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001486 mBroadcastWakeLock.release();
1487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489 }
Joe Onorato128e7292009-03-24 18:41:31 -07001490 else {
1491 // If we're in this case, then this handler is running for a previous
1492 // paired transaction. mBroadcastWakeLock will already have been released.
1493 break;
1494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 }
1497 };
1498
1499 long mScreenOnStart;
1500 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1501 public void onReceive(Context context, Intent intent) {
1502 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001503 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1505 mBroadcastWakeLock.release();
1506 }
1507 }
1508 };
1509
1510 long mScreenOffStart;
1511 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1512 public void onReceive(Context context, Intent intent) {
1513 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001514 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1516 mBroadcastWakeLock.release();
1517 }
1518 }
1519 };
1520
1521 void logPointerUpEvent() {
1522 if (LOG_TOUCH_DOWNS) {
1523 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1524 mLastTouchDown = 0;
1525 }
1526 }
1527
1528 void logPointerDownEvent() {
1529 if (LOG_TOUCH_DOWNS) {
1530 // If we are not already timing a down/up sequence
1531 if (mLastTouchDown == 0) {
1532 mLastTouchDown = SystemClock.elapsedRealtime();
1533 mTouchCycles++;
1534 }
1535 }
1536 }
1537
1538 /**
1539 * Prevents the screen from turning on even if it *should* turn on due
1540 * to a subsequent full wake lock being acquired.
1541 * <p>
1542 * This is a temporary hack that allows an activity to "cover up" any
1543 * display glitches that happen during the activity's startup
1544 * sequence. (Specifically, this API was added to work around a
1545 * cosmetic bug in the "incoming call" sequence, where the lock screen
1546 * would flicker briefly before the incoming call UI became visible.)
1547 * TODO: There ought to be a more elegant way of doing this,
1548 * probably by having the PowerManager and ActivityManager
1549 * work together to let apps specify that the screen on/off
1550 * state should be synchronized with the Activity lifecycle.
1551 * <p>
1552 * Note that calling preventScreenOn(true) will NOT turn the screen
1553 * off if it's currently on. (This API only affects *future*
1554 * acquisitions of full wake locks.)
1555 * But calling preventScreenOn(false) WILL turn the screen on if
1556 * it's currently off because of a prior preventScreenOn(true) call.
1557 * <p>
1558 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1559 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1560 * call doesn't occur within 5 seconds, we'll turn the screen back on
1561 * ourselves (and log a warning about it); this prevents a buggy app
1562 * from disabling the screen forever.)
1563 * <p>
1564 * TODO: this feature should really be controlled by a new type of poke
1565 * lock (rather than an IPowerManager call).
1566 */
1567 public void preventScreenOn(boolean prevent) {
1568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1569
1570 synchronized (mLocks) {
1571 if (prevent) {
1572 // First of all, grab a partial wake lock to
1573 // make sure the CPU stays on during the entire
1574 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1575 mPreventScreenOnPartialLock.acquire();
1576
1577 // Post a forceReenableScreen() call (for 5 seconds in the
1578 // future) to make sure the matching preventScreenOn(false) call
1579 // has happened by then.
1580 mHandler.removeCallbacks(mForceReenableScreenTask);
1581 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1582
1583 // Finally, set the flag that prevents the screen from turning on.
1584 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001585 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 mPreventScreenOn = true;
1587 } else {
1588 // (Re)enable the screen.
1589 mPreventScreenOn = false;
1590
1591 // We're "undoing" a the prior preventScreenOn(true) call, so we
1592 // no longer need the 5-second safeguard.
1593 mHandler.removeCallbacks(mForceReenableScreenTask);
1594
1595 // Forcibly turn on the screen if it's supposed to be on. (This
1596 // handles the case where the screen is currently off because of
1597 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001598 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001600 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1602 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001603 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607 }
1608
1609 // Release the partial wake lock that we held during the
1610 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1611 mPreventScreenOnPartialLock.release();
1612 }
1613 }
1614 }
1615
1616 public void setScreenBrightnessOverride(int brightness) {
1617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1618
Mike Lockwoodf527c712010-06-10 14:12:33 -04001619 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 synchronized (mLocks) {
1621 if (mScreenBrightnessOverride != brightness) {
1622 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001623 if (isScreenOn()) {
1624 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627 }
1628 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001629
1630 public void setButtonBrightnessOverride(int brightness) {
1631 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1632
Mike Lockwoodf527c712010-06-10 14:12:33 -04001633 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001634 synchronized (mLocks) {
1635 if (mButtonBrightnessOverride != brightness) {
1636 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001637 if (isScreenOn()) {
1638 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1639 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001640 }
1641 }
1642 }
1643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 /**
1645 * Sanity-check that gets called 5 seconds after any call to
1646 * preventScreenOn(true). This ensures that the original call
1647 * is followed promptly by a call to preventScreenOn(false).
1648 */
1649 private void forceReenableScreen() {
1650 // We shouldn't get here at all if mPreventScreenOn is false, since
1651 // we should have already removed any existing
1652 // mForceReenableScreenTask messages...
1653 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001654 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 return;
1656 }
1657
1658 // Uh oh. It's been 5 seconds since a call to
1659 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1660 // This means the app that called preventScreenOn(true) is either
1661 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1662 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1663 // crashed before doing so.)
1664
1665 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001666 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 + "Forcing the screen back on...");
1668 preventScreenOn(false);
1669 }
1670
1671 private Runnable mForceReenableScreenTask = new Runnable() {
1672 public void run() {
1673 forceReenableScreen();
1674 }
1675 };
1676
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001677 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001678 if (DEBUG_SCREEN_ON) {
1679 RuntimeException e = new RuntimeException("here");
1680 e.fillInStackTrace();
1681 Slog.i(TAG, "Set screen state: " + on, e);
1682 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001683 if (on) {
1684 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1685 // If we are turning the screen state on, but the screen
1686 // light is currently off, then make sure that we set the
1687 // light at this point to 0. This is the case where we are
1688 // turning on the screen and waiting for the UI to be drawn
1689 // before showing it to the user. We want the light off
1690 // until it is ready to be shown to the user, not it using
1691 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001692 if (DEBUG_SCREEN_ON) {
1693 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1694 + Integer.toHexString(mPowerState)
1695 + " mSkippedScreenOn=" + mSkippedScreenOn);
1696 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001697 mScreenBrightness.forceValueLocked(Power.BRIGHTNESS_OFF);
1698 }
1699 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001700 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001701 if (err == 0) {
1702 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1703 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001704 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001705 if (!on) {
1706 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001707 mButtonLight.turnOff();
1708 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001709 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001710 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001711 }
1712 return err;
1713 }
1714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 private void setPowerState(int state)
1716 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001717 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719
Mike Lockwood435eb642009-12-03 08:40:18 -05001720 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 {
1722 synchronized (mLocks) {
1723 int err;
1724
1725 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001726 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001728 + " noChangeLights=" + noChangeLights
1729 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731
1732 if (noChangeLights) {
1733 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1734 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001735 if (mProximitySensorActive) {
1736 // don't turn on the screen when the proximity sensor lock is held
1737 newState = (newState & ~SCREEN_BRIGHT);
1738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739
1740 if (batteryIsLow()) {
1741 newState |= BATTERY_LOW_BIT;
1742 } else {
1743 newState &= ~BATTERY_LOW_BIT;
1744 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001745 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 return;
1747 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001748
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001749 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 newState |= ALL_BRIGHT;
1751 }
1752
1753 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1754 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1755
Mike Lockwood51b844962009-11-16 21:51:18 -05001756 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001757 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001759 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001761 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001763 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001765 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001767 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1769 }
1770
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001771 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772
1773 if (oldScreenOn != newScreenOn) {
1774 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001775 // When the user presses the power button, we need to always send out the
1776 // notification that it's going to sleep so the keyguard goes on. But
1777 // we can't do that until the screen fades out, so we don't show the keyguard
1778 // too early.
1779 if (mStillNeedSleepNotification) {
1780 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 // Turn on the screen UNLESS there was a prior
1784 // preventScreenOn(true) request. (Note that the lifetime
1785 // of a single preventScreenOn() request is limited to 5
1786 // seconds to prevent a buggy app from disabling the
1787 // screen forever; see forceReenableScreen().)
1788 boolean reallyTurnScreenOn = true;
1789 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001790 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 + mPreventScreenOn);
1792 }
1793
1794 if (mPreventScreenOn) {
1795 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001796 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 reallyTurnScreenOn = false;
1799 }
1800 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001801 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 long identity = Binder.clearCallingIdentity();
1803 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001804 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 mBatteryStats.noteScreenOn();
1806 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001807 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 } finally {
1809 Binder.restoreCallingIdentity(identity);
1810 }
1811 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001812 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 // But continue as if we really did turn the screen on...
1814 err = 0;
1815 }
1816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 mLastTouchDown = 0;
1818 mTotalTouchDownTime = 0;
1819 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001820 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 mTotalTouchDownTime, mTouchCycles);
1822 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001824 // Update the lights *after* taking care of turning the
1825 // screen on, so we do this after our notifications are
1826 // enqueued and thus will delay turning on the screen light
1827 // until the windows are correctly displayed.
1828 if (stateChanged) {
1829 updateLightsLocked(newState, 0);
1830 }
1831 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001835 // Update the lights *before* taking care of turning the
1836 // screen off, so we can initiate any animations that are desired.
1837 if (stateChanged) {
1838 updateLightsLocked(newState, 0);
1839 }
1840
Mike Lockwood497087e32009-11-08 18:33:03 -05001841 // cancel light sensor task
1842 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001843 mLightSensorPendingDecrease = false;
1844 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 mScreenOffTime = SystemClock.elapsedRealtime();
1846 long identity = Binder.clearCallingIdentity();
1847 try {
1848 mBatteryStats.noteScreenOff();
1849 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001850 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 } finally {
1852 Binder.restoreCallingIdentity(identity);
1853 }
1854 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001855 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001857 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 err = 0;
1860 mLastTouchDown = 0;
1861 }
1862 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001863 } else if (stateChanged) {
1864 // Screen on/off didn't change, but lights may have.
1865 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001867
1868 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1869
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001870 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
1872 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001873
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001874 private void updateNativePowerStateLocked() {
1875 nativeSetPowerState(
1876 (mPowerState & SCREEN_ON_BIT) != 0,
1877 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001879
Mike Lockwood435eb642009-12-03 08:40:18 -05001880 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001882 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001884 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1885 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001887 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001889 mScreenOffReason = reason;
1890 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892 return err;
1893 }
1894
1895 private boolean batteryIsLow() {
1896 return (!mIsPowered &&
1897 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1898 }
1899
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001900 private boolean shouldDeferScreenOnLocked() {
1901 if (mPreparingForScreenOn) {
1902 // Currently waiting for confirmation from the policy that it
1903 // is okay to turn on the screen. Don't allow the screen to go
1904 // on until that is done.
1905 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1906 "updateLights: delaying screen on due to mPreparingForScreenOn");
1907 return true;
1908 } else {
1909 // If there is a screen-on command in the notification queue, we
1910 // can't turn the screen on until it has been processed (and we
1911 // have set mPreparingForScreenOn) or it has been dropped.
1912 for (int i=0; i<mBroadcastQueue.length; i++) {
1913 if (mBroadcastQueue[i] == 1) {
1914 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1915 "updateLights: delaying screen on due to notification queue");
1916 return true;
1917 }
1918 }
1919 }
1920 return false;
1921 }
1922
The Android Open Source Project10592532009-03-18 17:39:46 -07001923 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001924 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001925
1926 // If the screen is not currently on, we will want to delay actually
1927 // turning the lights on if we are still getting the UI put up.
1928 if ((oldState&SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1929 // Don't turn screen on until we know we are really ready to.
1930 // This is to avoid letting the screen go on before things like the
1931 // lock screen have been displayed.
1932 if ((mSkippedScreenOn=shouldDeferScreenOnLocked())) {
1933 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1934 }
1935 }
1936
Joe Onorato60607a902010-10-23 14:49:30 -07001937 if ((newState & SCREEN_ON_BIT) != 0) {
1938 // Only turn on the buttons or keyboard if the screen is also on.
1939 // We should never see the buttons on but not the screen.
1940 newState = applyButtonState(newState);
1941 newState = applyKeyboardState(newState);
1942 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001943 final int realDifference = (newState ^ oldState);
1944 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001946 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 int offMask = 0;
1950 int dimMask = 0;
1951 int onMask = 0;
1952
1953 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001956 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1957 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001959 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961 }
1962
1963 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001964 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1965 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001967 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
1969 }
1970
1971 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001972 int nominalCurrentValue = -1;
1973 // If there was an actual difference in the light state, then
1974 // figure out the "ideal" current value based on the previous
1975 // state. Otherwise, this is a change due to the brightness
1976 // override, so we want to animate from whatever the current
1977 // value is.
1978 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1979 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1980 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1981 nominalCurrentValue = preferredBrightness;
1982 break;
1983 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001984 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001985 break;
1986 case 0:
1987 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1988 break;
1989 case SCREEN_BRIGHT_BIT:
1990 default:
1991 // not possible
1992 nominalCurrentValue = (int)mScreenBrightness.curValue;
1993 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001994 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001995 }
1996 int brightness = preferredBrightness;
1997 int steps = ANIM_STEPS;
1998 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1999 // dim or turn off backlight, depending on if the screen is on
2000 // the scale is because the brightness ramp isn't linear and this biases
2001 // it so the later parts take longer.
2002 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002003 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002004 if (ratio > 1.0f) ratio = 1.0f;
2005 if ((newState & SCREEN_ON_BIT) == 0) {
2006 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2007 // was bright
2008 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002010 // was dim
2011 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002013 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002015 if ((oldState & SCREEN_ON_BIT) != 0) {
2016 // was bright
2017 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2018 } else {
2019 // was dim
2020 steps = (int)(ANIM_STEPS*ratio);
2021 }
2022 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2023 // If the "stay on while plugged in" option is
2024 // turned on, then the screen will often not
2025 // automatically turn off while plugged in. To
2026 // still have a sense of when it is inactive, we
2027 // will then count going dim as turning off.
2028 mScreenOffTime = SystemClock.elapsedRealtime();
2029 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002030 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002033 long identity = Binder.clearCallingIdentity();
2034 try {
2035 mBatteryStats.noteScreenBrightness(brightness);
2036 } catch (RemoteException e) {
2037 // Nothing interesting to do.
2038 } finally {
2039 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002041 if (!mSkippedScreenOn) {
2042 mScreenBrightness.setTargetLocked(brightness, steps,
2043 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
2044 if (DEBUG_SCREEN_ON) {
2045 RuntimeException e = new RuntimeException("here");
2046 e.fillInStackTrace();
2047 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2048 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002051
Joe Onorato60607a902010-10-23 14:49:30 -07002052 if (mSpew) {
2053 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2054 + " dimMask=0x" + Integer.toHexString(dimMask)
2055 + " onMask=0x" + Integer.toHexString(onMask)
2056 + " difference=0x" + Integer.toHexString(difference)
2057 + " realDifference=0x" + Integer.toHexString(realDifference)
2058 + " forceState=0x" + Integer.toHexString(forceState)
2059 );
2060 }
2061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002063 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002064 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 }
2066 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002067 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 if ((newState & BATTERY_LOW_BIT) != 0 &&
2069 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2070 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2071 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002072 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002073 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075 if (onMask != 0) {
2076 int brightness = getPreferredBrightness();
2077 if ((newState & BATTERY_LOW_BIT) != 0 &&
2078 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2079 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2080 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002081 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002082 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085
The Android Open Source Project10592532009-03-18 17:39:46 -07002086 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002087 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002088 ? LightsService.BRIGHTNESS_MODE_SENSOR
2089 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07002090 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002091 if (DEBUG_SCREEN_ON) {
2092 RuntimeException e = new RuntimeException("here");
2093 e.fillInStackTrace();
2094 Slog.i(TAG, "Set LCD brightness: " + value, e);
2095 }
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002096 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07002097 }
2098 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002099 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002100 }
2101 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002102 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105
Joe Onoratob08a1af2010-10-11 19:28:58 -07002106 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 boolean initialized;
2110 int targetValue;
2111 float curValue;
2112 float delta;
2113 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 BrightnessState(int m) {
2116 mask = m;
2117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 public void dump(PrintWriter pw, String prefix) {
2120 pw.println(prefix + "animating=" + animating
2121 + " targetValue=" + targetValue
2122 + " curValue=" + curValue
2123 + " delta=" + delta);
2124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002125
Dianne Hackborn474fd742011-10-10 18:40:22 -07002126 void forceValueLocked(int value) {
2127 targetValue = -1;
2128 curValue = value;
2129 setLightBrightness(mask, value);
2130 if (animating) {
2131 finishAnimationLocked(false, value);
2132 }
2133 }
2134
Joe Onoratob08a1af2010-10-11 19:28:58 -07002135 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002136 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 if (!initialized) {
2138 initialized = true;
2139 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002140 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002141 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002144 delta = (targetValue -
2145 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2146 / stepsToTarget;
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002147 if (mSpew || DEBUG_SCREEN_ON) {
Joe Onorato128e7292009-03-24 18:41:31 -07002148 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002149 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2150 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002151 + " nominalCurrentValue=" + nominalCurrentValue
2152 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
2154 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002155
2156 if (mSpew) {
2157 Slog.i(TAG, "scheduling light animator");
2158 }
2159 mScreenOffHandler.removeCallbacks(this);
2160 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 boolean stepLocked() {
2164 if (!animating) return false;
2165 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002166 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 + " target=" + targetValue + " delta=" + delta);
2168 }
2169 curValue += delta;
2170 int curIntValue = (int)curValue;
2171 boolean more = true;
2172 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002173 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 more = false;
2175 } else if (delta > 0) {
2176 if (curIntValue >= targetValue) {
2177 curValue = curIntValue = targetValue;
2178 more = false;
2179 }
2180 } else {
2181 if (curIntValue <= targetValue) {
2182 curValue = curIntValue = targetValue;
2183 more = false;
2184 }
2185 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002186 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002187 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002188 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002189 return more;
2190 }
2191
Joe Onorato3d3db602010-10-18 16:08:16 -04002192 void jumpToTargetLocked() {
2193 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002194 setLightBrightness(mask, targetValue);
2195 final int tv = targetValue;
2196 curValue = tv;
2197 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002198 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002199 }
2200
Joe Onorato3d3db602010-10-18 16:08:16 -04002201 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 animating = more;
2203 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002204 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002205 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 }
2207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 public void run() {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07002211 synchronized (mLocks) {
2212 // we're turning off
2213 final boolean turningOff = animating && targetValue == Power.BRIGHTNESS_OFF;
2214 if (mAnimateScreenLights || !turningOff) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002215 long now = SystemClock.uptimeMillis();
2216 boolean more = mScreenBrightness.stepLocked();
2217 if (more) {
2218 mScreenOffHandler.postAtTime(this, now+(1000/60));
2219 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -07002220 } else {
2221 // It's pretty scary to hold mLocks for this long, and we should
2222 // redesign this, but it works for now.
2223 nativeStartSurfaceFlingerAnimation(
2224 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2225 ? 0 : mAnimationSetting);
Joe Onorato3d3db602010-10-18 16:08:16 -04002226 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229 }
2230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 private int getPreferredBrightness() {
2233 try {
2234 if (mScreenBrightnessOverride >= 0) {
2235 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002236 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002237 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002238 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2241 SCREEN_BRIGHTNESS);
2242 // Don't let applications turn the screen all the way off
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002243 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 } catch (SettingNotFoundException snfe) {
2245 return Power.BRIGHTNESS_ON;
2246 }
2247 }
2248
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002249 private int applyButtonState(int state) {
2250 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002251 if ((state & BATTERY_LOW_BIT) != 0) {
2252 // do not override brightness if the battery is low
2253 return state;
2254 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002255 if (mButtonBrightnessOverride >= 0) {
2256 brightness = mButtonBrightnessOverride;
2257 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2258 brightness = mLightSensorButtonBrightness;
2259 }
2260 if (brightness > 0) {
2261 return state | BUTTON_BRIGHT_BIT;
2262 } else if (brightness == 0) {
2263 return state & ~BUTTON_BRIGHT_BIT;
2264 } else {
2265 return state;
2266 }
2267 }
2268
2269 private int applyKeyboardState(int state) {
2270 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002271 if ((state & BATTERY_LOW_BIT) != 0) {
2272 // do not override brightness if the battery is low
2273 return state;
2274 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002275 if (!mKeyboardVisible) {
2276 brightness = 0;
2277 } else if (mButtonBrightnessOverride >= 0) {
2278 brightness = mButtonBrightnessOverride;
2279 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2280 brightness = mLightSensorKeyboardBrightness;
2281 }
2282 if (brightness > 0) {
2283 return state | KEYBOARD_BRIGHT_BIT;
2284 } else if (brightness == 0) {
2285 return state & ~KEYBOARD_BRIGHT_BIT;
2286 } else {
2287 return state;
2288 }
2289 }
2290
Charles Mendis322591c2009-10-29 11:06:59 -07002291 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 synchronized (mLocks) {
2293 return (mPowerState & SCREEN_ON_BIT) != 0;
2294 }
2295 }
2296
Charles Mendis322591c2009-10-29 11:06:59 -07002297 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 synchronized (mLocks) {
2299 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2300 }
2301 }
2302
Mike Lockwood497087e32009-11-08 18:33:03 -05002303 private boolean isScreenTurningOffLocked() {
2304 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2305 }
2306
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002307 private boolean shouldLog(long time) {
2308 synchronized (mLocks) {
2309 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2310 mWarningSpewThrottleTime = time;
2311 mWarningSpewThrottleCount = 0;
2312 return true;
2313 } else if (mWarningSpewThrottleCount < 30) {
2314 mWarningSpewThrottleCount++;
2315 return true;
2316 } else {
2317 return false;
2318 }
2319 }
2320 }
2321
Mike Lockwood200b30b2009-09-20 00:23:59 -04002322 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002323 if (isScreenTurningOffLocked()) {
2324 // cancel animation so userActivity will succeed
2325 mScreenBrightness.animating = false;
2326 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002327 boolean savedActivityAllowed = mUserActivityAllowed;
2328 mUserActivityAllowed = true;
2329 userActivity(SystemClock.uptimeMillis(), false);
2330 mUserActivityAllowed = savedActivityAllowed;
2331 }
2332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002335 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337
2338 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002339 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2340 != PackageManager.PERMISSION_GRANTED) {
2341 if (shouldLog(time)) {
2342 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2343 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2344 }
2345 return;
2346 }
2347
Joe Onorato7999bff2010-07-24 11:50:05 -04002348 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
2350
2351 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002352 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
2354
2355 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002356 userActivity(time, -1, noChangeLights, eventType, force);
2357 }
2358
2359 /*
2360 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2361 * on with user activity. Don't use this function.
2362 */
2363 public void clearUserActivityTimeout(long now, long timeout) {
2364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2365 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2366 userActivity(now, timeout, false, OTHER_EVENT, false);
2367 }
2368
2369 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2370 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371
Joe Onorato1a542c72010-11-08 09:48:20 -08002372 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002373 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002374 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002375 }
2376 return;
2377 }
2378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 synchronized (mLocks) {
2380 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002381 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 + " mUserActivityAllowed=" + mUserActivityAllowed
2383 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002384 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2385 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002386 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002387 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
Mike Lockwood05067122009-10-27 23:07:25 -04002389 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002390 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002391 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002392 return;
2393 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002394 // Disable proximity sensor if if user presses power key while we are in the
2395 // "waiting for proximity sensor to go negative" state.
2396 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2397 mProximitySensorActive = false;
2398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 if (mLastEventTime <= time || force) {
2400 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002401 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002402 // Only turn on button backlights if a button was pressed
2403 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002404 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2406 } else {
2407 // don't clear button/keyboard backlights when the screen is touched.
2408 mUserState |= SCREEN_BRIGHT;
2409 }
2410
Dianne Hackborn617f8772009-03-31 15:04:46 -07002411 int uid = Binder.getCallingUid();
2412 long ident = Binder.clearCallingIdentity();
2413 try {
2414 mBatteryStats.noteUserActivity(uid, eventType);
2415 } catch (RemoteException e) {
2416 // Ignore
2417 } finally {
2418 Binder.restoreCallingIdentity(ident);
2419 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002420
Michael Chane96440f2009-05-06 10:27:36 -07002421 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002422 setPowerState(mUserState | mWakeLockState, noChangeLights,
2423 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002424 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 }
2426 }
2427 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002428
2429 if (mPolicy != null) {
2430 mPolicy.userActivity();
2431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002434 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2435 try {
2436 int i;
2437 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2438 if (sensorValue < mAutoBrightnessLevels[i]) {
2439 break;
2440 }
2441 }
2442 return values[i];
2443 } catch (Exception e) {
2444 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002445 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002446 return 255;
2447 }
2448 }
2449
Mike Lockwood20f87d72009-11-05 16:08:51 -05002450 private Runnable mProximityTask = new Runnable() {
2451 public void run() {
2452 synchronized (mLocks) {
2453 if (mProximityPendingValue != -1) {
2454 proximityChangedLocked(mProximityPendingValue == 1);
2455 mProximityPendingValue = -1;
2456 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002457 if (mProximityPartialLock.isHeld()) {
2458 mProximityPartialLock.release();
2459 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002460 }
2461 }
2462 };
2463
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002464 private Runnable mAutoBrightnessTask = new Runnable() {
2465 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002466 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002467 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2468 int value = (int)mLightSensorPendingValue;
2469 mLightSensorPendingDecrease = false;
2470 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002471 lightSensorChangedLocked(value);
2472 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002473 }
2474 }
2475 };
2476
Mike Lockwoodb2865412010-02-02 22:40:33 -05002477 private void dockStateChanged(int state) {
2478 synchronized (mLocks) {
2479 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2480 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002481 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002482 mHighestLightSensorValue = -1;
2483 }
2484 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2485 // force lights recalculation
2486 int value = (int)mLightSensorValue;
2487 mLightSensorValue = -1;
2488 lightSensorChangedLocked(value);
2489 }
2490 }
2491 }
2492
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002493 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002494 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002495 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002496 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002497
Joe Onorato06eb33a2010-10-25 14:09:21 -07002498 // Don't do anything if the screen is off.
2499 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2500 if (mDebugLightSensor) {
2501 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2502 }
2503 return;
2504 }
2505
Mike Lockwoodb2865412010-02-02 22:40:33 -05002506 // do not allow light sensor value to decrease
2507 if (mHighestLightSensorValue < value) {
2508 mHighestLightSensorValue = value;
2509 }
2510
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002511 if (mLightSensorValue != value) {
2512 mLightSensorValue = value;
2513 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002514 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2515 // we only do this if we are undocked, since lighting should be stable when
2516 // stationary in a dock.
2517 int lcdValue = getAutoBrightnessValue(
2518 (mIsDocked ? value : mHighestLightSensorValue),
2519 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002520 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002521 int keyboardValue;
2522 if (mKeyboardVisible) {
2523 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2524 } else {
2525 keyboardValue = 0;
2526 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002527 mLightSensorScreenBrightness = lcdValue;
2528 mLightSensorButtonBrightness = buttonValue;
2529 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002530
2531 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002532 Slog.d(TAG, "lcdValue " + lcdValue);
2533 Slog.d(TAG, "buttonValue " + buttonValue);
2534 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002535 }
2536
Mike Lockwood4984e732009-11-01 08:16:33 -05002537 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002538 if (!mSkippedScreenOn) {
2539 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2540 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
2541 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002542 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002543 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002544 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002545 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002546 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002547 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002548 }
2549 }
2550 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002551 }
2552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 /**
2554 * The user requested that we go to sleep (probably with the power button).
2555 * This overrides all wake locks that are held.
2556 */
2557 public void goToSleep(long time)
2558 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002559 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2560 }
2561
2562 /**
2563 * The user requested that we go to sleep (probably with the power button).
2564 * This overrides all wake locks that are held.
2565 */
2566 public void goToSleepWithReason(long time, int reason)
2567 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2569 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002570 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002575 * Reboot the device immediately, passing 'reason' (may be null)
2576 * to the underlying __reboot system call. Should not return.
2577 */
2578 public void reboot(String reason)
2579 {
2580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002581
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002582 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2583 throw new IllegalStateException("Too early to call reboot()");
2584 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002585
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002586 final String finalReason = reason;
2587 Runnable runnable = new Runnable() {
2588 public void run() {
2589 synchronized (this) {
2590 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002591 }
2592
San Mehat1e512792010-01-07 10:40:29 -08002593 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002594 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002595 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002596 mHandler.post(runnable);
2597
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002598 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002599 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002600 while (true) {
2601 try {
2602 runnable.wait();
2603 } catch (InterruptedException e) {
2604 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002605 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002606 }
2607 }
2608
Dan Egnor60d87622009-12-16 16:32:58 -08002609 /**
2610 * Crash the runtime (causing a complete restart of the Android framework).
2611 * Requires REBOOT permission. Mostly for testing. Should not return.
2612 */
2613 public void crash(final String message)
2614 {
2615 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2616 Thread t = new Thread("PowerManagerService.crash()") {
2617 public void run() { throw new RuntimeException(message); }
2618 };
2619 try {
2620 t.start();
2621 t.join();
2622 } catch (InterruptedException e) {
2623 Log.wtf(TAG, e);
2624 }
2625 }
2626
Mike Lockwood435eb642009-12-03 08:40:18 -05002627 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628
2629 if (mLastEventTime <= time) {
2630 mLastEventTime = time;
2631 // cancel all of the wake locks
2632 mWakeLockState = SCREEN_OFF;
2633 int N = mLocks.size();
2634 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002635 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 for (int i=0; i<N; i++) {
2637 WakeLock wl = mLocks.get(i);
2638 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002639 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2640 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2641 proxLock = true;
2642 } else {
2643 mLocks.get(i).activated = false;
2644 numCleared++;
2645 }
2646 }
2647 }
2648 if (!proxLock) {
2649 mProxIgnoredBecauseScreenTurnedOff = true;
2650 if (mDebugProximitySensor) {
2651 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 }
2653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002654 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002655 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002657 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 cancelTimerLocked();
2659 }
2660 }
2661
2662 public long timeSinceScreenOn() {
2663 synchronized (mLocks) {
2664 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2665 return 0;
2666 }
2667 return SystemClock.elapsedRealtime() - mScreenOffTime;
2668 }
2669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002672 synchronized (mLocks) {
2673 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002674 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002675 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002676 if (mKeyboardVisible != visible) {
2677 mKeyboardVisible = visible;
2678 // don't signal user activity if the screen is off; other code
2679 // will take care of turning on due to a true change to the lid
2680 // switch and synchronized with the lock screen.
2681 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002682 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002683 // force recompute of backlight values
2684 if (mLightSensorValue >= 0) {
2685 int value = (int)mLightSensorValue;
2686 mLightSensorValue = -1;
2687 lightSensorChangedLocked(value);
2688 }
2689 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002690 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2691 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002692 }
2693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695
2696 /**
2697 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002698 * When disabling user activity we also reset user power state so the keyguard can reset its
2699 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 */
2701 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002702 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002703 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 synchronized (mLocks) {
2706 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002707 if (!enabled) {
2708 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2709 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 }
2713
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002714 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002715 synchronized (mLocks) {
2716 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2717 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2718 mAutoBrightessEnabled = enabled;
2719 // This will get us a new value
2720 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002721 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002722 }
2723 }
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 /** Sets the screen off timeouts:
2726 * mKeylightDelay
2727 * mDimDelay
2728 * mScreenOffDelay
2729 * */
2730 private void setScreenOffTimeoutsLocked() {
2731 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002732 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 mDimDelay = -1;
2734 mScreenOffDelay = 0;
2735 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2736 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2737 mDimDelay = -1;
2738 mScreenOffDelay = 0;
2739 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002740 int totalDelay = mScreenOffTimeoutSetting;
2741 if (totalDelay > mMaximumScreenOffTimeout) {
2742 totalDelay = mMaximumScreenOffTimeout;
2743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2745 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002746 // negative number means stay on as long as possible.
2747 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 } else if (mKeylightDelay < totalDelay) {
2749 // subtract the time that the keylight delay. This will give us the
2750 // remainder of the time that we need to sleep to get the accurate
2751 // screen off timeout.
2752 mScreenOffDelay = totalDelay - mKeylightDelay;
2753 } else {
2754 mScreenOffDelay = 0;
2755 }
2756 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2757 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2758 mScreenOffDelay = LONG_DIM_TIME;
2759 } else {
2760 mDimDelay = -1;
2761 }
2762 }
2763 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002764 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2766 + " mDimScreen=" + mDimScreen);
2767 }
2768 }
2769
2770 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002771 * Refreshes cached secure settings. Called once on startup, and
2772 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 */
Doug Zongker43866e02010-01-07 12:09:54 -08002774 private void updateSettingsValues() {
2775 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002777 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002779 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
2782 private class LockList extends ArrayList<WakeLock>
2783 {
2784 void addLock(WakeLock wl)
2785 {
2786 int index = getIndex(wl.binder);
2787 if (index < 0) {
2788 this.add(wl);
2789 }
2790 }
2791
2792 WakeLock removeLock(IBinder binder)
2793 {
2794 int index = getIndex(binder);
2795 if (index >= 0) {
2796 return this.remove(index);
2797 } else {
2798 return null;
2799 }
2800 }
2801
2802 int getIndex(IBinder binder)
2803 {
2804 int N = this.size();
2805 for (int i=0; i<N; i++) {
2806 if (this.get(i).binder == binder) {
2807 return i;
2808 }
2809 }
2810 return -1;
2811 }
2812
2813 int gatherState()
2814 {
2815 int result = 0;
2816 int N = this.size();
2817 for (int i=0; i<N; i++) {
2818 WakeLock wl = this.get(i);
2819 if (wl.activated) {
2820 if (isScreenLock(wl.flags)) {
2821 result |= wl.minState;
2822 }
2823 }
2824 }
2825 return result;
2826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002827
Michael Chane96440f2009-05-06 10:27:36 -07002828 int reactivateScreenLocksLocked()
2829 {
2830 int result = 0;
2831 int N = this.size();
2832 for (int i=0; i<N; i++) {
2833 WakeLock wl = this.get(i);
2834 if (isScreenLock(wl.flags)) {
2835 wl.activated = true;
2836 result |= wl.minState;
2837 }
2838 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002839 if (mDebugProximitySensor) {
2840 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2841 + mProxIgnoredBecauseScreenTurnedOff);
2842 }
2843 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002844 return result;
2845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 }
2847
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002848 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 synchronized (mLocks) {
2850 mPolicy = p;
2851 mLocks.notifyAll();
2852 }
2853 }
2854
2855 WindowManagerPolicy getPolicyLocked() {
2856 while (mPolicy == null || !mDoneBooting) {
2857 try {
2858 mLocks.wait();
2859 } catch (InterruptedException e) {
2860 // Ignore
2861 }
2862 }
2863 return mPolicy;
2864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002867 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2868 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2869 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002870 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002871 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002872 }
2873
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002874 // wait until sensors are enabled before turning on screen.
2875 // some devices will not activate the light sensor properly on boot
2876 // unless we do this.
2877 if (mUseSoftwareAutoBrightness) {
2878 // turn the screen on
2879 setPowerState(SCREEN_BRIGHT);
2880 } else {
2881 // turn everything on
2882 setPowerState(ALL_BRIGHT);
2883 }
2884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002886 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002888
Joe Onoratod28f7532010-11-06 12:56:53 -07002889 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2890
Dianne Hackborn617f8772009-03-31 15:04:46 -07002891 long identity = Binder.clearCallingIdentity();
2892 try {
2893 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2894 mBatteryStats.noteScreenOn();
2895 } catch (RemoteException e) {
2896 // Nothing interesting to do.
2897 } finally {
2898 Binder.restoreCallingIdentity(identity);
2899 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002900 }
2901 }
2902
2903 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002904 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002905 synchronized (mLocks) {
2906 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2908 updateWakeLockLocked();
2909 mLocks.notifyAll();
2910 }
2911 }
2912
Joe Onoratob08a1af2010-10-11 19:28:58 -07002913 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 public void monitor() {
2915 synchronized (mLocks) { }
2916 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002917
2918 public int getSupportedWakeLockFlags() {
2919 int result = PowerManager.PARTIAL_WAKE_LOCK
2920 | PowerManager.FULL_WAKE_LOCK
2921 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2922
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002923 if (mProximitySensor != null) {
2924 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2925 }
2926
2927 return result;
2928 }
2929
Mike Lockwood237a2992009-09-15 14:42:16 -04002930 public void setBacklightBrightness(int brightness) {
2931 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2932 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002933 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002934 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002935 mLcdLight.setBrightness(brightness);
2936 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2937 mButtonLight.setBrightness(brightness);
2938 long identity = Binder.clearCallingIdentity();
2939 try {
2940 mBatteryStats.noteScreenBrightness(brightness);
2941 } catch (RemoteException e) {
2942 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2943 } finally {
2944 Binder.restoreCallingIdentity(identity);
2945 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002946
Joe Onoratob08a1af2010-10-11 19:28:58 -07002947 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002948 synchronized (mLocks) {
2949 mScreenBrightness.targetValue = brightness;
2950 mScreenBrightness.jumpToTargetLocked();
2951 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002952 }
2953 }
2954
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002955 public void setAttentionLight(boolean on, int color) {
2956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002957 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002958 }
2959
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002960 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002961 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002962 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002963 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002964 if (!mProximitySensorEnabled) {
2965 // clear calling identity so sensor manager battery stats are accurate
2966 long identity = Binder.clearCallingIdentity();
2967 try {
2968 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2969 SensorManager.SENSOR_DELAY_NORMAL);
2970 mProximitySensorEnabled = true;
2971 } finally {
2972 Binder.restoreCallingIdentity(identity);
2973 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002974 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002975 }
2976
2977 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002978 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002979 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002980 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002981 if (mProximitySensorEnabled) {
2982 // clear calling identity so sensor manager battery stats are accurate
2983 long identity = Binder.clearCallingIdentity();
2984 try {
2985 mSensorManager.unregisterListener(mProximityListener);
2986 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002987 if (mProximityPartialLock.isHeld()) {
2988 mProximityPartialLock.release();
2989 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002990 mProximitySensorEnabled = false;
2991 } finally {
2992 Binder.restoreCallingIdentity(identity);
2993 }
2994 if (mProximitySensorActive) {
2995 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002996 if (mDebugProximitySensor) {
2997 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2998 + mProxIgnoredBecauseScreenTurnedOff);
2999 }
3000 if (!mProxIgnoredBecauseScreenTurnedOff) {
3001 forceUserActivityLocked();
3002 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003003 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003004 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003005 }
3006
Mike Lockwood20f87d72009-11-05 16:08:51 -05003007 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003008 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003009 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003010 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003011 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003012 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003013 return;
3014 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003015 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003016 if (mDebugProximitySensor) {
3017 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3018 + mProxIgnoredBecauseScreenTurnedOff);
3019 }
3020 if (!mProxIgnoredBecauseScreenTurnedOff) {
3021 goToSleepLocked(SystemClock.uptimeMillis(),
3022 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3023 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003024 mProximitySensorActive = true;
3025 } else {
3026 // proximity sensor negative events trigger as user activity.
3027 // temporarily set mUserActivityAllowed to true so this will work
3028 // even when the keyguard is on.
3029 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003030 if (mDebugProximitySensor) {
3031 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3032 + mProxIgnoredBecauseScreenTurnedOff);
3033 }
3034 if (!mProxIgnoredBecauseScreenTurnedOff) {
3035 forceUserActivityLocked();
3036 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003037
3038 if (mProximityWakeLockCount == 0) {
3039 // disable sensor if we have no listeners left after proximity negative
3040 disableProximityLockLocked();
3041 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003042 }
3043 }
3044
Joe Onoratod28f7532010-11-06 12:56:53 -07003045 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003046 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003047 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3048 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3049 }
3050 if (!mAutoBrightessEnabled) {
3051 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003052 }
3053 if (mSensorManager != null && mLightSensorEnabled != enable) {
3054 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003055 // clear calling identity so sensor manager battery stats are accurate
3056 long identity = Binder.clearCallingIdentity();
3057 try {
3058 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003059 // reset our highest value when reenabling
3060 mHighestLightSensorValue = -1;
3061 // force recompute of backlight values
3062 if (mLightSensorValue >= 0) {
3063 int value = (int)mLightSensorValue;
3064 mLightSensorValue = -1;
3065 handleLightSensorValue(value);
3066 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003067 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003068 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003069 } else {
3070 mSensorManager.unregisterListener(mLightListener);
3071 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003072 mLightSensorPendingDecrease = false;
3073 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003074 }
3075 } finally {
3076 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003077 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003078 }
3079 }
3080
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003081 SensorEventListener mProximityListener = new SensorEventListener() {
3082 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003083 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003084 synchronized (mLocks) {
3085 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003086 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3087 mLastProximityEventTime = milliseconds;
3088 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003089 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003090
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003091 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003092 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3093 distance < mProximitySensor.getMaximumRange());
3094
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003095 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003096 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003097 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003098 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3099 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3100 mProximityPendingValue = (active ? 1 : 0);
3101 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003102 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003103 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003104 // process the value immediately
3105 mProximityPendingValue = -1;
3106 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003107 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003108
3109 // update mProximityPartialLock state
3110 boolean held = mProximityPartialLock.isHeld();
3111 if (!held && proximityTaskQueued) {
3112 // hold wakelock until mProximityTask runs
3113 mProximityPartialLock.acquire();
3114 } else if (held && !proximityTaskQueued) {
3115 mProximityPartialLock.release();
3116 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003117 }
3118 }
3119
3120 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3121 // ignore
3122 }
3123 };
3124
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003125 private void handleLightSensorValue(int value) {
3126 long milliseconds = SystemClock.elapsedRealtime();
3127 if (mLightSensorValue == -1 ||
3128 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3129 // process the value immediately if screen has just turned on
3130 mHandler.removeCallbacks(mAutoBrightnessTask);
3131 mLightSensorPendingDecrease = false;
3132 mLightSensorPendingIncrease = false;
3133 lightSensorChangedLocked(value);
3134 } else {
3135 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3136 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3137 (value == mLightSensorValue) ||
3138 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3139 // delay processing to debounce the sensor
3140 mHandler.removeCallbacks(mAutoBrightnessTask);
3141 mLightSensorPendingDecrease = (value < mLightSensorValue);
3142 mLightSensorPendingIncrease = (value > mLightSensorValue);
3143 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3144 mLightSensorPendingValue = value;
3145 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3146 }
3147 } else {
3148 mLightSensorPendingValue = value;
3149 }
3150 }
3151 }
3152
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003153 SensorEventListener mLightListener = new SensorEventListener() {
3154 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003155 if (mDebugLightSensor) {
3156 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3157 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003158 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003159 // ignore light sensor while screen is turning off
3160 if (isScreenTurningOffLocked()) {
3161 return;
3162 }
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003163 handleLightSensorValue((int)event.values[0]);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003164 }
3165 }
3166
3167 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3168 // ignore
3169 }
3170 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171}