blob: 9a371c6c553963dded6b4012caa230b55ed10956 [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;
Jeff Brown25157e42012-04-16 12:13:05 -070040import android.hardware.SystemSensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070041import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.BatteryStats;
43import android.os.Binder;
44import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.LocalPowerManager;
Jim Miller92e66dd2012-02-21 18:57:12 -080049import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.Power;
51import android.os.PowerManager;
52import android.os.Process;
53import android.os.RemoteException;
54import android.os.SystemClock;
Mike Lockwood3a74bd32011-08-12 13:55:22 -070055import android.os.SystemProperties;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070056import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.provider.Settings;
58import android.util.EventLog;
59import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.view.WindowManagerPolicy;
Jim Miller92e66dd2012-02-21 18:57:12 -080062import static android.view.WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import static android.provider.Settings.System.DIM_SCREEN;
64import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050065import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -080066import static android.provider.Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070067import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
69import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070070import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
71import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73import java.io.FileDescriptor;
74import java.io.PrintWriter;
75import java.util.ArrayList;
76import java.util.HashMap;
77import java.util.Observable;
78import java.util.Observer;
79
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080080public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040081 implements LocalPowerManager, Watchdog.Monitor {
Jim Miller92e66dd2012-02-21 18:57:12 -080082 private static final int NOMINAL_FRAME_TIME_MS = 1000/60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84 private static final String TAG = "PowerManagerService";
85 static final String PARTIAL_NAME = "PowerManagerService";
86
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -070087 static final boolean DEBUG_SCREEN_ON = false;
88
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 private static final boolean LOG_PARTIAL_WL = false;
90
91 // Indicates whether touch-down cycles should be logged as part of the
92 // LOG_POWER_SCREEN_STATE log events
93 private static final boolean LOG_TOUCH_DOWNS = true;
94
95 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
96 | PowerManager.SCREEN_DIM_WAKE_LOCK
97 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070098 | PowerManager.FULL_WAKE_LOCK
99 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
101 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -0800102 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
104 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
105 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
106 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
107
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800108 // How long to wait to debounce light sensor changes in milliseconds
Mike Lockwood9b8136922009-11-06 15:53:59 -0500109 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700110
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800111 // light sensor events rate in microseconds
112 private static final int LIGHT_SENSOR_RATE = 1000000;
113
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800114 // Expansion of range of light values when applying scale from light
115 // sensor brightness setting, in the [0..255] brightness range.
116 private static final int LIGHT_SENSOR_RANGE_EXPANSION = 20;
117
118 // Scaling factor of the light sensor brightness setting when applying
119 // it to the final brightness.
120 private static final int LIGHT_SENSOR_OFFSET_SCALE = 8;
121
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800122 // For debouncing the proximity sensor in milliseconds
Mike Lockwood20f87d72009-11-05 16:08:51 -0500123 private static final int PROXIMITY_SENSOR_DELAY = 1000;
124
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400125 // trigger proximity if distance is less than 5 cm
126 private static final float PROXIMITY_THRESHOLD = 5.0f;
127
Doug Zongker43866e02010-01-07 12:09:54 -0800128 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
130
Amith Yamasani8b619832010-09-22 16:11:59 -0700131 // Default timeout for screen off, if not found in settings database = 15 seconds.
132 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
133
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800134 // Screen brightness should always have a value, but just in case...
135 private static final int DEFAULT_SCREEN_BRIGHTNESS = 192;
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 // flags for setPowerState
Jim Miller92e66dd2012-02-21 18:57:12 -0800138 private static final int ALL_LIGHTS_OFF = 0x00000000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private static final int SCREEN_ON_BIT = 0x00000001;
140 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
141 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
142 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
143 private static final int BATTERY_LOW_BIT = 0x00000010;
144
145 // values for setPowerState
146
147 // SCREEN_OFF == everything off
148 private static final int SCREEN_OFF = 0x00000000;
149
150 // SCREEN_DIM == screen on, screen backlight dim
151 private static final int SCREEN_DIM = SCREEN_ON_BIT;
152
153 // SCREEN_BRIGHT == screen on, screen backlight bright
154 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
155
156 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
157 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
158
159 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
160 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
161
162 // used for noChangeLights in setPowerState()
163 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
164
Jim Miller46f31c32012-03-01 14:36:07 -0800165 // animate screen lights in PowerManager (as opposed to SurfaceFlinger)
Joe Onoratob08a1af2010-10-11 19:28:58 -0700166 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800167
Jim Miller92e66dd2012-02-21 18:57:12 -0800168 static final int ANIM_STEPS = 60; // nominal # of frames at 60Hz
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400169 // Slower animation for autobrightness changes
Jim Miller92e66dd2012-02-21 18:57:12 -0800170 static final int AUTOBRIGHTNESS_ANIM_STEPS = 2 * ANIM_STEPS;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800171 // Number of steps when performing a more immediate brightness change.
172 static final int IMMEDIATE_ANIM_STEPS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174 // These magic numbers are the initial state of the LEDs at boot. Ideally
175 // we should read them from the driver, but our current hardware returns 0
176 // for the initial value. Oops!
177 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
178 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
179 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700182 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
184 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500185 private boolean mBootCompleted = false;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700186 private boolean mHeadless = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500188 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
189 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700190 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700191 private boolean mSkippedScreenOn = false;
192 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private int mPartialCount = 0;
194 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500195 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
196 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
197 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private int mUserState;
199 private boolean mKeyboardVisible = false;
200 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500201 private int mProximityWakeLockCount = 0;
202 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700203 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500204 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
205 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800206 private int mScreenOffTimeoutSetting;
207 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private int mKeylightDelay;
209 private int mDimDelay;
210 private int mScreenOffDelay;
211 private int mWakeLockState;
212 private long mLastEventTime = 0;
213 private long mScreenOffTime;
214 private volatile WindowManagerPolicy mPolicy;
215 private final LockList mLocks = new LockList();
216 private Intent mScreenOffIntent;
217 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500218 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500220 private LightsService.Light mLcdLight;
221 private LightsService.Light mButtonLight;
222 private LightsService.Light mKeyboardLight;
223 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private UnsynchronizedWakeLock mBroadcastWakeLock;
225 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
226 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
227 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500228 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700230 private Handler mScreenOffHandler;
Jim Miller92e66dd2012-02-21 18:57:12 -0800231 private Handler mScreenBrightnessHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500233 private final TimeoutTask mTimeoutTask = new TimeoutTask();
Jim Miller92e66dd2012-02-21 18:57:12 -0800234 private ScreenBrightnessAnimator mScreenBrightnessAnimator;
Joe Onorato128e7292009-03-24 18:41:31 -0700235 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private boolean mIsPowered = false;
237 private IActivityManager mActivityService;
238 private IBatteryStats mBatteryStats;
239 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700240 private SensorManager mSensorManager;
241 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400242 private Sensor mLightSensor;
243 private boolean mLightSensorEnabled;
244 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400245 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500246 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500247 private boolean mLightSensorPendingDecrease = false;
248 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700249 private float mLightSensorPendingValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800250 private float mLightSensorAdjustSetting = 0;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500251 private int mLightSensorScreenBrightness = -1;
252 private int mLightSensorButtonBrightness = -1;
253 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500255 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 private long mNextTimeout;
257 private volatile int mPokey = 0;
258 private volatile boolean mPokeAwakeOnSet = false;
259 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500260 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500261 // mLastScreenOnTime is the time the screen was last turned on
262 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 private boolean mPreventScreenOn;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800264 private int mScreenBrightnessSetting = DEFAULT_SCREEN_BRIGHTNESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500266 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400267 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400268 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700269 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700270 private int[] mAutoBrightnessLevels;
271 private int[] mLcdBacklightValues;
272 private int[] mButtonBacklightValues;
273 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500274 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700275 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700276 private int mWarningSpewThrottleCount;
277 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700278 private int mAnimationSetting = ANIM_SETTING_OFF;
Jim Miller92e66dd2012-02-21 18:57:12 -0800279 private float mWindowScaleAnimation;
Joe Onorato609695d2010-10-14 14:57:49 -0700280
281 // Must match with the ISurfaceComposer constants in C++.
282 private static final int ANIM_SETTING_ON = 0x01;
283 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284
285 // Used when logging number and duration of touch-down cycles
286 private long mTotalTouchDownTime;
287 private long mLastTouchDown;
288 private int mTouchCycles;
289
290 // could be either static or controllable at runtime
291 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400292 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwoodae92eb32011-10-25 10:11:46 -0400293 private static final boolean mDebugLightSensor = (false || mSpew);
Jim Miller92e66dd2012-02-21 18:57:12 -0800294 private static final boolean mDebugLightAnimation = (false || mSpew);
295
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700296 private native void nativeInit();
297 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700298 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
300 /*
301 static PrintStream mLog;
302 static {
303 try {
304 mLog = new PrintStream("/data/power.log");
305 }
306 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800307 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 }
309 }
310 static class Log {
311 static void d(String tag, String s) {
312 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800313 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315 static void i(String tag, String s) {
316 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800317 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319 static void w(String tag, String s) {
320 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800321 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 }
323 static void e(String tag, String s) {
324 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800325 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 }
327 }
328 */
329
330 /**
331 * This class works around a deadlock between the lock in PowerManager.WakeLock
332 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
333 * mToken object so it can be accessed from any thread, but it calls into here
334 * with its lock held. This class is essentially a reimplementation of
335 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
336 * only call it with our own locks held.
337 */
338 private class UnsynchronizedWakeLock {
339 int mFlags;
340 String mTag;
341 IBinder mToken;
342 int mCount = 0;
343 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500344 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345
346 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
347 mFlags = flags;
348 mTag = tag;
349 mToken = new Binder();
350 mRefCounted = refCounted;
351 }
352
353 public void acquire() {
354 if (!mRefCounted || mCount++ == 0) {
355 long ident = Binder.clearCallingIdentity();
356 try {
357 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700358 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500359 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 } finally {
361 Binder.restoreCallingIdentity(ident);
362 }
363 }
364 }
365
366 public void release() {
367 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500368 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500369 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371 if (mCount < 0) {
372 throw new RuntimeException("WakeLock under-locked " + mTag);
373 }
374 }
375
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500376 public boolean isHeld()
377 {
378 return mHeld;
379 }
380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 public String toString() {
382 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500383 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385 }
386
387 private final class BatteryReceiver extends BroadcastReceiver {
388 @Override
389 public void onReceive(Context context, Intent intent) {
390 synchronized (mLocks) {
391 boolean wasPowered = mIsPowered;
392 mIsPowered = mBatteryService.isPowered();
393
394 if (mIsPowered != wasPowered) {
395 // update mStayOnWhilePluggedIn wake lock
396 updateWakeLockLocked();
397
398 // treat plugging and unplugging the devices as a user activity.
399 // users find it disconcerting when they unplug the device
400 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500401 // to avoid turning on the screen when unplugging, we only trigger
402 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 // temporarily set mUserActivityAllowed to true so this will work
404 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700405 // However, you can also set config_unplugTurnsOnScreen to have it
406 // turn on. Some devices want this because they don't have a
407 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700409 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
410 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500411 forceUserActivityLocked();
412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 }
414 }
415 }
416 }
417 }
418
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500419 private final class BootCompletedReceiver extends BroadcastReceiver {
420 @Override
421 public void onReceive(Context context, Intent intent) {
422 bootCompleted();
423 }
424 }
425
Mike Lockwoodb2865412010-02-02 22:40:33 -0500426 private final class DockReceiver extends BroadcastReceiver {
427 @Override
428 public void onReceive(Context context, Intent intent) {
429 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
430 Intent.EXTRA_DOCK_STATE_UNDOCKED);
431 dockStateChanged(state);
432 }
433 }
434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 /**
436 * Set the setting that determines whether the device stays on when plugged in.
437 * The argument is a bit string, with each bit specifying a power source that,
438 * when the device is connected to that source, causes the device to stay on.
439 * See {@link android.os.BatteryManager} for the list of power sources that
440 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
441 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
442 * @param val an {@code int} containing the bits that specify which power sources
443 * should cause the device to stay on.
444 */
445 public void setStayOnSetting(int val) {
446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
447 Settings.System.putInt(mContext.getContentResolver(),
448 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
449 }
450
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800451 public void setMaximumScreenOffTimeount(int timeMs) {
452 mContext.enforceCallingOrSelfPermission(
453 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
454 synchronized (mLocks) {
455 mMaximumScreenOffTimeout = timeMs;
456 // recalculate everything
457 setScreenOffTimeoutsLocked();
458 }
459 }
460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700462 private int getInt(String name, int defValue) {
463 ContentValues values = mSettings.getValues(name);
464 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
465 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
467
Joe Onorato609695d2010-10-14 14:57:49 -0700468 private float getFloat(String name, float defValue) {
469 ContentValues values = mSettings.getValues(name);
470 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
471 return fVal != null ? fVal : defValue;
472 }
473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 public void update(Observable o, Object arg) {
475 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700476 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
477 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
478 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 updateWakeLockLocked();
480
Amith Yamasani8b619832010-09-22 16:11:59 -0700481 // SCREEN_OFF_TIMEOUT, default to 15 seconds
482 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483
Joe Onorato609695d2010-10-14 14:57:49 -0700484 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 //mDimScreen = getInt(DIM_SCREEN) != 0;
486
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800487 mScreenBrightnessSetting = getInt(SCREEN_BRIGHTNESS, DEFAULT_SCREEN_BRIGHTNESS);
488 mLightSensorAdjustSetting = getFloat(SCREEN_AUTO_BRIGHTNESS_ADJ, 0);
489
Amith Yamasani8b619832010-09-22 16:11:59 -0700490 // SCREEN_BRIGHTNESS_MODE, default to manual
491 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
492 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 // recalculate everything
495 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700496
Jim Miller92e66dd2012-02-21 18:57:12 -0800497 mWindowScaleAnimation = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
Joe Onorato609695d2010-10-14 14:57:49 -0700498 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
499 mAnimationSetting = 0;
Jim Miller92e66dd2012-02-21 18:57:12 -0800500 if (mWindowScaleAnimation > 0.5f) {
Joe Onorato609695d2010-10-14 14:57:49 -0700501 mAnimationSetting |= ANIM_SETTING_OFF;
502 }
503 if (transitionScale > 0.5f) {
504 // Uncomment this if you want the screen-on animation.
505 // mAnimationSetting |= ANIM_SETTING_ON;
506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508 }
509 }
510
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700511 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 // Hack to get our uid... should have a func for this.
513 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700514 MY_UID = Process.myUid();
515 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 Binder.restoreCallingIdentity(token);
517
518 // XXX remove this when the kernel doesn't timeout wake locks
519 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
520
521 // assume nothing is on yet
522 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 // Add ourself to the Watchdog monitors.
525 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 }
527
528 private ContentQueryMap mSettings;
529
Mike Lockwood3a322132009-11-24 00:30:52 -0500530 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700531 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500532 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 mContext = context;
534 mActivityService = activity;
535 mBatteryStats = BatteryStatsService.getService();
536 mBatteryService = battery;
537
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500538 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
539 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
540 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
541 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700542 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500543
Joe Onoratob08a1af2010-10-11 19:28:58 -0700544 nativeInit();
545 synchronized (mLocks) {
546 updateNativePowerStateLocked();
547 }
548
549 mInitComplete = false;
Jim Miller92e66dd2012-02-21 18:57:12 -0800550 mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread",
551 Process.THREAD_PRIORITY_DISPLAY);
552 mScreenBrightnessAnimator.start();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700553
Jim Miller92e66dd2012-02-21 18:57:12 -0800554 synchronized (mScreenBrightnessAnimator) {
Joe Onoratob08a1af2010-10-11 19:28:58 -0700555 while (!mInitComplete) {
556 try {
Jim Miller92e66dd2012-02-21 18:57:12 -0800557 mScreenBrightnessAnimator.wait();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700558 } catch (InterruptedException e) {
559 // Ignore
560 }
561 }
562 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800563
Joe Onoratob08a1af2010-10-11 19:28:58 -0700564 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 mHandlerThread = new HandlerThread("PowerManagerService") {
566 @Override
567 protected void onLooperPrepared() {
568 super.onLooperPrepared();
569 initInThread();
570 }
571 };
572 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 synchronized (mHandlerThread) {
575 while (!mInitComplete) {
576 try {
577 mHandlerThread.wait();
578 } catch (InterruptedException e) {
579 // Ignore
580 }
581 }
582 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800583
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700584 nativeInit();
Todd Poynor94d00242012-01-11 20:14:34 -0800585 Power.powerInitNative();
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700586 synchronized (mLocks) {
587 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700588 // We make sure to start out with the screen on due to user activity.
589 // (They did just boot their device, after all.)
590 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700591 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 void initInThread() {
596 mHandler = new Handler();
597
598 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700599 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
601 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
602 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
603 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
604 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
605 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500606 mProximityPartialLock = new UnsynchronizedWakeLock(
607 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608
609 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
610 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
611 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
612 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
613
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700614 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400615
Joe Onoratob08a1af2010-10-11 19:28:58 -0700616 mAnimateScreenLights = resources.getBoolean(
617 com.android.internal.R.bool.config_animateScreenLights);
618
Joe Onorato6d747652010-10-11 15:15:31 -0700619 mUnplugTurnsOnScreen = resources.getBoolean(
620 com.android.internal.R.bool.config_unplugTurnsOnScreen);
621
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400622 mScreenBrightnessDim = resources.getInteger(
623 com.android.internal.R.integer.config_screenBrightnessDim);
624
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400625 // read settings for auto-brightness
626 mUseSoftwareAutoBrightness = resources.getBoolean(
627 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400628 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700629 mAutoBrightnessLevels = resources.getIntArray(
630 com.android.internal.R.array.config_autoBrightnessLevels);
631 mLcdBacklightValues = resources.getIntArray(
632 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
633 mButtonBacklightValues = resources.getIntArray(
634 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
635 mKeyboardBacklightValues = resources.getIntArray(
636 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500637 mLightSensorWarmupTime = resources.getInteger(
638 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700639 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700640
641 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
643 "(" + Settings.System.NAME + "=?) or ("
644 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700645 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700646 + Settings.System.NAME + "=?) or ("
647 + Settings.System.NAME + "=?) or ("
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800648 + Settings.System.NAME + "=?) or ("
649 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 + Settings.System.NAME + "=?)",
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800651 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS,
652 SCREEN_BRIGHTNESS_MODE, SCREEN_AUTO_BRIGHTNESS_ADJ,
653 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 null);
655 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
656 SettingsObserver settingsObserver = new SettingsObserver();
657 mSettings.addObserver(settingsObserver);
658
659 // pretend that the settings changed so we will get their initial state
660 settingsObserver.update(mSettings, null);
661
662 // register for the battery changed notifications
663 IntentFilter filter = new IntentFilter();
664 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
665 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500666 filter = new IntentFilter();
667 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
668 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500669 filter = new IntentFilter();
670 filter.addAction(Intent.ACTION_DOCK_EVENT);
671 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
Doug Zongker43866e02010-01-07 12:09:54 -0800673 // Listen for secure settings changes
674 mContext.getContentResolver().registerContentObserver(
675 Settings.Secure.CONTENT_URI, true,
676 new ContentObserver(new Handler()) {
677 public void onChange(boolean selfChange) {
678 updateSettingsValues();
679 }
680 });
681 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 synchronized (mHandlerThread) {
684 mInitComplete = true;
685 mHandlerThread.notifyAll();
686 }
687 }
688
689 private class WakeLock implements IBinder.DeathRecipient
690 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700691 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 super();
693 flags = f;
694 binder = b;
695 tag = t;
696 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700697 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 if (u != MY_UID || (
699 !"KEEP_SCREEN_ON_FLAG".equals(tag)
700 && !"KeyInputQueue".equals(tag))) {
701 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
702 ? BatteryStats.WAKE_TYPE_PARTIAL
703 : BatteryStats.WAKE_TYPE_FULL;
704 } else {
705 monitorType = -1;
706 }
707 try {
708 b.linkToDeath(this, 0);
709 } catch (RemoteException e) {
710 binderDied();
711 }
712 }
713 public void binderDied() {
714 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500715 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717 }
718 final int flags;
719 final IBinder binder;
720 final String tag;
721 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400722 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700724 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 boolean activated = true;
726 int minState;
727 }
728
729 private void updateWakeLockLocked() {
730 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
731 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
732 mStayOnWhilePluggedInScreenDimLock.acquire();
733 mStayOnWhilePluggedInPartialLock.acquire();
734 } else {
735 mStayOnWhilePluggedInScreenDimLock.release();
736 mStayOnWhilePluggedInPartialLock.release();
737 }
738 }
739
740 private boolean isScreenLock(int flags)
741 {
742 int n = flags & LOCK_MASK;
743 return n == PowerManager.FULL_WAKE_LOCK
744 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400745 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
746 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 }
748
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700749 void enforceWakeSourcePermission(int uid, int pid) {
750 if (uid == Process.myUid()) {
751 return;
752 }
753 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
754 pid, uid, null);
755 }
756
757 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700759 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700760 if (uid != Process.myUid()) {
761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
762 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700763 if (ws != null) {
764 enforceWakeSourcePermission(uid, pid);
765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 long ident = Binder.clearCallingIdentity();
767 try {
768 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700769 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
771 } finally {
772 Binder.restoreCallingIdentity(ident);
773 }
774 }
775
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700776 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700777 if (wl.monitorType >= 0) {
778 long origId = Binder.clearCallingIdentity();
779 try {
780 if (ws != null) {
781 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
782 wl.monitorType);
783 } else {
784 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
785 }
786 } catch (RemoteException e) {
787 // Ignore
788 } finally {
789 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700791 }
792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700794 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700795 if (wl.monitorType >= 0) {
796 long origId = Binder.clearCallingIdentity();
797 try {
798 if (ws != null) {
799 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
800 wl.monitorType);
801 } else {
802 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
803 }
804 } catch (RemoteException e) {
805 // Ignore
806 } finally {
807 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700808 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700809 }
810 }
811
812 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
813 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800815 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700818 if (ws != null && ws.size() == 0) {
819 ws = null;
820 }
821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 int index = mLocks.getIndex(lock);
823 WakeLock wl;
824 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700825 boolean diffsource;
826 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700828 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 switch (wl.flags & LOCK_MASK)
830 {
831 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500832 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400833 wl.minState = SCREEN_BRIGHT;
834 } else {
835 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 break;
838 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
839 wl.minState = SCREEN_BRIGHT;
840 break;
841 case PowerManager.SCREEN_DIM_WAKE_LOCK:
842 wl.minState = SCREEN_DIM;
843 break;
844 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700845 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 break;
847 default:
848 // just log and bail. we're in the server, so don't
849 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800850 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 + " flags=" + flags);
852 return;
853 }
854 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700855 if (ws != null) {
856 wl.ws = new WorkSource(ws);
857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700859 diffsource = false;
860 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 } else {
862 wl = mLocks.get(index);
863 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700864 oldsource = wl.ws;
865 if (oldsource != null) {
866 if (ws == null) {
867 wl.ws = null;
868 diffsource = true;
869 } else {
870 diffsource = oldsource.diff(ws);
871 }
872 } else if (ws != null) {
873 diffsource = true;
874 } else {
875 diffsource = false;
876 }
877 if (diffsource) {
878 wl.ws = new WorkSource(ws);
879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881 if (isScreenLock(flags)) {
882 // if this causes a wakeup, we reactivate all of the locks and
883 // set it to whatever they want. otherwise, we modulate that
884 // by the current state so we never turn it more on than
885 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400886 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
887 mProximityWakeLockCount++;
888 if (mProximityWakeLockCount == 1) {
889 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400892 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
893 int oldWakeLockState = mWakeLockState;
894 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400895
896 // Disable proximity sensor if if user presses power key while we are in the
897 // "waiting for proximity sensor to go negative" state.
898 if ((mWakeLockState & SCREEN_ON_BIT) != 0
899 && mProximitySensorActive && mProximityWakeLockCount == 0) {
900 mProximitySensorActive = false;
901 }
902
Joe Onorato8274a0e2010-10-05 17:38:09 -0400903 if (mSpew) {
904 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
905 + " mWakeLockState=0x"
906 + Integer.toHexString(mWakeLockState)
907 + " previous wakeLockState=0x"
908 + Integer.toHexString(oldWakeLockState));
909 }
910 } else {
911 if (mSpew) {
912 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
913 + " mLocks.gatherState()=0x"
914 + Integer.toHexString(mLocks.gatherState())
915 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
916 }
917 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400919 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 }
922 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
923 if (newlock) {
924 mPartialCount++;
925 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
928 }
929 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700932 if (diffsource) {
933 // If the lock sources have changed, need to first release the
934 // old ones.
935 noteStopWakeLocked(wl, oldsource);
936 }
937 if (newlock || diffsource) {
938 noteStartWakeLocked(wl, ws);
939 }
940 }
941
942 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
943 int uid = Binder.getCallingUid();
944 int pid = Binder.getCallingPid();
945 if (ws != null && ws.size() == 0) {
946 ws = null;
947 }
948 if (ws != null) {
949 enforceWakeSourcePermission(uid, pid);
950 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700951 synchronized (mLocks) {
952 int index = mLocks.getIndex(lock);
953 if (index < 0) {
954 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700956 WakeLock wl = mLocks.get(index);
957 WorkSource oldsource = wl.ws;
958 wl.ws = ws != null ? new WorkSource(ws) : null;
959 noteStopWakeLocked(wl, oldsource);
960 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962 }
963
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500964 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700965 int uid = Binder.getCallingUid();
966 if (uid != Process.myUid()) {
967 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
970 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500971 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973 }
974
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500975 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 WakeLock wl = mLocks.removeLock(lock);
977 if (wl == null) {
978 return;
979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800982 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
984 }
985
986 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400987 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
988 mProximityWakeLockCount--;
989 if (mProximityWakeLockCount == 0) {
990 if (mProximitySensorActive &&
991 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
992 // wait for proximity sensor to go negative before disabling sensor
993 if (mDebugProximitySensor) {
994 Slog.d(TAG, "waiting for proximity sensor to go negative");
995 }
996 } else {
997 disableProximityLockLocked();
998 }
999 }
1000 } else {
1001 mWakeLockState = mLocks.gatherState();
1002 // goes in the middle to reduce flicker
1003 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
1004 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
1005 }
1006 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
1009 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
1010 mPartialCount--;
1011 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001012 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 Power.releaseWakeLock(PARTIAL_NAME);
1014 }
1015 }
1016 // Unlink the lock from the binder.
1017 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018
Dianne Hackborn70be1672010-09-14 11:13:03 -07001019 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 private class PokeLock implements IBinder.DeathRecipient
1023 {
1024 PokeLock(int p, IBinder b, String t) {
1025 super();
1026 this.pokey = p;
1027 this.binder = b;
1028 this.tag = t;
1029 try {
1030 b.linkToDeath(this, 0);
1031 } catch (RemoteException e) {
1032 binderDied();
1033 }
1034 }
1035 public void binderDied() {
1036 setPokeLock(0, this.binder, this.tag);
1037 }
1038 int pokey;
1039 IBinder binder;
1040 String tag;
1041 boolean awakeOnSet;
1042 }
1043
1044 public void setPokeLock(int pokey, IBinder token, String tag) {
1045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1046 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001047 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 return;
1049 }
1050
1051 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1052 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1053 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1054 }
1055
1056 synchronized (mLocks) {
1057 if (pokey != 0) {
1058 PokeLock p = mPokeLocks.get(token);
1059 int oldPokey = 0;
1060 if (p != null) {
1061 oldPokey = p.pokey;
1062 p.pokey = pokey;
1063 } else {
1064 p = new PokeLock(pokey, token, tag);
1065 mPokeLocks.put(token, p);
1066 }
1067 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1068 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1069 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1070 p.awakeOnSet = true;
1071 }
1072 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001073 PokeLock rLock = mPokeLocks.remove(token);
1074 if (rLock != null) {
1075 token.unlinkToDeath(rLock, 0);
1076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
1079 int oldPokey = mPokey;
1080 int cumulative = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 boolean awakeOnSet = false;
1082 for (PokeLock p: mPokeLocks.values()) {
1083 cumulative |= p.pokey;
1084 if (p.awakeOnSet) {
1085 awakeOnSet = true;
1086 }
1087 }
1088 mPokey = cumulative;
1089 mPokeAwakeOnSet = awakeOnSet;
1090
1091 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1092 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 if (oldCumulativeTimeout != newCumulativeTimeout) {
1095 setScreenOffTimeoutsLocked();
1096 // reset the countdown timer, but use the existing nextState so it doesn't
1097 // change anything
1098 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1099 }
1100 }
1101 }
1102
1103 private static String lockType(int type)
1104 {
1105 switch (type)
1106 {
1107 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001108 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001110 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001112 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001114 return "PARTIAL_WAKE_LOCK ";
1115 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1116 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 default:
David Brown251faa62009-08-02 22:04:36 -07001118 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120 }
1121
1122 private static String dumpPowerState(int state) {
1123 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1124 ? "KEYBOARD_BRIGHT_BIT " : "")
1125 + (((state & SCREEN_BRIGHT_BIT) != 0)
1126 ? "SCREEN_BRIGHT_BIT " : "")
1127 + (((state & SCREEN_ON_BIT) != 0)
1128 ? "SCREEN_ON_BIT " : "")
1129 + (((state & BATTERY_LOW_BIT) != 0)
1130 ? "BATTERY_LOW_BIT " : "");
1131 }
1132
1133 @Override
1134 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1135 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1136 != PackageManager.PERMISSION_GRANTED) {
1137 pw.println("Permission Denial: can't dump PowerManager from from pid="
1138 + Binder.getCallingPid()
1139 + ", uid=" + Binder.getCallingUid());
1140 return;
1141 }
1142
1143 long now = SystemClock.uptimeMillis();
1144
Mike Lockwoodca44df82010-02-25 13:48:49 -05001145 synchronized (mLocks) {
1146 pw.println("Power Manager State:");
1147 pw.println(" mIsPowered=" + mIsPowered
1148 + " mPowerState=" + mPowerState
1149 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1150 + " ms");
1151 pw.println(" mPartialCount=" + mPartialCount);
1152 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1153 pw.println(" mUserState=" + dumpPowerState(mUserState));
1154 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1155 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1156 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1157 + " " + ((mNextTimeout-now)/1000) + "s from now");
1158 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001159 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001160 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1161 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001162 pw.println(" mScreenOffReason=" + mScreenOffReason
1163 + " mUserState=" + mUserState);
1164 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1165 + ',' + mBroadcastQueue[2] + "}");
1166 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1167 + ',' + mBroadcastWhy[2] + "}");
1168 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1169 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1170 + " mUserActivityAllowed=" + mUserActivityAllowed);
1171 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1172 + " mScreenOffDelay=" + mScreenOffDelay);
1173 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1174 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1175 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1176 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1177 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1178 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1179 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1180 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1181 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1182 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1183 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1184 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1185 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1186 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1187 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1188 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08001189 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled
1190 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001191 pw.println(" mLightSensorValue=" + mLightSensorValue
1192 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001193 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1194 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001195 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1196 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1197 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1198 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1199 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
Jim Miller92e66dd2012-02-21 18:57:12 -08001200 mScreenBrightnessAnimator.dump(pw, " mScreenBrightnessAnimator: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001201
Mike Lockwoodca44df82010-02-25 13:48:49 -05001202 int N = mLocks.size();
1203 pw.println();
1204 pw.println("mLocks.size=" + N + ":");
1205 for (int i=0; i<N; i++) {
1206 WakeLock wl = mLocks.get(i);
1207 String type = lockType(wl.flags & LOCK_MASK);
1208 String acquireCausesWakeup = "";
1209 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1210 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1211 }
1212 String activated = "";
1213 if (wl.activated) {
1214 activated = " activated";
1215 }
1216 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001217 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1218 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001220
1221 pw.println();
1222 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1223 for (PokeLock p: mPokeLocks.values()) {
1224 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001225 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1226 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001227 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1228 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1229 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1230 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232
Mike Lockwoodca44df82010-02-25 13:48:49 -05001233 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236
Joe Onorato7999bff2010-07-24 11:50:05 -04001237 private void setTimeoutLocked(long now, int nextState) {
1238 setTimeoutLocked(now, -1, nextState);
1239 }
1240
1241 // If they gave a timeoutOverride it is the number of seconds
1242 // to screen-off. Figure out where in the countdown cycle we
1243 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001244 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1245 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001246 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001247 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001248 long when = 0;
1249 if (timeoutOverride <= 0) {
1250 switch (nextState)
1251 {
1252 case SCREEN_BRIGHT:
1253 when = now + mKeylightDelay;
1254 break;
1255 case SCREEN_DIM:
1256 if (mDimDelay >= 0) {
1257 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001258 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001259 } else {
1260 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1261 }
1262 case SCREEN_OFF:
1263 synchronized (mLocks) {
1264 when = now + mScreenOffDelay;
1265 }
1266 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001267 default:
1268 when = now;
1269 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001271 } else {
1272 override: {
1273 if (timeoutOverride <= mScreenOffDelay) {
1274 when = now + timeoutOverride;
1275 nextState = SCREEN_OFF;
1276 break override;
1277 }
1278 timeoutOverride -= mScreenOffDelay;
1279
1280 if (mDimDelay >= 0) {
1281 if (timeoutOverride <= mDimDelay) {
1282 when = now + timeoutOverride;
1283 nextState = SCREEN_DIM;
1284 break override;
1285 }
1286 timeoutOverride -= mDimDelay;
1287 }
1288
1289 when = now + timeoutOverride;
1290 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001292 }
1293 if (mSpew) {
1294 Slog.d(TAG, "setTimeoutLocked now=" + now
1295 + " timeoutOverride=" + timeoutOverride
1296 + " nextState=" + nextState + " when=" + when);
1297 }
Joe Onorato797e6882010-08-26 14:46:01 -04001298
1299 mHandler.removeCallbacks(mTimeoutTask);
1300 mTimeoutTask.nextState = nextState;
1301 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1302 ? (originalTimeoutOverride - timeoutOverride)
1303 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001304 mHandler.postAtTime(mTimeoutTask, when);
1305 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308 }
1309
1310 private void cancelTimerLocked()
1311 {
1312 mHandler.removeCallbacks(mTimeoutTask);
1313 mTimeoutTask.nextState = -1;
1314 }
1315
1316 private class TimeoutTask implements Runnable
1317 {
1318 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001319 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 public void run()
1321 {
1322 synchronized (mLocks) {
1323 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001324 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326
1327 if (nextState == -1) {
1328 return;
1329 }
1330
1331 mUserState = this.nextState;
1332 setPowerState(this.nextState | mWakeLockState);
1333
1334 long now = SystemClock.uptimeMillis();
1335
1336 switch (this.nextState)
1337 {
1338 case SCREEN_BRIGHT:
1339 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001340 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 break;
1342 }
1343 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001344 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 break;
1346 }
1347 }
1348 }
1349 }
1350
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001351 private void sendNotificationLocked(boolean on, int why) {
1352 if (!mInitialized) {
1353 // No notifications sent until first initialization is done.
1354 // This is so that when we are moving from our initial state
1355 // which looks like the screen was off to it being on, we do not
1356 // go through the process of waiting for the higher-level user
1357 // space to be ready before turning up the display brightness.
1358 // (And also do not send needless broadcasts about the screen.)
1359 return;
1360 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001361
1362 if (DEBUG_SCREEN_ON) {
1363 RuntimeException here = new RuntimeException("here");
1364 here.fillInStackTrace();
1365 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1366 }
1367
Joe Onorato64c62ba2009-03-24 20:13:57 -07001368 if (!on) {
1369 mStillNeedSleepNotification = false;
1370 }
1371
Joe Onorato128e7292009-03-24 18:41:31 -07001372 // Add to the queue.
1373 int index = 0;
1374 while (mBroadcastQueue[index] != -1) {
1375 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Joe Onorato128e7292009-03-24 18:41:31 -07001377 mBroadcastQueue[index] = on ? 1 : 0;
1378 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
Joe Onorato128e7292009-03-24 18:41:31 -07001380 // If we added it position 2, then there is a pair that can be stripped.
1381 // If we added it position 1 and we're turning the screen off, we can strip
1382 // the pair and do nothing, because the screen is already off, and therefore
1383 // keyguard has already been enabled.
1384 // However, if we added it at position 1 and we're turning it on, then position
1385 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1386 // on, so have to run the queue then.
1387 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001388 // While we're collapsing them, if it's going off, and the new reason
1389 // is more significant than the first, then use the new one.
1390 if (!on && mBroadcastWhy[0] > why) {
1391 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001392 }
1393 mBroadcastQueue[0] = on ? 1 : 0;
1394 mBroadcastQueue[1] = -1;
1395 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001396 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001397 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001398 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001399 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001400 index = 0;
1401 }
1402 if (index == 1 && !on) {
1403 mBroadcastQueue[0] = -1;
1404 mBroadcastQueue[1] = -1;
1405 index = -1;
1406 // The wake lock was being held, but we're not actually going to do any
1407 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001408 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001410 }
1411
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001412 // The broadcast queue has changed; make sure the screen is on if it
1413 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001414 if (mSkippedScreenOn) {
1415 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1416 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001417
Joe Onorato128e7292009-03-24 18:41:31 -07001418 // Now send the message.
1419 if (index >= 0) {
1420 // Acquire the broadcast wake lock before changing the power
1421 // state. It will be release after the broadcast is sent.
1422 // We always increment the ref count for each notification in the queue
1423 // and always decrement when that notification is handled.
1424 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001425 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001426 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 }
1429
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001430 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1431 new WindowManagerPolicy.ScreenOnListener() {
Jim Miller92e66dd2012-02-21 18:57:12 -08001432 public void onScreenOn() {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001433 synchronized (mLocks) {
1434 if (mPreparingForScreenOn) {
1435 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001436 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001437 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1438 4, mBroadcastWakeLock.mCount);
1439 mBroadcastWakeLock.release();
1440 }
1441 }
1442 }
1443 };
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 private Runnable mNotificationTask = new Runnable()
1446 {
1447 public void run()
1448 {
Joe Onorato128e7292009-03-24 18:41:31 -07001449 while (true) {
1450 int value;
1451 int why;
1452 WindowManagerPolicy policy;
1453 synchronized (mLocks) {
1454 value = mBroadcastQueue[0];
1455 why = mBroadcastWhy[0];
1456 for (int i=0; i<2; i++) {
1457 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1458 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1459 }
1460 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001461 if (value == 1 && !mPreparingForScreenOn) {
1462 mPreparingForScreenOn = true;
1463 mBroadcastWakeLock.acquire();
1464 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1465 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
Joe Onorato128e7292009-03-24 18:41:31 -07001468 if (value == 1) {
1469 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001470
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001471 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001472 try {
1473 ActivityManagerNative.getDefault().wakingUp();
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 (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001480 }
1481 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1482 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1483 mScreenOnBroadcastDone, mHandler, 0, null, null);
1484 } else {
1485 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001487 mBroadcastWakeLock.mCount);
1488 mBroadcastWakeLock.release();
1489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491 }
Joe Onorato128e7292009-03-24 18:41:31 -07001492 else if (value == 0) {
1493 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001494
Joe Onorato128e7292009-03-24 18:41:31 -07001495 policy.screenTurnedOff(why);
1496 try {
1497 ActivityManagerNative.getDefault().goingToSleep();
1498 } catch (RemoteException e) {
1499 // ignore it.
1500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501
Joe Onorato128e7292009-03-24 18:41:31 -07001502 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1503 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1504 mScreenOffBroadcastDone, mHandler, 0, null, null);
1505 } else {
1506 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001507 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001508 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001509 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001510 mBroadcastWakeLock.release();
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 }
Joe Onorato128e7292009-03-24 18:41:31 -07001514 else {
1515 // If we're in this case, then this handler is running for a previous
1516 // paired transaction. mBroadcastWakeLock will already have been released.
1517 break;
1518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520 }
1521 };
1522
1523 long mScreenOnStart;
1524 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1525 public void onReceive(Context context, Intent intent) {
1526 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001527 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1529 mBroadcastWakeLock.release();
1530 }
1531 }
1532 };
1533
1534 long mScreenOffStart;
1535 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1536 public void onReceive(Context context, Intent intent) {
1537 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001538 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1540 mBroadcastWakeLock.release();
1541 }
1542 }
1543 };
1544
1545 void logPointerUpEvent() {
1546 if (LOG_TOUCH_DOWNS) {
1547 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1548 mLastTouchDown = 0;
1549 }
1550 }
1551
1552 void logPointerDownEvent() {
1553 if (LOG_TOUCH_DOWNS) {
1554 // If we are not already timing a down/up sequence
1555 if (mLastTouchDown == 0) {
1556 mLastTouchDown = SystemClock.elapsedRealtime();
1557 mTouchCycles++;
1558 }
1559 }
1560 }
1561
1562 /**
1563 * Prevents the screen from turning on even if it *should* turn on due
1564 * to a subsequent full wake lock being acquired.
1565 * <p>
1566 * This is a temporary hack that allows an activity to "cover up" any
1567 * display glitches that happen during the activity's startup
1568 * sequence. (Specifically, this API was added to work around a
1569 * cosmetic bug in the "incoming call" sequence, where the lock screen
1570 * would flicker briefly before the incoming call UI became visible.)
1571 * TODO: There ought to be a more elegant way of doing this,
1572 * probably by having the PowerManager and ActivityManager
1573 * work together to let apps specify that the screen on/off
1574 * state should be synchronized with the Activity lifecycle.
1575 * <p>
1576 * Note that calling preventScreenOn(true) will NOT turn the screen
1577 * off if it's currently on. (This API only affects *future*
1578 * acquisitions of full wake locks.)
1579 * But calling preventScreenOn(false) WILL turn the screen on if
1580 * it's currently off because of a prior preventScreenOn(true) call.
1581 * <p>
1582 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1583 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1584 * call doesn't occur within 5 seconds, we'll turn the screen back on
1585 * ourselves (and log a warning about it); this prevents a buggy app
1586 * from disabling the screen forever.)
1587 * <p>
1588 * TODO: this feature should really be controlled by a new type of poke
1589 * lock (rather than an IPowerManager call).
1590 */
1591 public void preventScreenOn(boolean prevent) {
1592 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1593
1594 synchronized (mLocks) {
1595 if (prevent) {
1596 // First of all, grab a partial wake lock to
1597 // make sure the CPU stays on during the entire
1598 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1599 mPreventScreenOnPartialLock.acquire();
1600
1601 // Post a forceReenableScreen() call (for 5 seconds in the
1602 // future) to make sure the matching preventScreenOn(false) call
1603 // has happened by then.
1604 mHandler.removeCallbacks(mForceReenableScreenTask);
1605 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1606
1607 // Finally, set the flag that prevents the screen from turning on.
1608 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001609 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 mPreventScreenOn = true;
1611 } else {
1612 // (Re)enable the screen.
1613 mPreventScreenOn = false;
1614
1615 // We're "undoing" a the prior preventScreenOn(true) call, so we
1616 // no longer need the 5-second safeguard.
1617 mHandler.removeCallbacks(mForceReenableScreenTask);
1618
1619 // Forcibly turn on the screen if it's supposed to be on. (This
1620 // handles the case where the screen is currently off because of
1621 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001622 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001624 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1626 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001627 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001629 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
1631 }
1632
1633 // Release the partial wake lock that we held during the
1634 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1635 mPreventScreenOnPartialLock.release();
1636 }
1637 }
1638 }
1639
1640 public void setScreenBrightnessOverride(int brightness) {
1641 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1642
Mike Lockwoodf527c712010-06-10 14:12:33 -04001643 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 synchronized (mLocks) {
1645 if (mScreenBrightnessOverride != brightness) {
1646 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001647 if (isScreenOn()) {
1648 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
1652 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001653
1654 public void setButtonBrightnessOverride(int brightness) {
1655 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1656
Mike Lockwoodf527c712010-06-10 14:12:33 -04001657 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001658 synchronized (mLocks) {
1659 if (mButtonBrightnessOverride != brightness) {
1660 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001661 if (isScreenOn()) {
1662 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1663 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001664 }
1665 }
1666 }
1667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 /**
1669 * Sanity-check that gets called 5 seconds after any call to
1670 * preventScreenOn(true). This ensures that the original call
1671 * is followed promptly by a call to preventScreenOn(false).
1672 */
1673 private void forceReenableScreen() {
1674 // We shouldn't get here at all if mPreventScreenOn is false, since
1675 // we should have already removed any existing
1676 // mForceReenableScreenTask messages...
1677 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001678 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 return;
1680 }
1681
1682 // Uh oh. It's been 5 seconds since a call to
1683 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1684 // This means the app that called preventScreenOn(true) is either
1685 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1686 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1687 // crashed before doing so.)
1688
1689 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001690 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 + "Forcing the screen back on...");
1692 preventScreenOn(false);
1693 }
1694
1695 private Runnable mForceReenableScreenTask = new Runnable() {
1696 public void run() {
1697 forceReenableScreen();
1698 }
1699 };
1700
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001701 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001702 if (DEBUG_SCREEN_ON) {
1703 RuntimeException e = new RuntimeException("here");
1704 e.fillInStackTrace();
1705 Slog.i(TAG, "Set screen state: " + on, e);
1706 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001707 if (on) {
1708 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1709 // If we are turning the screen state on, but the screen
1710 // light is currently off, then make sure that we set the
1711 // light at this point to 0. This is the case where we are
1712 // turning on the screen and waiting for the UI to be drawn
1713 // before showing it to the user. We want the light off
1714 // until it is ready to be shown to the user, not it using
1715 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001716 if (DEBUG_SCREEN_ON) {
1717 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1718 + Integer.toHexString(mPowerState)
1719 + " mSkippedScreenOn=" + mSkippedScreenOn);
1720 }
Jim Miller46f31c32012-03-01 14:36:07 -08001721 mScreenBrightnessHandler.removeMessages(ScreenBrightnessAnimator.ANIMATE_LIGHTS);
Jim Miller92e66dd2012-02-21 18:57:12 -08001722 mScreenBrightnessAnimator.animateTo(Power.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
Dianne Hackborn474fd742011-10-10 18:40:22 -07001723 }
1724 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001725 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001726 if (err == 0) {
1727 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1728 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001729 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001730 if (!on) {
1731 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001732 mButtonLight.turnOff();
1733 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001734 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001735 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001736 }
1737 return err;
1738 }
1739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 private void setPowerState(int state)
1741 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001742 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744
Mike Lockwood435eb642009-12-03 08:40:18 -05001745 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 {
1747 synchronized (mLocks) {
1748 int err;
1749
1750 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001751 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001753 + " noChangeLights=" + noChangeLights
1754 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
Daniel Sandler7d276c32012-01-30 14:33:52 -05001756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (noChangeLights) {
1758 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1759 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001760 if (mProximitySensorActive) {
1761 // don't turn on the screen when the proximity sensor lock is held
1762 newState = (newState & ~SCREEN_BRIGHT);
1763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764
1765 if (batteryIsLow()) {
1766 newState |= BATTERY_LOW_BIT;
1767 } else {
1768 newState &= ~BATTERY_LOW_BIT;
1769 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001770 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 return;
1772 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001773
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001774 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 newState |= ALL_BRIGHT;
1776 }
1777
1778 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1779 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1780
Mike Lockwood51b844962009-11-16 21:51:18 -05001781 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001782 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001784 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001786 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001788 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001790 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001792 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1794 }
1795
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001796 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797
Daniel Sandler7d276c32012-01-30 14:33:52 -05001798 if (stateChanged && reason == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT) {
Daniel Sandler0af48952012-04-10 15:14:35 -04001799 if (mPolicy != null && mPolicy.isScreenSaverEnabled()) {
Daniel Sandler7d276c32012-01-30 14:33:52 -05001800 if (mSpew) {
1801 Slog.d(TAG, "setPowerState: running screen saver instead of turning off screen");
1802 }
1803 if (mPolicy.startScreenSaver()) {
1804 // was successful
1805 return;
1806 }
1807 }
1808 }
1809
1810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 if (oldScreenOn != newScreenOn) {
1812 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001813 // When the user presses the power button, we need to always send out the
1814 // notification that it's going to sleep so the keyguard goes on. But
1815 // we can't do that until the screen fades out, so we don't show the keyguard
1816 // too early.
1817 if (mStillNeedSleepNotification) {
1818 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1819 }
1820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 // Turn on the screen UNLESS there was a prior
1822 // preventScreenOn(true) request. (Note that the lifetime
1823 // of a single preventScreenOn() request is limited to 5
1824 // seconds to prevent a buggy app from disabling the
1825 // screen forever; see forceReenableScreen().)
1826 boolean reallyTurnScreenOn = true;
1827 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001828 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 + mPreventScreenOn);
1830 }
1831
1832 if (mPreventScreenOn) {
1833 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001834 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 reallyTurnScreenOn = false;
1837 }
1838 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001839 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 long identity = Binder.clearCallingIdentity();
1841 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001842 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 mBatteryStats.noteScreenOn();
1844 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001845 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 } finally {
1847 Binder.restoreCallingIdentity(identity);
1848 }
1849 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001850 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 // But continue as if we really did turn the screen on...
1852 err = 0;
1853 }
1854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 mLastTouchDown = 0;
1856 mTotalTouchDownTime = 0;
1857 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001858 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 mTotalTouchDownTime, mTouchCycles);
1860 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001862 // Update the lights *after* taking care of turning the
1863 // screen on, so we do this after our notifications are
1864 // enqueued and thus will delay turning on the screen light
1865 // until the windows are correctly displayed.
1866 if (stateChanged) {
1867 updateLightsLocked(newState, 0);
1868 }
1869 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001873 // Update the lights *before* taking care of turning the
1874 // screen off, so we can initiate any animations that are desired.
Craig Mautner44bf70f2012-03-13 11:38:38 -07001875 mScreenOffReason = reason;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001876 if (stateChanged) {
1877 updateLightsLocked(newState, 0);
1878 }
1879
Mike Lockwood497087e32009-11-08 18:33:03 -05001880 // cancel light sensor task
1881 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001882 mLightSensorPendingDecrease = false;
1883 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 mScreenOffTime = SystemClock.elapsedRealtime();
1885 long identity = Binder.clearCallingIdentity();
1886 try {
1887 mBatteryStats.noteScreenOff();
1888 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001889 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 } finally {
1891 Binder.restoreCallingIdentity(identity);
1892 }
1893 mPowerState &= ~SCREEN_ON_BIT;
Jim Miller92e66dd2012-02-21 18:57:12 -08001894 if (!mScreenBrightnessAnimator.isAnimating()) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001895 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 err = 0;
1898 mLastTouchDown = 0;
1899 }
1900 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001901 } else if (stateChanged) {
1902 // Screen on/off didn't change, but lights may have.
1903 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001905
1906 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1907
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001908 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001911
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001912 private void updateNativePowerStateLocked() {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001913 if (!mHeadless) {
1914 nativeSetPowerState(
1915 (mPowerState & SCREEN_ON_BIT) != 0,
1916 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1917 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001919
Mike Lockwood435eb642009-12-03 08:40:18 -05001920 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001922 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001924 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1925 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001927 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001929 mScreenOffReason = reason;
1930 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 return err;
1933 }
1934
1935 private boolean batteryIsLow() {
1936 return (!mIsPowered &&
1937 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1938 }
1939
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001940 private boolean shouldDeferScreenOnLocked() {
1941 if (mPreparingForScreenOn) {
1942 // Currently waiting for confirmation from the policy that it
1943 // is okay to turn on the screen. Don't allow the screen to go
1944 // on until that is done.
1945 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1946 "updateLights: delaying screen on due to mPreparingForScreenOn");
1947 return true;
1948 } else {
1949 // If there is a screen-on command in the notification queue, we
1950 // can't turn the screen on until it has been processed (and we
1951 // have set mPreparingForScreenOn) or it has been dropped.
1952 for (int i=0; i<mBroadcastQueue.length; i++) {
1953 if (mBroadcastQueue[i] == 1) {
1954 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1955 "updateLights: delaying screen on due to notification queue");
1956 return true;
1957 }
1958 }
1959 }
1960 return false;
1961 }
1962
The Android Open Source Project10592532009-03-18 17:39:46 -07001963 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001964 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001965
1966 // If the screen is not currently on, we will want to delay actually
1967 // turning the lights on if we are still getting the UI put up.
Jim Miller92e66dd2012-02-21 18:57:12 -08001968 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001969 // Don't turn screen on until we know we are really ready to.
1970 // This is to avoid letting the screen go on before things like the
1971 // lock screen have been displayed.
Jim Miller92e66dd2012-02-21 18:57:12 -08001972 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001973 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1974 }
1975 }
1976
Joe Onorato60607a902010-10-23 14:49:30 -07001977 if ((newState & SCREEN_ON_BIT) != 0) {
1978 // Only turn on the buttons or keyboard if the screen is also on.
1979 // We should never see the buttons on but not the screen.
1980 newState = applyButtonState(newState);
1981 newState = applyKeyboardState(newState);
1982 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001983 final int realDifference = (newState ^ oldState);
1984 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001986 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 int offMask = 0;
1990 int dimMask = 0;
1991 int onMask = 0;
1992
1993 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001996 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1997 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001999 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
2001 }
2002
2003 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002004 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
2005 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002007 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009 }
2010
2011 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002012 int nominalCurrentValue = -1;
2013 // If there was an actual difference in the light state, then
2014 // figure out the "ideal" current value based on the previous
2015 // state. Otherwise, this is a change due to the brightness
2016 // override, so we want to animate from whatever the current
2017 // value is.
2018 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
2019 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
2020 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
2021 nominalCurrentValue = preferredBrightness;
2022 break;
2023 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002024 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002025 break;
2026 case 0:
2027 nominalCurrentValue = Power.BRIGHTNESS_OFF;
2028 break;
2029 case SCREEN_BRIGHT_BIT:
2030 default:
2031 // not possible
Jim Miller92e66dd2012-02-21 18:57:12 -08002032 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness();
Joe Onoratob08a1af2010-10-11 19:28:58 -07002033 break;
Joe Onorato128e7292009-03-24 18:41:31 -07002034 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002035 }
2036 int brightness = preferredBrightness;
2037 int steps = ANIM_STEPS;
2038 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
2039 // dim or turn off backlight, depending on if the screen is on
2040 // the scale is because the brightness ramp isn't linear and this biases
2041 // it so the later parts take longer.
2042 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002043 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002044 if (ratio > 1.0f) ratio = 1.0f;
2045 if ((newState & SCREEN_ON_BIT) == 0) {
2046 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2047 // was bright
2048 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002050 // was dim
2051 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002053 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002055 if ((oldState & SCREEN_ON_BIT) != 0) {
2056 // was bright
2057 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2058 } else {
2059 // was dim
2060 steps = (int)(ANIM_STEPS*ratio);
2061 }
2062 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2063 // If the "stay on while plugged in" option is
2064 // turned on, then the screen will often not
2065 // automatically turn off while plugged in. To
2066 // still have a sense of when it is inactive, we
2067 // will then count going dim as turning off.
2068 mScreenOffTime = SystemClock.elapsedRealtime();
2069 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002070 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002073 long identity = Binder.clearCallingIdentity();
2074 try {
2075 mBatteryStats.noteScreenBrightness(brightness);
2076 } catch (RemoteException e) {
2077 // Nothing interesting to do.
2078 } finally {
2079 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002081 if (!mSkippedScreenOn) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002082 int dt = steps * NOMINAL_FRAME_TIME_MS;
2083 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002084 if (DEBUG_SCREEN_ON) {
2085 RuntimeException e = new RuntimeException("here");
2086 e.fillInStackTrace();
2087 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2088 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002091
Joe Onorato60607a902010-10-23 14:49:30 -07002092 if (mSpew) {
2093 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2094 + " dimMask=0x" + Integer.toHexString(dimMask)
2095 + " onMask=0x" + Integer.toHexString(onMask)
2096 + " difference=0x" + Integer.toHexString(difference)
2097 + " realDifference=0x" + Integer.toHexString(realDifference)
2098 + " forceState=0x" + Integer.toHexString(forceState)
2099 );
2100 }
2101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002103 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002104 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002107 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 if ((newState & BATTERY_LOW_BIT) != 0 &&
2109 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2110 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2111 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002112 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002113 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115 if (onMask != 0) {
2116 int brightness = getPreferredBrightness();
2117 if ((newState & BATTERY_LOW_BIT) != 0 &&
2118 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2119 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2120 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002121 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002122 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125
Jim Miller92e66dd2012-02-21 18:57:12 -08002126 /**
2127 * Note: by design this class does not hold mLocks while calling native methods.
2128 * Nor should it. Ever.
2129 */
2130 class ScreenBrightnessAnimator extends HandlerThread {
2131 static final int ANIMATE_LIGHTS = 10;
Jim Miller46f31c32012-03-01 14:36:07 -08002132 static final int ANIMATE_POWER_OFF = 11;
Jim Miller92e66dd2012-02-21 18:57:12 -08002133 volatile int startValue;
2134 volatile int endValue;
2135 volatile int currentValue;
2136 private int currentMask;
2137 private int duration;
2138 private long startTimeMillis;
2139 private final String prefix;
2140
2141 public ScreenBrightnessAnimator(String name, int priority) {
2142 super(name, priority);
2143 prefix = name;
2144 }
2145
2146 @Override
2147 protected void onLooperPrepared() {
2148 mScreenBrightnessHandler = new Handler() {
2149 public void handleMessage(Message msg) {
2150 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation
Mike Lockwood3a322132009-11-24 00:30:52 -05002151 ? LightsService.BRIGHTNESS_MODE_SENSOR
2152 : LightsService.BRIGHTNESS_MODE_USER);
Jim Miller92e66dd2012-02-21 18:57:12 -08002153 if (msg.what == ANIMATE_LIGHTS) {
2154 final int mask = msg.arg1;
2155 int value = msg.arg2;
2156 long tStart = SystemClock.uptimeMillis();
2157 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
2158 if (mDebugLightAnimation) Log.v(TAG, "Set brightness: " + value);
2159 mLcdLight.setBrightness(value, brightnessMode);
2160 }
2161 long elapsed = SystemClock.uptimeMillis() - tStart;
2162 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
2163 mButtonLight.setBrightness(value);
2164 }
2165 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
2166 mKeyboardLight.setBrightness(value);
2167 }
2168
2169 if (elapsed > 100) {
2170 Log.e(TAG, "Excessive delay setting brightness: " + elapsed
2171 + "ms, mask=" + mask);
2172 }
2173
2174 // Throttle brightness updates to frame refresh rate
2175 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 0;
2176 synchronized(this) {
2177 currentValue = value;
2178 }
2179 animateInternal(mask, false, delay);
Jim Miller46f31c32012-03-01 14:36:07 -08002180 } else if (msg.what == ANIMATE_POWER_OFF) {
2181 int mode = msg.arg1;
2182 nativeStartSurfaceFlingerAnimation(mode);
Jim Miller92e66dd2012-02-21 18:57:12 -08002183 }
2184 }
2185 };
2186 synchronized (this) {
2187 mInitComplete = true;
2188 notifyAll();
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002189 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002190 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002191
2192 private void animateInternal(int mask, boolean turningOff, int delay) {
2193 synchronized (this) {
2194 if (currentValue != endValue) {
2195 final long now = SystemClock.elapsedRealtime();
2196 final int elapsed = (int) (now - startTimeMillis);
2197 int newValue;
2198 if (elapsed < duration) {
2199 int delta = endValue - startValue;
2200 newValue = startValue + delta * elapsed / duration;
2201 newValue = Math.max(Power.BRIGHTNESS_OFF, newValue);
2202 newValue = Math.min(Power.BRIGHTNESS_ON, newValue);
2203 } else {
2204 newValue = endValue;
2205 mInitialAnimation = false;
2206 }
2207
2208 if (mDebugLightAnimation) {
2209 Log.v(TAG, "Animating light: " + "start:" + startValue
2210 + ", end:" + endValue + ", elapsed:" + elapsed
2211 + ", duration:" + duration + ", current:" + currentValue
2212 + ", delay:" + delay);
2213 }
2214
Jim Miller46f31c32012-03-01 14:36:07 -08002215 if (turningOff && !mHeadless && !mAnimateScreenLights) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002216 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR
2217 ? 0 : mAnimationSetting;
2218 if (mDebugLightAnimation) Log.v(TAG, "Doing power-off anim, mode=" + mode);
Jim Miller46f31c32012-03-01 14:36:07 -08002219 mScreenBrightnessHandler.obtainMessage(ANIMATE_POWER_OFF, mode, 0)
2220 .sendToTarget();
Jim Miller92e66dd2012-02-21 18:57:12 -08002221 }
2222 Message msg = mScreenBrightnessHandler
2223 .obtainMessage(ANIMATE_LIGHTS, mask, newValue);
2224 mScreenBrightnessHandler.sendMessageDelayed(msg, delay);
2225 }
2226 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002227 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002228
2229 public void dump(PrintWriter pw, String string) {
2230 pw.println(prefix + "animating: " + "start:" + startValue + ", end:" + endValue
2231 + ", duration:" + duration + ", current:" + currentValue);
2232 }
2233
2234 public void animateTo(int target, int mask, int animationDuration) {
2235 synchronized(this) {
2236 startValue = currentValue;
2237 endValue = target;
2238 currentMask = mask;
2239 duration = (int) (mWindowScaleAnimation * animationDuration);
2240 startTimeMillis = SystemClock.elapsedRealtime();
2241 mInitialAnimation = currentValue == 0 && target > 0;
2242
2243 if (mDebugLightAnimation) {
2244 Log.v(TAG, "animateTo(target=" + target + ", mask=" + mask
2245 + ", duration=" + animationDuration +")"
2246 + ", currentValue=" + currentValue
2247 + ", startTime=" + startTimeMillis);
2248 }
2249
2250 if (target != currentValue) {
Jim Miller18651802012-03-07 14:19:56 -08002251 final boolean doScreenAnim = (mask & (SCREEN_BRIGHT_BIT | SCREEN_ON_BIT)) != 0;
Jim Miller92e66dd2012-02-21 18:57:12 -08002252 final boolean turningOff = endValue == Power.BRIGHTNESS_OFF;
Jim Miller18651802012-03-07 14:19:56 -08002253 if (turningOff && doScreenAnim) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002254 // Cancel all pending animations since we're turning off
2255 mScreenBrightnessHandler.removeCallbacksAndMessages(null);
2256 screenOffFinishedAnimatingLocked(mScreenOffReason);
2257 duration = 200; // TODO: how long should this be?
2258 }
Jim Miller18651802012-03-07 14:19:56 -08002259 if (doScreenAnim) {
2260 animateInternal(mask, turningOff, 0);
2261 }
2262 // TODO: Handle keyboard light animation when we have devices that support it
Jim Miller92e66dd2012-02-21 18:57:12 -08002263 }
2264 }
2265 }
2266
2267 public int getCurrentBrightness() {
2268 synchronized (this) {
2269 return currentValue;
2270 }
2271 }
2272
2273 public boolean isAnimating() {
2274 synchronized (this) {
2275 return currentValue != endValue;
2276 }
2277 }
2278
2279 public void cancelAnimation() {
2280 animateTo(endValue, currentMask, 0);
The Android Open Source Project10592532009-03-18 17:39:46 -07002281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283
Jim Miller92e66dd2012-02-21 18:57:12 -08002284 private void setLightBrightness(int mask, int value) {
2285 mScreenBrightnessAnimator.animateTo(value, mask, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 private int getPreferredBrightness() {
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002289 if (mScreenBrightnessOverride >= 0) {
2290 return mScreenBrightnessOverride;
2291 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
2292 && mAutoBrightessEnabled) {
2293 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002295 final int brightness = mScreenBrightnessSetting;
2296 // Don't let applications turn the screen all the way off
2297 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 }
2299
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002300 private int applyButtonState(int state) {
2301 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002302 if ((state & BATTERY_LOW_BIT) != 0) {
2303 // do not override brightness if the battery is low
2304 return state;
2305 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002306 if (mButtonBrightnessOverride >= 0) {
2307 brightness = mButtonBrightnessOverride;
2308 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2309 brightness = mLightSensorButtonBrightness;
2310 }
2311 if (brightness > 0) {
2312 return state | BUTTON_BRIGHT_BIT;
2313 } else if (brightness == 0) {
2314 return state & ~BUTTON_BRIGHT_BIT;
2315 } else {
2316 return state;
2317 }
2318 }
2319
2320 private int applyKeyboardState(int state) {
2321 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002322 if ((state & BATTERY_LOW_BIT) != 0) {
2323 // do not override brightness if the battery is low
2324 return state;
2325 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002326 if (!mKeyboardVisible) {
2327 brightness = 0;
2328 } else if (mButtonBrightnessOverride >= 0) {
2329 brightness = mButtonBrightnessOverride;
2330 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2331 brightness = mLightSensorKeyboardBrightness;
2332 }
2333 if (brightness > 0) {
2334 return state | KEYBOARD_BRIGHT_BIT;
2335 } else if (brightness == 0) {
2336 return state & ~KEYBOARD_BRIGHT_BIT;
2337 } else {
2338 return state;
2339 }
2340 }
2341
Charles Mendis322591c2009-10-29 11:06:59 -07002342 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 synchronized (mLocks) {
2344 return (mPowerState & SCREEN_ON_BIT) != 0;
2345 }
2346 }
2347
Charles Mendis322591c2009-10-29 11:06:59 -07002348 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 synchronized (mLocks) {
2350 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2351 }
2352 }
2353
Mike Lockwood497087e32009-11-08 18:33:03 -05002354 private boolean isScreenTurningOffLocked() {
Jim Miller92e66dd2012-02-21 18:57:12 -08002355 return (mScreenBrightnessAnimator.isAnimating()
2356 && mScreenBrightnessAnimator.endValue == Power.BRIGHTNESS_OFF);
Mike Lockwood497087e32009-11-08 18:33:03 -05002357 }
2358
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002359 private boolean shouldLog(long time) {
2360 synchronized (mLocks) {
2361 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2362 mWarningSpewThrottleTime = time;
2363 mWarningSpewThrottleCount = 0;
2364 return true;
2365 } else if (mWarningSpewThrottleCount < 30) {
2366 mWarningSpewThrottleCount++;
2367 return true;
2368 } else {
2369 return false;
2370 }
2371 }
2372 }
2373
Mike Lockwood200b30b2009-09-20 00:23:59 -04002374 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002375 if (isScreenTurningOffLocked()) {
2376 // cancel animation so userActivity will succeed
Jim Miller92e66dd2012-02-21 18:57:12 -08002377 mScreenBrightnessAnimator.cancelAnimation();
Mike Lockwoode090281422009-11-14 21:02:56 -05002378 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002379 boolean savedActivityAllowed = mUserActivityAllowed;
2380 mUserActivityAllowed = true;
2381 userActivity(SystemClock.uptimeMillis(), false);
2382 mUserActivityAllowed = savedActivityAllowed;
2383 }
2384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002387 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 }
2389
2390 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002391 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2392 != PackageManager.PERMISSION_GRANTED) {
2393 if (shouldLog(time)) {
2394 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2395 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2396 }
2397 return;
2398 }
2399
Joe Onorato7999bff2010-07-24 11:50:05 -04002400 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 }
2402
2403 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002404 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
2406
2407 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002408 userActivity(time, -1, noChangeLights, eventType, force);
2409 }
2410
2411 /*
2412 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2413 * on with user activity. Don't use this function.
2414 */
2415 public void clearUserActivityTimeout(long now, long timeout) {
2416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2417 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2418 userActivity(now, timeout, false, OTHER_EVENT, false);
2419 }
2420
2421 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2422 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423
Joe Onorato1a542c72010-11-08 09:48:20 -08002424 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002425 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002426 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002427 }
2428 return;
2429 }
2430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 synchronized (mLocks) {
2432 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002433 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 + " mUserActivityAllowed=" + mUserActivityAllowed
2435 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002436 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2437 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002438 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002439 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 }
Mike Lockwood05067122009-10-27 23:07:25 -04002441 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002442 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002443 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002444 return;
2445 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002446 // Disable proximity sensor if if user presses power key while we are in the
2447 // "waiting for proximity sensor to go negative" state.
2448 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2449 mProximitySensorActive = false;
2450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 if (mLastEventTime <= time || force) {
2452 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002453 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002454 // Only turn on button backlights if a button was pressed
2455 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002456 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2458 } else {
2459 // don't clear button/keyboard backlights when the screen is touched.
2460 mUserState |= SCREEN_BRIGHT;
2461 }
2462
Dianne Hackborn617f8772009-03-31 15:04:46 -07002463 int uid = Binder.getCallingUid();
2464 long ident = Binder.clearCallingIdentity();
2465 try {
2466 mBatteryStats.noteUserActivity(uid, eventType);
2467 } catch (RemoteException e) {
2468 // Ignore
2469 } finally {
2470 Binder.restoreCallingIdentity(ident);
2471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002472
Michael Chane96440f2009-05-06 10:27:36 -07002473 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002474 setPowerState(mUserState | mWakeLockState, noChangeLights,
2475 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002476 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
2478 }
2479 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002480
2481 if (mPolicy != null) {
2482 mPolicy.userActivity();
2483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
2485
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002486 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2487 try {
2488 int i;
2489 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2490 if (sensorValue < mAutoBrightnessLevels[i]) {
2491 break;
2492 }
2493 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002494 // This is the range of brightness values that we can use.
2495 final int minval = values[0];
2496 final int maxval = values[mAutoBrightnessLevels.length];
2497 // This is the range we will be scaling. We put some padding
2498 // at the low and high end to give the adjustment a little better
2499 // impact on the actual observed value.
2500 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION;
2501 // This is the desired brightness value from 0.0 to 1.0.
2502 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range);
2503 // Apply a scaling to the value based on the adjustment.
2504 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) {
2505 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting);
2506 if (adj <= .00001) {
2507 valf = 1;
2508 } else {
2509 valf /= adj;
2510 }
2511 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) {
2512 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting);
2513 valf *= adj;
2514 }
2515 // Apply an additional offset to the value based on the adjustment.
2516 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE;
2517 // Convert the 0.0-1.0 value back to a brightness integer.
2518 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2);
2519 if (val < minval) val = minval;
2520 else if (val > maxval) val = maxval;
2521 return val;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002522 } catch (Exception e) {
2523 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002524 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002525 return 255;
2526 }
2527 }
2528
Mike Lockwood20f87d72009-11-05 16:08:51 -05002529 private Runnable mProximityTask = new Runnable() {
2530 public void run() {
2531 synchronized (mLocks) {
2532 if (mProximityPendingValue != -1) {
2533 proximityChangedLocked(mProximityPendingValue == 1);
2534 mProximityPendingValue = -1;
2535 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002536 if (mProximityPartialLock.isHeld()) {
2537 mProximityPartialLock.release();
2538 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002539 }
2540 }
2541 };
2542
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002543 private Runnable mAutoBrightnessTask = new Runnable() {
2544 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002545 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002546 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2547 int value = (int)mLightSensorPendingValue;
2548 mLightSensorPendingDecrease = false;
2549 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002550 lightSensorChangedLocked(value, false);
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002551 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002552 }
2553 }
2554 };
2555
Jim Miller92e66dd2012-02-21 18:57:12 -08002556 private boolean mInitialAnimation; // used to prevent lightsensor changes while turning on
2557
Mike Lockwoodb2865412010-02-02 22:40:33 -05002558 private void dockStateChanged(int state) {
2559 synchronized (mLocks) {
2560 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2561 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002562 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002563 mHighestLightSensorValue = -1;
2564 }
2565 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2566 // force lights recalculation
2567 int value = (int)mLightSensorValue;
2568 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002569 lightSensorChangedLocked(value, false);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002570 }
2571 }
2572 }
2573
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002574 private void lightSensorChangedLocked(int value, boolean immediate) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002575 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002576 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002577 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002578
Joe Onorato06eb33a2010-10-25 14:09:21 -07002579 // Don't do anything if the screen is off.
2580 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2581 if (mDebugLightSensor) {
2582 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2583 }
2584 return;
2585 }
2586
Mike Lockwoodb2865412010-02-02 22:40:33 -05002587 // do not allow light sensor value to decrease
2588 if (mHighestLightSensorValue < value) {
2589 mHighestLightSensorValue = value;
2590 }
2591
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002592 if (mLightSensorValue != value) {
2593 mLightSensorValue = value;
2594 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002595 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2596 // we only do this if we are undocked, since lighting should be stable when
2597 // stationary in a dock.
2598 int lcdValue = getAutoBrightnessValue(
2599 (mIsDocked ? value : mHighestLightSensorValue),
2600 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002601 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002602 int keyboardValue;
2603 if (mKeyboardVisible) {
2604 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2605 } else {
2606 keyboardValue = 0;
2607 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002608 mLightSensorScreenBrightness = lcdValue;
2609 mLightSensorButtonBrightness = buttonValue;
2610 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002611
2612 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002613 Slog.d(TAG, "lcdValue " + lcdValue);
2614 Slog.d(TAG, "buttonValue " + buttonValue);
2615 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002616 }
2617
Mike Lockwood4984e732009-11-01 08:16:33 -05002618 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002619 if (!mSkippedScreenOn && !mInitialAnimation) {
2620 int steps = immediate ? IMMEDIATE_ANIM_STEPS : AUTOBRIGHTNESS_ANIM_STEPS;
2621 mScreenBrightnessAnimator.cancelAnimation();
2622 mScreenBrightnessAnimator.animateTo(lcdValue,
2623 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002624 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002625 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002626 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002627 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002628 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002629 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002630 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002631 }
2632 }
2633 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002634 }
2635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 /**
2637 * The user requested that we go to sleep (probably with the power button).
2638 * This overrides all wake locks that are held.
2639 */
2640 public void goToSleep(long time)
2641 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002642 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2643 }
2644
2645 /**
2646 * The user requested that we go to sleep (probably with the power button).
2647 * This overrides all wake locks that are held.
2648 */
2649 public void goToSleepWithReason(long time, int reason)
2650 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2652 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002653 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
2655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002658 * Reboot the device immediately, passing 'reason' (may be null)
2659 * to the underlying __reboot system call. Should not return.
2660 */
2661 public void reboot(String reason)
2662 {
2663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002664
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002665 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2666 throw new IllegalStateException("Too early to call reboot()");
2667 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002668
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002669 final String finalReason = reason;
2670 Runnable runnable = new Runnable() {
2671 public void run() {
2672 synchronized (this) {
2673 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002674 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002675
San Mehat1e512792010-01-07 10:40:29 -08002676 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002677 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002678 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002679 mHandler.post(runnable);
2680
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002681 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002682 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002683 while (true) {
2684 try {
2685 runnable.wait();
2686 } catch (InterruptedException e) {
2687 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002688 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002689 }
2690 }
2691
Dan Egnor60d87622009-12-16 16:32:58 -08002692 /**
2693 * Crash the runtime (causing a complete restart of the Android framework).
2694 * Requires REBOOT permission. Mostly for testing. Should not return.
2695 */
2696 public void crash(final String message)
2697 {
2698 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2699 Thread t = new Thread("PowerManagerService.crash()") {
2700 public void run() { throw new RuntimeException(message); }
2701 };
2702 try {
2703 t.start();
2704 t.join();
2705 } catch (InterruptedException e) {
2706 Log.wtf(TAG, e);
2707 }
2708 }
2709
Mike Lockwood435eb642009-12-03 08:40:18 -05002710 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711
2712 if (mLastEventTime <= time) {
2713 mLastEventTime = time;
2714 // cancel all of the wake locks
2715 mWakeLockState = SCREEN_OFF;
2716 int N = mLocks.size();
2717 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002718 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 for (int i=0; i<N; i++) {
2720 WakeLock wl = mLocks.get(i);
2721 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002722 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2723 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2724 proxLock = true;
2725 } else {
2726 mLocks.get(i).activated = false;
2727 numCleared++;
2728 }
2729 }
2730 }
2731 if (!proxLock) {
2732 mProxIgnoredBecauseScreenTurnedOff = true;
2733 if (mDebugProximitySensor) {
2734 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 }
2736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002737 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002738 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002740 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 cancelTimerLocked();
2742 }
2743 }
2744
2745 public long timeSinceScreenOn() {
2746 synchronized (mLocks) {
2747 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2748 return 0;
2749 }
2750 return SystemClock.elapsedRealtime() - mScreenOffTime;
2751 }
2752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002755 synchronized (mLocks) {
2756 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002757 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002758 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002759 if (mKeyboardVisible != visible) {
2760 mKeyboardVisible = visible;
2761 // don't signal user activity if the screen is off; other code
2762 // will take care of turning on due to a true change to the lid
2763 // switch and synchronized with the lock screen.
2764 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002765 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002766 // force recompute of backlight values
2767 if (mLightSensorValue >= 0) {
2768 int value = (int)mLightSensorValue;
2769 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002770 lightSensorChangedLocked(value, false);
Mike Lockwooddf024922009-10-29 21:29:15 -04002771 }
2772 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002773 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2774 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002775 }
2776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 }
2778
2779 /**
2780 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002781 * When disabling user activity we also reset user power state so the keyguard can reset its
2782 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 */
2784 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002785 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002786 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 synchronized (mLocks) {
2789 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002790 if (!enabled) {
2791 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2792 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
2795 }
2796
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002797 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002798 synchronized (mLocks) {
2799 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2800 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2801 mAutoBrightessEnabled = enabled;
2802 // This will get us a new value
2803 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002804 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002805 }
2806 }
2807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 /** Sets the screen off timeouts:
2809 * mKeylightDelay
2810 * mDimDelay
2811 * mScreenOffDelay
2812 * */
2813 private void setScreenOffTimeoutsLocked() {
2814 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002815 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mDimDelay = -1;
2817 mScreenOffDelay = 0;
2818 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2819 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2820 mDimDelay = -1;
2821 mScreenOffDelay = 0;
2822 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002823 int totalDelay = mScreenOffTimeoutSetting;
2824 if (totalDelay > mMaximumScreenOffTimeout) {
2825 totalDelay = mMaximumScreenOffTimeout;
2826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2828 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002829 // negative number means stay on as long as possible.
2830 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 } else if (mKeylightDelay < totalDelay) {
2832 // subtract the time that the keylight delay. This will give us the
2833 // remainder of the time that we need to sleep to get the accurate
2834 // screen off timeout.
2835 mScreenOffDelay = totalDelay - mKeylightDelay;
2836 } else {
2837 mScreenOffDelay = 0;
2838 }
2839 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2840 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2841 mScreenOffDelay = LONG_DIM_TIME;
2842 } else {
2843 mDimDelay = -1;
2844 }
2845 }
2846 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002847 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2849 + " mDimScreen=" + mDimScreen);
2850 }
2851 }
2852
2853 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002854 * Refreshes cached secure settings. Called once on startup, and
2855 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 */
Doug Zongker43866e02010-01-07 12:09:54 -08002857 private void updateSettingsValues() {
2858 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002860 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002862 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 }
2864
2865 private class LockList extends ArrayList<WakeLock>
2866 {
2867 void addLock(WakeLock wl)
2868 {
2869 int index = getIndex(wl.binder);
2870 if (index < 0) {
2871 this.add(wl);
2872 }
2873 }
2874
2875 WakeLock removeLock(IBinder binder)
2876 {
2877 int index = getIndex(binder);
2878 if (index >= 0) {
2879 return this.remove(index);
2880 } else {
2881 return null;
2882 }
2883 }
2884
2885 int getIndex(IBinder binder)
2886 {
2887 int N = this.size();
2888 for (int i=0; i<N; i++) {
2889 if (this.get(i).binder == binder) {
2890 return i;
2891 }
2892 }
2893 return -1;
2894 }
2895
2896 int gatherState()
2897 {
2898 int result = 0;
2899 int N = this.size();
2900 for (int i=0; i<N; i++) {
2901 WakeLock wl = this.get(i);
2902 if (wl.activated) {
2903 if (isScreenLock(wl.flags)) {
2904 result |= wl.minState;
2905 }
2906 }
2907 }
2908 return result;
2909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002910
Michael Chane96440f2009-05-06 10:27:36 -07002911 int reactivateScreenLocksLocked()
2912 {
2913 int result = 0;
2914 int N = this.size();
2915 for (int i=0; i<N; i++) {
2916 WakeLock wl = this.get(i);
2917 if (isScreenLock(wl.flags)) {
2918 wl.activated = true;
2919 result |= wl.minState;
2920 }
2921 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002922 if (mDebugProximitySensor) {
2923 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2924 + mProxIgnoredBecauseScreenTurnedOff);
2925 }
2926 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002927 return result;
2928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002931 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 synchronized (mLocks) {
2933 mPolicy = p;
2934 mLocks.notifyAll();
2935 }
2936 }
2937
2938 WindowManagerPolicy getPolicyLocked() {
2939 while (mPolicy == null || !mDoneBooting) {
2940 try {
2941 mLocks.wait();
2942 } catch (InterruptedException e) {
2943 // Ignore
2944 }
2945 }
2946 return mPolicy;
2947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 void systemReady() {
Jeff Brown25157e42012-04-16 12:13:05 -07002950 mSensorManager = new SystemSensorManager(mHandlerThread.getLooper());
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002951 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2952 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002953 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002954 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002955 }
2956
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002957 // wait until sensors are enabled before turning on screen.
2958 // some devices will not activate the light sensor properly on boot
2959 // unless we do this.
2960 if (mUseSoftwareAutoBrightness) {
2961 // turn the screen on
2962 setPowerState(SCREEN_BRIGHT);
2963 } else {
2964 // turn everything on
2965 setPowerState(ALL_BRIGHT);
2966 }
2967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002969 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002971
Joe Onoratod28f7532010-11-06 12:56:53 -07002972 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2973
Dianne Hackborn617f8772009-03-31 15:04:46 -07002974 long identity = Binder.clearCallingIdentity();
2975 try {
2976 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2977 mBatteryStats.noteScreenOn();
2978 } catch (RemoteException e) {
2979 // Nothing interesting to do.
2980 } finally {
2981 Binder.restoreCallingIdentity(identity);
2982 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002983 }
2984 }
2985
2986 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002987 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002988 synchronized (mLocks) {
2989 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2991 updateWakeLockLocked();
2992 mLocks.notifyAll();
2993 }
2994 }
2995
Joe Onoratob08a1af2010-10-11 19:28:58 -07002996 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 public void monitor() {
2998 synchronized (mLocks) { }
2999 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003000
3001 public int getSupportedWakeLockFlags() {
3002 int result = PowerManager.PARTIAL_WAKE_LOCK
3003 | PowerManager.FULL_WAKE_LOCK
3004 | PowerManager.SCREEN_DIM_WAKE_LOCK;
3005
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003006 if (mProximitySensor != null) {
3007 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
3008 }
3009
3010 return result;
3011 }
3012
Mike Lockwood237a2992009-09-15 14:42:16 -04003013 public void setBacklightBrightness(int brightness) {
3014 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3015 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07003016 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04003017 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07003018 mLcdLight.setBrightness(brightness);
3019 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
3020 mButtonLight.setBrightness(brightness);
3021 long identity = Binder.clearCallingIdentity();
3022 try {
3023 mBatteryStats.noteScreenBrightness(brightness);
3024 } catch (RemoteException e) {
3025 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
3026 } finally {
3027 Binder.restoreCallingIdentity(identity);
3028 }
Jim Miller92e66dd2012-02-21 18:57:12 -08003029 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003030 }
3031 }
3032
3033 public void setAutoBrightnessAdjustment(float adj) {
3034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3035 synchronized (mLocks) {
3036 mLightSensorAdjustSetting = adj;
3037 if (mSensorManager != null && mLightSensorEnabled) {
3038 // clear calling identity so sensor manager battery stats are accurate
3039 long identity = Binder.clearCallingIdentity();
3040 try {
3041 // force recompute of backlight values
3042 if (mLightSensorValue >= 0) {
3043 int value = (int)mLightSensorValue;
3044 mLightSensorValue = -1;
3045 handleLightSensorValue(value, true);
3046 }
3047 } finally {
3048 Binder.restoreCallingIdentity(identity);
3049 }
Joe Onorato3d3db602010-10-18 16:08:16 -04003050 }
Mike Lockwood237a2992009-09-15 14:42:16 -04003051 }
3052 }
3053
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003054 public void setAttentionLight(boolean on, int color) {
3055 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05003056 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003057 }
3058
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003059 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003060 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003061 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003062 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003063 if (!mProximitySensorEnabled) {
3064 // clear calling identity so sensor manager battery stats are accurate
3065 long identity = Binder.clearCallingIdentity();
3066 try {
3067 mSensorManager.registerListener(mProximityListener, mProximitySensor,
3068 SensorManager.SENSOR_DELAY_NORMAL);
3069 mProximitySensorEnabled = true;
3070 } finally {
3071 Binder.restoreCallingIdentity(identity);
3072 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003073 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003074 }
3075
3076 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003077 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003078 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003079 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003080 if (mProximitySensorEnabled) {
3081 // clear calling identity so sensor manager battery stats are accurate
3082 long identity = Binder.clearCallingIdentity();
3083 try {
3084 mSensorManager.unregisterListener(mProximityListener);
3085 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003086 if (mProximityPartialLock.isHeld()) {
3087 mProximityPartialLock.release();
3088 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003089 mProximitySensorEnabled = false;
3090 } finally {
3091 Binder.restoreCallingIdentity(identity);
3092 }
3093 if (mProximitySensorActive) {
3094 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003095 if (mDebugProximitySensor) {
3096 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
3097 + mProxIgnoredBecauseScreenTurnedOff);
3098 }
3099 if (!mProxIgnoredBecauseScreenTurnedOff) {
3100 forceUserActivityLocked();
3101 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003102 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003103 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003104 }
3105
Mike Lockwood20f87d72009-11-05 16:08:51 -05003106 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003107 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003108 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003109 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003110 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003111 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003112 return;
3113 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003114 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003115 if (mDebugProximitySensor) {
3116 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3117 + mProxIgnoredBecauseScreenTurnedOff);
3118 }
3119 if (!mProxIgnoredBecauseScreenTurnedOff) {
3120 goToSleepLocked(SystemClock.uptimeMillis(),
3121 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3122 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003123 mProximitySensorActive = true;
3124 } else {
3125 // proximity sensor negative events trigger as user activity.
3126 // temporarily set mUserActivityAllowed to true so this will work
3127 // even when the keyguard is on.
3128 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003129 if (mDebugProximitySensor) {
3130 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3131 + mProxIgnoredBecauseScreenTurnedOff);
3132 }
3133 if (!mProxIgnoredBecauseScreenTurnedOff) {
3134 forceUserActivityLocked();
3135 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003136
3137 if (mProximityWakeLockCount == 0) {
3138 // disable sensor if we have no listeners left after proximity negative
3139 disableProximityLockLocked();
3140 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003141 }
3142 }
3143
Joe Onoratod28f7532010-11-06 12:56:53 -07003144 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003145 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003146 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3147 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3148 }
3149 if (!mAutoBrightessEnabled) {
3150 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003151 }
3152 if (mSensorManager != null && mLightSensorEnabled != enable) {
3153 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003154 // clear calling identity so sensor manager battery stats are accurate
3155 long identity = Binder.clearCallingIdentity();
3156 try {
3157 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003158 // reset our highest value when reenabling
3159 mHighestLightSensorValue = -1;
3160 // force recompute of backlight values
3161 if (mLightSensorValue >= 0) {
3162 int value = (int)mLightSensorValue;
3163 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003164 handleLightSensorValue(value, true);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003165 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003166 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003167 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003168 } else {
3169 mSensorManager.unregisterListener(mLightListener);
3170 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003171 mLightSensorPendingDecrease = false;
3172 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003173 }
3174 } finally {
3175 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003176 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003177 }
3178 }
3179
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003180 SensorEventListener mProximityListener = new SensorEventListener() {
3181 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003182 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003183 synchronized (mLocks) {
3184 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003185 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3186 mLastProximityEventTime = milliseconds;
3187 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003188 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003189
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003190 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003191 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3192 distance < mProximitySensor.getMaximumRange());
3193
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003194 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003195 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003196 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003197 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3198 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3199 mProximityPendingValue = (active ? 1 : 0);
3200 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003201 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003202 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003203 // process the value immediately
3204 mProximityPendingValue = -1;
3205 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003206 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003207
3208 // update mProximityPartialLock state
3209 boolean held = mProximityPartialLock.isHeld();
3210 if (!held && proximityTaskQueued) {
3211 // hold wakelock until mProximityTask runs
3212 mProximityPartialLock.acquire();
3213 } else if (held && !proximityTaskQueued) {
3214 mProximityPartialLock.release();
3215 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003216 }
3217 }
3218
3219 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3220 // ignore
3221 }
3222 };
3223
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003224 private void handleLightSensorValue(int value, boolean immediate) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003225 long milliseconds = SystemClock.elapsedRealtime();
3226 if (mLightSensorValue == -1 ||
3227 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3228 // process the value immediately if screen has just turned on
3229 mHandler.removeCallbacks(mAutoBrightnessTask);
3230 mLightSensorPendingDecrease = false;
3231 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003232 lightSensorChangedLocked(value, immediate);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003233 } else {
3234 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3235 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3236 (value == mLightSensorValue) ||
3237 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3238 // delay processing to debounce the sensor
3239 mHandler.removeCallbacks(mAutoBrightnessTask);
3240 mLightSensorPendingDecrease = (value < mLightSensorValue);
3241 mLightSensorPendingIncrease = (value > mLightSensorValue);
3242 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3243 mLightSensorPendingValue = value;
3244 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3245 }
3246 } else {
3247 mLightSensorPendingValue = value;
3248 }
3249 }
3250 }
3251
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003252 SensorEventListener mLightListener = new SensorEventListener() {
3253 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003254 if (mDebugLightSensor) {
3255 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3256 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003257 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003258 // ignore light sensor while screen is turning off
3259 if (isScreenTurningOffLocked()) {
3260 return;
3261 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003262 handleLightSensorValue((int)event.values[0], false);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003263 }
3264 }
3265
3266 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3267 // ignore
3268 }
3269 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270}