blob: 0f7580d575bedf53065c5ad8d08e2dd00e02514d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070040import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.BatteryStats;
42import android.os.Binder;
43import android.os.Handler;
44import android.os.HandlerThread;
45import android.os.IBinder;
46import android.os.IPowerManager;
47import android.os.LocalPowerManager;
Jim Miller92e66dd2012-02-21 18:57:12 -080048import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Power;
50import android.os.PowerManager;
51import android.os.Process;
52import android.os.RemoteException;
53import android.os.SystemClock;
Mike Lockwood3a74bd32011-08-12 13:55:22 -070054import android.os.SystemProperties;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
57import android.util.EventLog;
58import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080059import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.view.WindowManagerPolicy;
Jim Miller92e66dd2012-02-21 18:57:12 -080061import static android.view.WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import static android.provider.Settings.System.DIM_SCREEN;
63import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050064import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -080065import static android.provider.Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070066import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
68import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070069import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
70import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72import java.io.FileDescriptor;
73import java.io.PrintWriter;
74import java.util.ArrayList;
75import java.util.HashMap;
76import java.util.Observable;
77import java.util.Observer;
78
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080079public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040080 implements LocalPowerManager, Watchdog.Monitor {
Jim Miller92e66dd2012-02-21 18:57:12 -080081 private static final int NOMINAL_FRAME_TIME_MS = 1000/60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
83 private static final String TAG = "PowerManagerService";
84 static final String PARTIAL_NAME = "PowerManagerService";
85
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -070086 static final boolean DEBUG_SCREEN_ON = false;
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 private static final boolean LOG_PARTIAL_WL = false;
89
90 // Indicates whether touch-down cycles should be logged as part of the
91 // LOG_POWER_SCREEN_STATE log events
92 private static final boolean LOG_TOUCH_DOWNS = true;
93
94 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
95 | PowerManager.SCREEN_DIM_WAKE_LOCK
96 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070097 | PowerManager.FULL_WAKE_LOCK
98 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
100 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -0800101 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
103 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
104 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
105 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
106
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800107 // How long to wait to debounce light sensor changes in milliseconds
Mike Lockwood9b8136922009-11-06 15:53:59 -0500108 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700109
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800110 // light sensor events rate in microseconds
111 private static final int LIGHT_SENSOR_RATE = 1000000;
112
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800113 // Expansion of range of light values when applying scale from light
114 // sensor brightness setting, in the [0..255] brightness range.
115 private static final int LIGHT_SENSOR_RANGE_EXPANSION = 20;
116
117 // Scaling factor of the light sensor brightness setting when applying
118 // it to the final brightness.
119 private static final int LIGHT_SENSOR_OFFSET_SCALE = 8;
120
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800121 // For debouncing the proximity sensor in milliseconds
Mike Lockwood20f87d72009-11-05 16:08:51 -0500122 private static final int PROXIMITY_SENSOR_DELAY = 1000;
123
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400124 // trigger proximity if distance is less than 5 cm
125 private static final float PROXIMITY_THRESHOLD = 5.0f;
126
Doug Zongker43866e02010-01-07 12:09:54 -0800127 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
129
Amith Yamasani8b619832010-09-22 16:11:59 -0700130 // Default timeout for screen off, if not found in settings database = 15 seconds.
131 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
132
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800133 // Screen brightness should always have a value, but just in case...
134 private static final int DEFAULT_SCREEN_BRIGHTNESS = 192;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 // flags for setPowerState
Jim Miller92e66dd2012-02-21 18:57:12 -0800137 private static final int ALL_LIGHTS_OFF = 0x00000000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private static final int SCREEN_ON_BIT = 0x00000001;
139 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
140 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
141 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
142 private static final int BATTERY_LOW_BIT = 0x00000010;
143
144 // values for setPowerState
145
146 // SCREEN_OFF == everything off
147 private static final int SCREEN_OFF = 0x00000000;
148
149 // SCREEN_DIM == screen on, screen backlight dim
150 private static final int SCREEN_DIM = SCREEN_ON_BIT;
151
152 // SCREEN_BRIGHT == screen on, screen backlight bright
153 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
154
155 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
156 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
157
158 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
159 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
160
161 // used for noChangeLights in setPowerState()
162 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
163
Joe Onoratob08a1af2010-10-11 19:28:58 -0700164 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800165
Jim Miller92e66dd2012-02-21 18:57:12 -0800166 static final int ANIM_STEPS = 60; // nominal # of frames at 60Hz
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400167 // Slower animation for autobrightness changes
Jim Miller92e66dd2012-02-21 18:57:12 -0800168 static final int AUTOBRIGHTNESS_ANIM_STEPS = 2 * ANIM_STEPS;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800169 // Number of steps when performing a more immediate brightness change.
170 static final int IMMEDIATE_ANIM_STEPS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 // These magic numbers are the initial state of the LEDs at boot. Ideally
173 // we should read them from the driver, but our current hardware returns 0
174 // for the initial value. Oops!
175 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
176 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
177 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700180 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
182 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500183 private boolean mBootCompleted = false;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700184 private boolean mHeadless = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500186 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
187 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700188 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700189 private boolean mSkippedScreenOn = false;
190 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private int mPartialCount = 0;
192 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500193 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
194 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
195 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private int mUserState;
197 private boolean mKeyboardVisible = false;
198 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500199 private int mProximityWakeLockCount = 0;
200 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700201 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500202 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
203 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800204 private int mScreenOffTimeoutSetting;
205 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private int mKeylightDelay;
207 private int mDimDelay;
208 private int mScreenOffDelay;
209 private int mWakeLockState;
210 private long mLastEventTime = 0;
211 private long mScreenOffTime;
212 private volatile WindowManagerPolicy mPolicy;
213 private final LockList mLocks = new LockList();
214 private Intent mScreenOffIntent;
215 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500216 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500218 private LightsService.Light mLcdLight;
219 private LightsService.Light mButtonLight;
220 private LightsService.Light mKeyboardLight;
221 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private UnsynchronizedWakeLock mBroadcastWakeLock;
223 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
224 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
225 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500226 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700228 private Handler mScreenOffHandler;
Jim Miller92e66dd2012-02-21 18:57:12 -0800229 private Handler mScreenBrightnessHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500231 private final TimeoutTask mTimeoutTask = new TimeoutTask();
Jim Miller92e66dd2012-02-21 18:57:12 -0800232 private ScreenBrightnessAnimator mScreenBrightnessAnimator;
Joe Onorato128e7292009-03-24 18:41:31 -0700233 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private boolean mIsPowered = false;
235 private IActivityManager mActivityService;
236 private IBatteryStats mBatteryStats;
237 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700238 private SensorManager mSensorManager;
239 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400240 private Sensor mLightSensor;
241 private boolean mLightSensorEnabled;
242 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400243 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500244 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500245 private boolean mLightSensorPendingDecrease = false;
246 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700247 private float mLightSensorPendingValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800248 private float mLightSensorAdjustSetting = 0;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500249 private int mLightSensorScreenBrightness = -1;
250 private int mLightSensorButtonBrightness = -1;
251 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500253 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 private long mNextTimeout;
255 private volatile int mPokey = 0;
256 private volatile boolean mPokeAwakeOnSet = false;
257 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500258 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500259 // mLastScreenOnTime is the time the screen was last turned on
260 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 private boolean mPreventScreenOn;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800262 private int mScreenBrightnessSetting = DEFAULT_SCREEN_BRIGHTNESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500264 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400265 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400266 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700267 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700268 private int[] mAutoBrightnessLevels;
269 private int[] mLcdBacklightValues;
270 private int[] mButtonBacklightValues;
271 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500272 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700273 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700274 private int mWarningSpewThrottleCount;
275 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700276 private int mAnimationSetting = ANIM_SETTING_OFF;
Jim Miller92e66dd2012-02-21 18:57:12 -0800277 private float mWindowScaleAnimation;
Joe Onorato609695d2010-10-14 14:57:49 -0700278
279 // Must match with the ISurfaceComposer constants in C++.
280 private static final int ANIM_SETTING_ON = 0x01;
281 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282
283 // Used when logging number and duration of touch-down cycles
284 private long mTotalTouchDownTime;
285 private long mLastTouchDown;
286 private int mTouchCycles;
287
288 // could be either static or controllable at runtime
289 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400290 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwoodae92eb32011-10-25 10:11:46 -0400291 private static final boolean mDebugLightSensor = (false || mSpew);
Jim Miller92e66dd2012-02-21 18:57:12 -0800292 private static final boolean mDebugLightAnimation = (false || mSpew);
293
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700294 private native void nativeInit();
295 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700296 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
298 /*
299 static PrintStream mLog;
300 static {
301 try {
302 mLog = new PrintStream("/data/power.log");
303 }
304 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800305 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 }
307 }
308 static class Log {
309 static void d(String tag, String s) {
310 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800311 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
313 static void i(String tag, String s) {
314 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800315 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
317 static void w(String tag, String s) {
318 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800319 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 }
321 static void e(String tag, String s) {
322 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800323 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325 }
326 */
327
328 /**
329 * This class works around a deadlock between the lock in PowerManager.WakeLock
330 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
331 * mToken object so it can be accessed from any thread, but it calls into here
332 * with its lock held. This class is essentially a reimplementation of
333 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
334 * only call it with our own locks held.
335 */
336 private class UnsynchronizedWakeLock {
337 int mFlags;
338 String mTag;
339 IBinder mToken;
340 int mCount = 0;
341 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500342 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
344 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
345 mFlags = flags;
346 mTag = tag;
347 mToken = new Binder();
348 mRefCounted = refCounted;
349 }
350
351 public void acquire() {
352 if (!mRefCounted || mCount++ == 0) {
353 long ident = Binder.clearCallingIdentity();
354 try {
355 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700356 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500357 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 } finally {
359 Binder.restoreCallingIdentity(ident);
360 }
361 }
362 }
363
364 public void release() {
365 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500366 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500367 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 }
369 if (mCount < 0) {
370 throw new RuntimeException("WakeLock under-locked " + mTag);
371 }
372 }
373
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500374 public boolean isHeld()
375 {
376 return mHeld;
377 }
378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 public String toString() {
380 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500381 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 }
383 }
384
385 private final class BatteryReceiver extends BroadcastReceiver {
386 @Override
387 public void onReceive(Context context, Intent intent) {
388 synchronized (mLocks) {
389 boolean wasPowered = mIsPowered;
390 mIsPowered = mBatteryService.isPowered();
391
392 if (mIsPowered != wasPowered) {
393 // update mStayOnWhilePluggedIn wake lock
394 updateWakeLockLocked();
395
396 // treat plugging and unplugging the devices as a user activity.
397 // users find it disconcerting when they unplug the device
398 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500399 // to avoid turning on the screen when unplugging, we only trigger
400 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 // temporarily set mUserActivityAllowed to true so this will work
402 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700403 // However, you can also set config_unplugTurnsOnScreen to have it
404 // turn on. Some devices want this because they don't have a
405 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700407 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
408 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500409 forceUserActivityLocked();
410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412 }
413 }
414 }
415 }
416
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500417 private final class BootCompletedReceiver extends BroadcastReceiver {
418 @Override
419 public void onReceive(Context context, Intent intent) {
420 bootCompleted();
421 }
422 }
423
Mike Lockwoodb2865412010-02-02 22:40:33 -0500424 private final class DockReceiver extends BroadcastReceiver {
425 @Override
426 public void onReceive(Context context, Intent intent) {
427 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
428 Intent.EXTRA_DOCK_STATE_UNDOCKED);
429 dockStateChanged(state);
430 }
431 }
432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 /**
434 * Set the setting that determines whether the device stays on when plugged in.
435 * The argument is a bit string, with each bit specifying a power source that,
436 * when the device is connected to that source, causes the device to stay on.
437 * See {@link android.os.BatteryManager} for the list of power sources that
438 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
439 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
440 * @param val an {@code int} containing the bits that specify which power sources
441 * should cause the device to stay on.
442 */
443 public void setStayOnSetting(int val) {
444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
445 Settings.System.putInt(mContext.getContentResolver(),
446 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
447 }
448
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800449 public void setMaximumScreenOffTimeount(int timeMs) {
450 mContext.enforceCallingOrSelfPermission(
451 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
452 synchronized (mLocks) {
453 mMaximumScreenOffTimeout = timeMs;
454 // recalculate everything
455 setScreenOffTimeoutsLocked();
456 }
457 }
458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700460 private int getInt(String name, int defValue) {
461 ContentValues values = mSettings.getValues(name);
462 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
463 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
465
Joe Onorato609695d2010-10-14 14:57:49 -0700466 private float getFloat(String name, float defValue) {
467 ContentValues values = mSettings.getValues(name);
468 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
469 return fVal != null ? fVal : defValue;
470 }
471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 public void update(Observable o, Object arg) {
473 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700474 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
475 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
476 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 updateWakeLockLocked();
478
Amith Yamasani8b619832010-09-22 16:11:59 -0700479 // SCREEN_OFF_TIMEOUT, default to 15 seconds
480 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481
Joe Onorato609695d2010-10-14 14:57:49 -0700482 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 //mDimScreen = getInt(DIM_SCREEN) != 0;
484
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800485 mScreenBrightnessSetting = getInt(SCREEN_BRIGHTNESS, DEFAULT_SCREEN_BRIGHTNESS);
486 mLightSensorAdjustSetting = getFloat(SCREEN_AUTO_BRIGHTNESS_ADJ, 0);
487
Amith Yamasani8b619832010-09-22 16:11:59 -0700488 // SCREEN_BRIGHTNESS_MODE, default to manual
489 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
490 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 // recalculate everything
493 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700494
Jim Miller92e66dd2012-02-21 18:57:12 -0800495 mWindowScaleAnimation = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
Joe Onorato609695d2010-10-14 14:57:49 -0700496 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
497 mAnimationSetting = 0;
Jim Miller92e66dd2012-02-21 18:57:12 -0800498 if (mWindowScaleAnimation > 0.5f) {
Joe Onorato609695d2010-10-14 14:57:49 -0700499 mAnimationSetting |= ANIM_SETTING_OFF;
500 }
501 if (transitionScale > 0.5f) {
502 // Uncomment this if you want the screen-on animation.
503 // mAnimationSetting |= ANIM_SETTING_ON;
504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
506 }
507 }
508
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700509 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 // Hack to get our uid... should have a func for this.
511 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700512 MY_UID = Process.myUid();
513 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 Binder.restoreCallingIdentity(token);
515
516 // XXX remove this when the kernel doesn't timeout wake locks
517 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
518
519 // assume nothing is on yet
520 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 // Add ourself to the Watchdog monitors.
523 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 }
525
526 private ContentQueryMap mSettings;
527
Mike Lockwood3a322132009-11-24 00:30:52 -0500528 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700529 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500530 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 mContext = context;
532 mActivityService = activity;
533 mBatteryStats = BatteryStatsService.getService();
534 mBatteryService = battery;
535
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500536 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
537 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
538 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
539 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700540 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500541
Joe Onoratob08a1af2010-10-11 19:28:58 -0700542 nativeInit();
543 synchronized (mLocks) {
544 updateNativePowerStateLocked();
545 }
546
547 mInitComplete = false;
Jim Miller92e66dd2012-02-21 18:57:12 -0800548 mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread",
549 Process.THREAD_PRIORITY_DISPLAY);
550 mScreenBrightnessAnimator.start();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700551
Jim Miller92e66dd2012-02-21 18:57:12 -0800552 synchronized (mScreenBrightnessAnimator) {
Joe Onoratob08a1af2010-10-11 19:28:58 -0700553 while (!mInitComplete) {
554 try {
Jim Miller92e66dd2012-02-21 18:57:12 -0800555 mScreenBrightnessAnimator.wait();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700556 } catch (InterruptedException e) {
557 // Ignore
558 }
559 }
560 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800561
Joe Onoratob08a1af2010-10-11 19:28:58 -0700562 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 mHandlerThread = new HandlerThread("PowerManagerService") {
564 @Override
565 protected void onLooperPrepared() {
566 super.onLooperPrepared();
567 initInThread();
568 }
569 };
570 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 synchronized (mHandlerThread) {
573 while (!mInitComplete) {
574 try {
575 mHandlerThread.wait();
576 } catch (InterruptedException e) {
577 // Ignore
578 }
579 }
580 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800581
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700582 nativeInit();
Todd Poynor94d00242012-01-11 20:14:34 -0800583 Power.powerInitNative();
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700584 synchronized (mLocks) {
585 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700586 // We make sure to start out with the screen on due to user activity.
587 // (They did just boot their device, after all.)
588 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700589 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 void initInThread() {
594 mHandler = new Handler();
595
596 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700597 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
599 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
600 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
601 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
602 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
603 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500604 mProximityPartialLock = new UnsynchronizedWakeLock(
605 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606
607 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
608 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
609 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
610 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
611
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700612 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400613
Joe Onoratob08a1af2010-10-11 19:28:58 -0700614 mAnimateScreenLights = resources.getBoolean(
615 com.android.internal.R.bool.config_animateScreenLights);
616
Joe Onorato6d747652010-10-11 15:15:31 -0700617 mUnplugTurnsOnScreen = resources.getBoolean(
618 com.android.internal.R.bool.config_unplugTurnsOnScreen);
619
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400620 mScreenBrightnessDim = resources.getInteger(
621 com.android.internal.R.integer.config_screenBrightnessDim);
622
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400623 // read settings for auto-brightness
624 mUseSoftwareAutoBrightness = resources.getBoolean(
625 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400626 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700627 mAutoBrightnessLevels = resources.getIntArray(
628 com.android.internal.R.array.config_autoBrightnessLevels);
629 mLcdBacklightValues = resources.getIntArray(
630 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
631 mButtonBacklightValues = resources.getIntArray(
632 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
633 mKeyboardBacklightValues = resources.getIntArray(
634 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500635 mLightSensorWarmupTime = resources.getInteger(
636 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700637 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700638
639 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
641 "(" + Settings.System.NAME + "=?) or ("
642 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700643 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700644 + Settings.System.NAME + "=?) or ("
645 + Settings.System.NAME + "=?) or ("
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800646 + Settings.System.NAME + "=?) or ("
647 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 + Settings.System.NAME + "=?)",
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800649 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS,
650 SCREEN_BRIGHTNESS_MODE, SCREEN_AUTO_BRIGHTNESS_ADJ,
651 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 null);
653 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
654 SettingsObserver settingsObserver = new SettingsObserver();
655 mSettings.addObserver(settingsObserver);
656
657 // pretend that the settings changed so we will get their initial state
658 settingsObserver.update(mSettings, null);
659
660 // register for the battery changed notifications
661 IntentFilter filter = new IntentFilter();
662 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
663 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500664 filter = new IntentFilter();
665 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
666 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500667 filter = new IntentFilter();
668 filter.addAction(Intent.ACTION_DOCK_EVENT);
669 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Doug Zongker43866e02010-01-07 12:09:54 -0800671 // Listen for secure settings changes
672 mContext.getContentResolver().registerContentObserver(
673 Settings.Secure.CONTENT_URI, true,
674 new ContentObserver(new Handler()) {
675 public void onChange(boolean selfChange) {
676 updateSettingsValues();
677 }
678 });
679 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 synchronized (mHandlerThread) {
682 mInitComplete = true;
683 mHandlerThread.notifyAll();
684 }
685 }
686
687 private class WakeLock implements IBinder.DeathRecipient
688 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700689 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 super();
691 flags = f;
692 binder = b;
693 tag = t;
694 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700695 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (u != MY_UID || (
697 !"KEEP_SCREEN_ON_FLAG".equals(tag)
698 && !"KeyInputQueue".equals(tag))) {
699 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
700 ? BatteryStats.WAKE_TYPE_PARTIAL
701 : BatteryStats.WAKE_TYPE_FULL;
702 } else {
703 monitorType = -1;
704 }
705 try {
706 b.linkToDeath(this, 0);
707 } catch (RemoteException e) {
708 binderDied();
709 }
710 }
711 public void binderDied() {
712 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500713 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715 }
716 final int flags;
717 final IBinder binder;
718 final String tag;
719 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400720 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700722 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 boolean activated = true;
724 int minState;
725 }
726
727 private void updateWakeLockLocked() {
728 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
729 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
730 mStayOnWhilePluggedInScreenDimLock.acquire();
731 mStayOnWhilePluggedInPartialLock.acquire();
732 } else {
733 mStayOnWhilePluggedInScreenDimLock.release();
734 mStayOnWhilePluggedInPartialLock.release();
735 }
736 }
737
738 private boolean isScreenLock(int flags)
739 {
740 int n = flags & LOCK_MASK;
741 return n == PowerManager.FULL_WAKE_LOCK
742 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400743 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
744 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700747 void enforceWakeSourcePermission(int uid, int pid) {
748 if (uid == Process.myUid()) {
749 return;
750 }
751 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
752 pid, uid, null);
753 }
754
755 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700757 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700758 if (uid != Process.myUid()) {
759 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
760 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700761 if (ws != null) {
762 enforceWakeSourcePermission(uid, pid);
763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 long ident = Binder.clearCallingIdentity();
765 try {
766 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700767 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 } finally {
770 Binder.restoreCallingIdentity(ident);
771 }
772 }
773
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700774 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700775 if (wl.monitorType >= 0) {
776 long origId = Binder.clearCallingIdentity();
777 try {
778 if (ws != null) {
779 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
780 wl.monitorType);
781 } else {
782 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
783 }
784 } catch (RemoteException e) {
785 // Ignore
786 } finally {
787 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700788 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700789 }
790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700792 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700793 if (wl.monitorType >= 0) {
794 long origId = Binder.clearCallingIdentity();
795 try {
796 if (ws != null) {
797 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
798 wl.monitorType);
799 } else {
800 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
801 }
802 } catch (RemoteException e) {
803 // Ignore
804 } finally {
805 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700806 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700807 }
808 }
809
810 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
811 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700816 if (ws != null && ws.size() == 0) {
817 ws = null;
818 }
819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 int index = mLocks.getIndex(lock);
821 WakeLock wl;
822 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700823 boolean diffsource;
824 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700826 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 switch (wl.flags & LOCK_MASK)
828 {
829 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500830 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400831 wl.minState = SCREEN_BRIGHT;
832 } else {
833 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 break;
836 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
837 wl.minState = SCREEN_BRIGHT;
838 break;
839 case PowerManager.SCREEN_DIM_WAKE_LOCK:
840 wl.minState = SCREEN_DIM;
841 break;
842 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700843 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 break;
845 default:
846 // just log and bail. we're in the server, so don't
847 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800848 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 + " flags=" + flags);
850 return;
851 }
852 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700853 if (ws != null) {
854 wl.ws = new WorkSource(ws);
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700857 diffsource = false;
858 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 } else {
860 wl = mLocks.get(index);
861 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700862 oldsource = wl.ws;
863 if (oldsource != null) {
864 if (ws == null) {
865 wl.ws = null;
866 diffsource = true;
867 } else {
868 diffsource = oldsource.diff(ws);
869 }
870 } else if (ws != null) {
871 diffsource = true;
872 } else {
873 diffsource = false;
874 }
875 if (diffsource) {
876 wl.ws = new WorkSource(ws);
877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879 if (isScreenLock(flags)) {
880 // if this causes a wakeup, we reactivate all of the locks and
881 // set it to whatever they want. otherwise, we modulate that
882 // by the current state so we never turn it more on than
883 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400884 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
885 mProximityWakeLockCount++;
886 if (mProximityWakeLockCount == 1) {
887 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400890 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
891 int oldWakeLockState = mWakeLockState;
892 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400893
894 // Disable proximity sensor if if user presses power key while we are in the
895 // "waiting for proximity sensor to go negative" state.
896 if ((mWakeLockState & SCREEN_ON_BIT) != 0
897 && mProximitySensorActive && mProximityWakeLockCount == 0) {
898 mProximitySensorActive = false;
899 }
900
Joe Onorato8274a0e2010-10-05 17:38:09 -0400901 if (mSpew) {
902 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
903 + " mWakeLockState=0x"
904 + Integer.toHexString(mWakeLockState)
905 + " previous wakeLockState=0x"
906 + Integer.toHexString(oldWakeLockState));
907 }
908 } else {
909 if (mSpew) {
910 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
911 + " mLocks.gatherState()=0x"
912 + Integer.toHexString(mLocks.gatherState())
913 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
914 }
915 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400917 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
921 if (newlock) {
922 mPartialCount++;
923 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800924 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
926 }
927 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700930 if (diffsource) {
931 // If the lock sources have changed, need to first release the
932 // old ones.
933 noteStopWakeLocked(wl, oldsource);
934 }
935 if (newlock || diffsource) {
936 noteStartWakeLocked(wl, ws);
937 }
938 }
939
940 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
941 int uid = Binder.getCallingUid();
942 int pid = Binder.getCallingPid();
943 if (ws != null && ws.size() == 0) {
944 ws = null;
945 }
946 if (ws != null) {
947 enforceWakeSourcePermission(uid, pid);
948 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700949 synchronized (mLocks) {
950 int index = mLocks.getIndex(lock);
951 if (index < 0) {
952 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700954 WakeLock wl = mLocks.get(index);
955 WorkSource oldsource = wl.ws;
956 wl.ws = ws != null ? new WorkSource(ws) : null;
957 noteStopWakeLocked(wl, oldsource);
958 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
960 }
961
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500962 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700963 int uid = Binder.getCallingUid();
964 if (uid != Process.myUid()) {
965 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967
968 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500969 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971 }
972
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500973 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 WakeLock wl = mLocks.removeLock(lock);
975 if (wl == null) {
976 return;
977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800980 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
982 }
983
984 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400985 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
986 mProximityWakeLockCount--;
987 if (mProximityWakeLockCount == 0) {
988 if (mProximitySensorActive &&
989 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
990 // wait for proximity sensor to go negative before disabling sensor
991 if (mDebugProximitySensor) {
992 Slog.d(TAG, "waiting for proximity sensor to go negative");
993 }
994 } else {
995 disableProximityLockLocked();
996 }
997 }
998 } else {
999 mWakeLockState = mLocks.gatherState();
1000 // goes in the middle to reduce flicker
1001 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
1002 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
1003 }
1004 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
1007 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
1008 mPartialCount--;
1009 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 Power.releaseWakeLock(PARTIAL_NAME);
1012 }
1013 }
1014 // Unlink the lock from the binder.
1015 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016
Dianne Hackborn70be1672010-09-14 11:13:03 -07001017 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 private class PokeLock implements IBinder.DeathRecipient
1021 {
1022 PokeLock(int p, IBinder b, String t) {
1023 super();
1024 this.pokey = p;
1025 this.binder = b;
1026 this.tag = t;
1027 try {
1028 b.linkToDeath(this, 0);
1029 } catch (RemoteException e) {
1030 binderDied();
1031 }
1032 }
1033 public void binderDied() {
1034 setPokeLock(0, this.binder, this.tag);
1035 }
1036 int pokey;
1037 IBinder binder;
1038 String tag;
1039 boolean awakeOnSet;
1040 }
1041
1042 public void setPokeLock(int pokey, IBinder token, String tag) {
1043 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1044 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001045 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 return;
1047 }
1048
1049 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1050 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1051 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1052 }
1053
1054 synchronized (mLocks) {
1055 if (pokey != 0) {
1056 PokeLock p = mPokeLocks.get(token);
1057 int oldPokey = 0;
1058 if (p != null) {
1059 oldPokey = p.pokey;
1060 p.pokey = pokey;
1061 } else {
1062 p = new PokeLock(pokey, token, tag);
1063 mPokeLocks.put(token, p);
1064 }
1065 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1066 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1067 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1068 p.awakeOnSet = true;
1069 }
1070 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001071 PokeLock rLock = mPokeLocks.remove(token);
1072 if (rLock != null) {
1073 token.unlinkToDeath(rLock, 0);
1074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
1077 int oldPokey = mPokey;
1078 int cumulative = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 boolean awakeOnSet = false;
1080 for (PokeLock p: mPokeLocks.values()) {
1081 cumulative |= p.pokey;
1082 if (p.awakeOnSet) {
1083 awakeOnSet = true;
1084 }
1085 }
1086 mPokey = cumulative;
1087 mPokeAwakeOnSet = awakeOnSet;
1088
1089 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1090 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 if (oldCumulativeTimeout != newCumulativeTimeout) {
1093 setScreenOffTimeoutsLocked();
1094 // reset the countdown timer, but use the existing nextState so it doesn't
1095 // change anything
1096 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1097 }
1098 }
1099 }
1100
1101 private static String lockType(int type)
1102 {
1103 switch (type)
1104 {
1105 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001106 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001108 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001110 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001112 return "PARTIAL_WAKE_LOCK ";
1113 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1114 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 default:
David Brown251faa62009-08-02 22:04:36 -07001116 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118 }
1119
1120 private static String dumpPowerState(int state) {
1121 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1122 ? "KEYBOARD_BRIGHT_BIT " : "")
1123 + (((state & SCREEN_BRIGHT_BIT) != 0)
1124 ? "SCREEN_BRIGHT_BIT " : "")
1125 + (((state & SCREEN_ON_BIT) != 0)
1126 ? "SCREEN_ON_BIT " : "")
1127 + (((state & BATTERY_LOW_BIT) != 0)
1128 ? "BATTERY_LOW_BIT " : "");
1129 }
1130
1131 @Override
1132 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1133 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1134 != PackageManager.PERMISSION_GRANTED) {
1135 pw.println("Permission Denial: can't dump PowerManager from from pid="
1136 + Binder.getCallingPid()
1137 + ", uid=" + Binder.getCallingUid());
1138 return;
1139 }
1140
1141 long now = SystemClock.uptimeMillis();
1142
Mike Lockwoodca44df82010-02-25 13:48:49 -05001143 synchronized (mLocks) {
1144 pw.println("Power Manager State:");
1145 pw.println(" mIsPowered=" + mIsPowered
1146 + " mPowerState=" + mPowerState
1147 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1148 + " ms");
1149 pw.println(" mPartialCount=" + mPartialCount);
1150 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1151 pw.println(" mUserState=" + dumpPowerState(mUserState));
1152 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1153 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1154 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1155 + " " + ((mNextTimeout-now)/1000) + "s from now");
1156 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001157 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001158 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1159 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001160 pw.println(" mScreenOffReason=" + mScreenOffReason
1161 + " mUserState=" + mUserState);
1162 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1163 + ',' + mBroadcastQueue[2] + "}");
1164 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1165 + ',' + mBroadcastWhy[2] + "}");
1166 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1167 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1168 + " mUserActivityAllowed=" + mUserActivityAllowed);
1169 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1170 + " mScreenOffDelay=" + mScreenOffDelay);
1171 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1172 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1173 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1174 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1175 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1176 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1177 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1178 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1179 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1180 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1181 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1182 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1183 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1184 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1185 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1186 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08001187 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled
1188 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001189 pw.println(" mLightSensorValue=" + mLightSensorValue
1190 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001191 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1192 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001193 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1194 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1195 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1196 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1197 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
Jim Miller92e66dd2012-02-21 18:57:12 -08001198 mScreenBrightnessAnimator.dump(pw, " mScreenBrightnessAnimator: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001199
Mike Lockwoodca44df82010-02-25 13:48:49 -05001200 int N = mLocks.size();
1201 pw.println();
1202 pw.println("mLocks.size=" + N + ":");
1203 for (int i=0; i<N; i++) {
1204 WakeLock wl = mLocks.get(i);
1205 String type = lockType(wl.flags & LOCK_MASK);
1206 String acquireCausesWakeup = "";
1207 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1208 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1209 }
1210 String activated = "";
1211 if (wl.activated) {
1212 activated = " activated";
1213 }
1214 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001215 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1216 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001218
1219 pw.println();
1220 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1221 for (PokeLock p: mPokeLocks.values()) {
1222 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001223 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1224 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001225 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1226 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1227 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1228 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001230
Mike Lockwoodca44df82010-02-25 13:48:49 -05001231 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234
Joe Onorato7999bff2010-07-24 11:50:05 -04001235 private void setTimeoutLocked(long now, int nextState) {
1236 setTimeoutLocked(now, -1, nextState);
1237 }
1238
1239 // If they gave a timeoutOverride it is the number of seconds
1240 // to screen-off. Figure out where in the countdown cycle we
1241 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001242 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1243 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001244 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001245 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001246 long when = 0;
1247 if (timeoutOverride <= 0) {
1248 switch (nextState)
1249 {
1250 case SCREEN_BRIGHT:
1251 when = now + mKeylightDelay;
1252 break;
1253 case SCREEN_DIM:
1254 if (mDimDelay >= 0) {
1255 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001256 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001257 } else {
1258 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1259 }
1260 case SCREEN_OFF:
1261 synchronized (mLocks) {
1262 when = now + mScreenOffDelay;
1263 }
1264 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001265 default:
1266 when = now;
1267 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001269 } else {
1270 override: {
1271 if (timeoutOverride <= mScreenOffDelay) {
1272 when = now + timeoutOverride;
1273 nextState = SCREEN_OFF;
1274 break override;
1275 }
1276 timeoutOverride -= mScreenOffDelay;
1277
1278 if (mDimDelay >= 0) {
1279 if (timeoutOverride <= mDimDelay) {
1280 when = now + timeoutOverride;
1281 nextState = SCREEN_DIM;
1282 break override;
1283 }
1284 timeoutOverride -= mDimDelay;
1285 }
1286
1287 when = now + timeoutOverride;
1288 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001290 }
1291 if (mSpew) {
1292 Slog.d(TAG, "setTimeoutLocked now=" + now
1293 + " timeoutOverride=" + timeoutOverride
1294 + " nextState=" + nextState + " when=" + when);
1295 }
Joe Onorato797e6882010-08-26 14:46:01 -04001296
1297 mHandler.removeCallbacks(mTimeoutTask);
1298 mTimeoutTask.nextState = nextState;
1299 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1300 ? (originalTimeoutOverride - timeoutOverride)
1301 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001302 mHandler.postAtTime(mTimeoutTask, when);
1303 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 }
1307
1308 private void cancelTimerLocked()
1309 {
1310 mHandler.removeCallbacks(mTimeoutTask);
1311 mTimeoutTask.nextState = -1;
1312 }
1313
1314 private class TimeoutTask implements Runnable
1315 {
1316 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001317 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 public void run()
1319 {
1320 synchronized (mLocks) {
1321 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001322 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
1325 if (nextState == -1) {
1326 return;
1327 }
1328
1329 mUserState = this.nextState;
1330 setPowerState(this.nextState | mWakeLockState);
1331
1332 long now = SystemClock.uptimeMillis();
1333
1334 switch (this.nextState)
1335 {
1336 case SCREEN_BRIGHT:
1337 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001338 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 break;
1340 }
1341 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001342 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 break;
1344 }
1345 }
1346 }
1347 }
1348
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001349 private void sendNotificationLocked(boolean on, int why) {
1350 if (!mInitialized) {
1351 // No notifications sent until first initialization is done.
1352 // This is so that when we are moving from our initial state
1353 // which looks like the screen was off to it being on, we do not
1354 // go through the process of waiting for the higher-level user
1355 // space to be ready before turning up the display brightness.
1356 // (And also do not send needless broadcasts about the screen.)
1357 return;
1358 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001359
1360 if (DEBUG_SCREEN_ON) {
1361 RuntimeException here = new RuntimeException("here");
1362 here.fillInStackTrace();
1363 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1364 }
1365
Joe Onorato64c62ba2009-03-24 20:13:57 -07001366 if (!on) {
1367 mStillNeedSleepNotification = false;
1368 }
1369
Joe Onorato128e7292009-03-24 18:41:31 -07001370 // Add to the queue.
1371 int index = 0;
1372 while (mBroadcastQueue[index] != -1) {
1373 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
Joe Onorato128e7292009-03-24 18:41:31 -07001375 mBroadcastQueue[index] = on ? 1 : 0;
1376 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377
Joe Onorato128e7292009-03-24 18:41:31 -07001378 // If we added it position 2, then there is a pair that can be stripped.
1379 // If we added it position 1 and we're turning the screen off, we can strip
1380 // the pair and do nothing, because the screen is already off, and therefore
1381 // keyguard has already been enabled.
1382 // However, if we added it at position 1 and we're turning it on, then position
1383 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1384 // on, so have to run the queue then.
1385 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001386 // While we're collapsing them, if it's going off, and the new reason
1387 // is more significant than the first, then use the new one.
1388 if (!on && mBroadcastWhy[0] > why) {
1389 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001390 }
1391 mBroadcastQueue[0] = on ? 1 : 0;
1392 mBroadcastQueue[1] = -1;
1393 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001394 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001395 mBroadcastWakeLock.release();
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();
Joe Onorato128e7292009-03-24 18:41:31 -07001398 index = 0;
1399 }
1400 if (index == 1 && !on) {
1401 mBroadcastQueue[0] = -1;
1402 mBroadcastQueue[1] = -1;
1403 index = -1;
1404 // The wake lock was being held, but we're not actually going to do any
1405 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001406 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001408 }
1409
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001410 // The broadcast queue has changed; make sure the screen is on if it
1411 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001412 if (mSkippedScreenOn) {
1413 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1414 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001415
Joe Onorato128e7292009-03-24 18:41:31 -07001416 // Now send the message.
1417 if (index >= 0) {
1418 // Acquire the broadcast wake lock before changing the power
1419 // state. It will be release after the broadcast is sent.
1420 // We always increment the ref count for each notification in the queue
1421 // and always decrement when that notification is handled.
1422 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001423 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001424 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426 }
1427
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001428 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1429 new WindowManagerPolicy.ScreenOnListener() {
Jim Miller92e66dd2012-02-21 18:57:12 -08001430 public void onScreenOn() {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001431 synchronized (mLocks) {
1432 if (mPreparingForScreenOn) {
1433 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001434 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001435 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1436 4, mBroadcastWakeLock.mCount);
1437 mBroadcastWakeLock.release();
1438 }
1439 }
1440 }
1441 };
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 private Runnable mNotificationTask = new Runnable()
1444 {
1445 public void run()
1446 {
Joe Onorato128e7292009-03-24 18:41:31 -07001447 while (true) {
1448 int value;
1449 int why;
1450 WindowManagerPolicy policy;
1451 synchronized (mLocks) {
1452 value = mBroadcastQueue[0];
1453 why = mBroadcastWhy[0];
1454 for (int i=0; i<2; i++) {
1455 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1456 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1457 }
1458 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001459 if (value == 1 && !mPreparingForScreenOn) {
1460 mPreparingForScreenOn = true;
1461 mBroadcastWakeLock.acquire();
1462 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1463 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
Joe Onorato128e7292009-03-24 18:41:31 -07001466 if (value == 1) {
1467 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001468
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001469 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001470 try {
1471 ActivityManagerNative.getDefault().wakingUp();
1472 } catch (RemoteException e) {
1473 // ignore it
1474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475
Joe Onorato128e7292009-03-24 18:41:31 -07001476 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001478 }
1479 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1480 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1481 mScreenOnBroadcastDone, mHandler, 0, null, null);
1482 } else {
1483 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001484 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001485 mBroadcastWakeLock.mCount);
1486 mBroadcastWakeLock.release();
1487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489 }
Joe Onorato128e7292009-03-24 18:41:31 -07001490 else if (value == 0) {
1491 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492
Joe Onorato128e7292009-03-24 18:41:31 -07001493 policy.screenTurnedOff(why);
1494 try {
1495 ActivityManagerNative.getDefault().goingToSleep();
1496 } catch (RemoteException e) {
1497 // ignore it.
1498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499
Joe Onorato128e7292009-03-24 18:41:31 -07001500 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1501 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1502 mScreenOffBroadcastDone, mHandler, 0, null, null);
1503 } else {
1504 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001505 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001506 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001507 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001508 mBroadcastWakeLock.release();
1509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511 }
Joe Onorato128e7292009-03-24 18:41:31 -07001512 else {
1513 // If we're in this case, then this handler is running for a previous
1514 // paired transaction. mBroadcastWakeLock will already have been released.
1515 break;
1516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518 }
1519 };
1520
1521 long mScreenOnStart;
1522 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1523 public void onReceive(Context context, Intent intent) {
1524 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001525 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1527 mBroadcastWakeLock.release();
1528 }
1529 }
1530 };
1531
1532 long mScreenOffStart;
1533 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1534 public void onReceive(Context context, Intent intent) {
1535 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001536 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1538 mBroadcastWakeLock.release();
1539 }
1540 }
1541 };
1542
1543 void logPointerUpEvent() {
1544 if (LOG_TOUCH_DOWNS) {
1545 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1546 mLastTouchDown = 0;
1547 }
1548 }
1549
1550 void logPointerDownEvent() {
1551 if (LOG_TOUCH_DOWNS) {
1552 // If we are not already timing a down/up sequence
1553 if (mLastTouchDown == 0) {
1554 mLastTouchDown = SystemClock.elapsedRealtime();
1555 mTouchCycles++;
1556 }
1557 }
1558 }
1559
1560 /**
1561 * Prevents the screen from turning on even if it *should* turn on due
1562 * to a subsequent full wake lock being acquired.
1563 * <p>
1564 * This is a temporary hack that allows an activity to "cover up" any
1565 * display glitches that happen during the activity's startup
1566 * sequence. (Specifically, this API was added to work around a
1567 * cosmetic bug in the "incoming call" sequence, where the lock screen
1568 * would flicker briefly before the incoming call UI became visible.)
1569 * TODO: There ought to be a more elegant way of doing this,
1570 * probably by having the PowerManager and ActivityManager
1571 * work together to let apps specify that the screen on/off
1572 * state should be synchronized with the Activity lifecycle.
1573 * <p>
1574 * Note that calling preventScreenOn(true) will NOT turn the screen
1575 * off if it's currently on. (This API only affects *future*
1576 * acquisitions of full wake locks.)
1577 * But calling preventScreenOn(false) WILL turn the screen on if
1578 * it's currently off because of a prior preventScreenOn(true) call.
1579 * <p>
1580 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1581 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1582 * call doesn't occur within 5 seconds, we'll turn the screen back on
1583 * ourselves (and log a warning about it); this prevents a buggy app
1584 * from disabling the screen forever.)
1585 * <p>
1586 * TODO: this feature should really be controlled by a new type of poke
1587 * lock (rather than an IPowerManager call).
1588 */
1589 public void preventScreenOn(boolean prevent) {
1590 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1591
1592 synchronized (mLocks) {
1593 if (prevent) {
1594 // First of all, grab a partial wake lock to
1595 // make sure the CPU stays on during the entire
1596 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1597 mPreventScreenOnPartialLock.acquire();
1598
1599 // Post a forceReenableScreen() call (for 5 seconds in the
1600 // future) to make sure the matching preventScreenOn(false) call
1601 // has happened by then.
1602 mHandler.removeCallbacks(mForceReenableScreenTask);
1603 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1604
1605 // Finally, set the flag that prevents the screen from turning on.
1606 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001607 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 mPreventScreenOn = true;
1609 } else {
1610 // (Re)enable the screen.
1611 mPreventScreenOn = false;
1612
1613 // We're "undoing" a the prior preventScreenOn(true) call, so we
1614 // no longer need the 5-second safeguard.
1615 mHandler.removeCallbacks(mForceReenableScreenTask);
1616
1617 // Forcibly turn on the screen if it's supposed to be on. (This
1618 // handles the case where the screen is currently off because of
1619 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001620 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001622 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1624 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001625 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001627 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629 }
1630
1631 // Release the partial wake lock that we held during the
1632 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1633 mPreventScreenOnPartialLock.release();
1634 }
1635 }
1636 }
1637
1638 public void setScreenBrightnessOverride(int brightness) {
1639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1640
Mike Lockwoodf527c712010-06-10 14:12:33 -04001641 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 synchronized (mLocks) {
1643 if (mScreenBrightnessOverride != brightness) {
1644 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001645 if (isScreenOn()) {
1646 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001651
1652 public void setButtonBrightnessOverride(int brightness) {
1653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1654
Mike Lockwoodf527c712010-06-10 14:12:33 -04001655 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001656 synchronized (mLocks) {
1657 if (mButtonBrightnessOverride != brightness) {
1658 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001659 if (isScreenOn()) {
1660 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1661 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001662 }
1663 }
1664 }
1665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 /**
1667 * Sanity-check that gets called 5 seconds after any call to
1668 * preventScreenOn(true). This ensures that the original call
1669 * is followed promptly by a call to preventScreenOn(false).
1670 */
1671 private void forceReenableScreen() {
1672 // We shouldn't get here at all if mPreventScreenOn is false, since
1673 // we should have already removed any existing
1674 // mForceReenableScreenTask messages...
1675 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001676 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 return;
1678 }
1679
1680 // Uh oh. It's been 5 seconds since a call to
1681 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1682 // This means the app that called preventScreenOn(true) is either
1683 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1684 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1685 // crashed before doing so.)
1686
1687 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001688 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 + "Forcing the screen back on...");
1690 preventScreenOn(false);
1691 }
1692
1693 private Runnable mForceReenableScreenTask = new Runnable() {
1694 public void run() {
1695 forceReenableScreen();
1696 }
1697 };
1698
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001699 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001700 if (DEBUG_SCREEN_ON) {
1701 RuntimeException e = new RuntimeException("here");
1702 e.fillInStackTrace();
1703 Slog.i(TAG, "Set screen state: " + on, e);
1704 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001705 if (on) {
1706 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1707 // If we are turning the screen state on, but the screen
1708 // light is currently off, then make sure that we set the
1709 // light at this point to 0. This is the case where we are
1710 // turning on the screen and waiting for the UI to be drawn
1711 // before showing it to the user. We want the light off
1712 // until it is ready to be shown to the user, not it using
1713 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001714 if (DEBUG_SCREEN_ON) {
1715 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1716 + Integer.toHexString(mPowerState)
1717 + " mSkippedScreenOn=" + mSkippedScreenOn);
1718 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001719 mScreenBrightnessAnimator.animateTo(Power.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
Dianne Hackborn474fd742011-10-10 18:40:22 -07001720 }
1721 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001722 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001723 if (err == 0) {
1724 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1725 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001726 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001727 if (!on) {
1728 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001729 mButtonLight.turnOff();
1730 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001731 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001732 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001733 }
1734 return err;
1735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 private void setPowerState(int state)
1738 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001739 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741
Mike Lockwood435eb642009-12-03 08:40:18 -05001742 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 {
1744 synchronized (mLocks) {
1745 int err;
1746
1747 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001748 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001750 + " noChangeLights=" + noChangeLights
1751 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753
1754 if (noChangeLights) {
1755 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1756 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001757 if (mProximitySensorActive) {
1758 // don't turn on the screen when the proximity sensor lock is held
1759 newState = (newState & ~SCREEN_BRIGHT);
1760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761
1762 if (batteryIsLow()) {
1763 newState |= BATTERY_LOW_BIT;
1764 } else {
1765 newState &= ~BATTERY_LOW_BIT;
1766 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001767 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 return;
1769 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001770
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001771 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 newState |= ALL_BRIGHT;
1773 }
1774
1775 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1776 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1777
Mike Lockwood51b844962009-11-16 21:51:18 -05001778 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001779 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001787 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001789 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1791 }
1792
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001793 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794
1795 if (oldScreenOn != newScreenOn) {
1796 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001797 // When the user presses the power button, we need to always send out the
1798 // notification that it's going to sleep so the keyguard goes on. But
1799 // we can't do that until the screen fades out, so we don't show the keyguard
1800 // too early.
1801 if (mStillNeedSleepNotification) {
1802 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1803 }
1804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 // Turn on the screen UNLESS there was a prior
1806 // preventScreenOn(true) request. (Note that the lifetime
1807 // of a single preventScreenOn() request is limited to 5
1808 // seconds to prevent a buggy app from disabling the
1809 // screen forever; see forceReenableScreen().)
1810 boolean reallyTurnScreenOn = true;
1811 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001812 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 + mPreventScreenOn);
1814 }
1815
1816 if (mPreventScreenOn) {
1817 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001818 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
1820 reallyTurnScreenOn = false;
1821 }
1822 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001823 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 long identity = Binder.clearCallingIdentity();
1825 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001826 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 mBatteryStats.noteScreenOn();
1828 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001829 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 } finally {
1831 Binder.restoreCallingIdentity(identity);
1832 }
1833 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001834 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 // But continue as if we really did turn the screen on...
1836 err = 0;
1837 }
1838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 mLastTouchDown = 0;
1840 mTotalTouchDownTime = 0;
1841 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001842 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 mTotalTouchDownTime, mTouchCycles);
1844 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001846 // Update the lights *after* taking care of turning the
1847 // screen on, so we do this after our notifications are
1848 // enqueued and thus will delay turning on the screen light
1849 // until the windows are correctly displayed.
1850 if (stateChanged) {
1851 updateLightsLocked(newState, 0);
1852 }
1853 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001857 // Update the lights *before* taking care of turning the
1858 // screen off, so we can initiate any animations that are desired.
1859 if (stateChanged) {
1860 updateLightsLocked(newState, 0);
1861 }
1862
Mike Lockwood497087e32009-11-08 18:33:03 -05001863 // cancel light sensor task
1864 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001865 mLightSensorPendingDecrease = false;
1866 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 mScreenOffTime = SystemClock.elapsedRealtime();
1868 long identity = Binder.clearCallingIdentity();
1869 try {
1870 mBatteryStats.noteScreenOff();
1871 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001872 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 } finally {
1874 Binder.restoreCallingIdentity(identity);
1875 }
1876 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001877 mScreenOffReason = reason;
Jim Miller92e66dd2012-02-21 18:57:12 -08001878 if (!mScreenBrightnessAnimator.isAnimating()) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001879 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 err = 0;
1882 mLastTouchDown = 0;
1883 }
1884 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001885 } else if (stateChanged) {
1886 // Screen on/off didn't change, but lights may have.
1887 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001889
1890 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1891
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001892 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001895
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001896 private void updateNativePowerStateLocked() {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001897 if (!mHeadless) {
1898 nativeSetPowerState(
1899 (mPowerState & SCREEN_ON_BIT) != 0,
1900 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1901 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001903
Mike Lockwood435eb642009-12-03 08:40:18 -05001904 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001906 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001908 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1909 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001911 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001913 mScreenOffReason = reason;
1914 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
1916 return err;
1917 }
1918
1919 private boolean batteryIsLow() {
1920 return (!mIsPowered &&
1921 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1922 }
1923
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001924 private boolean shouldDeferScreenOnLocked() {
1925 if (mPreparingForScreenOn) {
1926 // Currently waiting for confirmation from the policy that it
1927 // is okay to turn on the screen. Don't allow the screen to go
1928 // on until that is done.
1929 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1930 "updateLights: delaying screen on due to mPreparingForScreenOn");
1931 return true;
1932 } else {
1933 // If there is a screen-on command in the notification queue, we
1934 // can't turn the screen on until it has been processed (and we
1935 // have set mPreparingForScreenOn) or it has been dropped.
1936 for (int i=0; i<mBroadcastQueue.length; i++) {
1937 if (mBroadcastQueue[i] == 1) {
1938 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1939 "updateLights: delaying screen on due to notification queue");
1940 return true;
1941 }
1942 }
1943 }
1944 return false;
1945 }
1946
The Android Open Source Project10592532009-03-18 17:39:46 -07001947 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001948 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001949
1950 // If the screen is not currently on, we will want to delay actually
1951 // turning the lights on if we are still getting the UI put up.
Jim Miller92e66dd2012-02-21 18:57:12 -08001952 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001953 // Don't turn screen on until we know we are really ready to.
1954 // This is to avoid letting the screen go on before things like the
1955 // lock screen have been displayed.
Jim Miller92e66dd2012-02-21 18:57:12 -08001956 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001957 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1958 }
1959 }
1960
Joe Onorato60607a902010-10-23 14:49:30 -07001961 if ((newState & SCREEN_ON_BIT) != 0) {
1962 // Only turn on the buttons or keyboard if the screen is also on.
1963 // We should never see the buttons on but not the screen.
1964 newState = applyButtonState(newState);
1965 newState = applyKeyboardState(newState);
1966 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001967 final int realDifference = (newState ^ oldState);
1968 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001970 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 int offMask = 0;
1974 int dimMask = 0;
1975 int onMask = 0;
1976
1977 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001980 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1981 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001983 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
1985 }
1986
1987 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001988 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1989 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001991 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993 }
1994
1995 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001996 int nominalCurrentValue = -1;
1997 // If there was an actual difference in the light state, then
1998 // figure out the "ideal" current value based on the previous
1999 // state. Otherwise, this is a change due to the brightness
2000 // override, so we want to animate from whatever the current
2001 // value is.
2002 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
2003 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
2004 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
2005 nominalCurrentValue = preferredBrightness;
2006 break;
2007 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002008 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002009 break;
2010 case 0:
2011 nominalCurrentValue = Power.BRIGHTNESS_OFF;
2012 break;
2013 case SCREEN_BRIGHT_BIT:
2014 default:
2015 // not possible
Jim Miller92e66dd2012-02-21 18:57:12 -08002016 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness();
Joe Onoratob08a1af2010-10-11 19:28:58 -07002017 break;
Joe Onorato128e7292009-03-24 18:41:31 -07002018 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002019 }
2020 int brightness = preferredBrightness;
2021 int steps = ANIM_STEPS;
2022 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
2023 // dim or turn off backlight, depending on if the screen is on
2024 // the scale is because the brightness ramp isn't linear and this biases
2025 // it so the later parts take longer.
2026 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002027 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002028 if (ratio > 1.0f) ratio = 1.0f;
2029 if ((newState & SCREEN_ON_BIT) == 0) {
2030 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2031 // was bright
2032 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 // was dim
2035 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002037 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002039 if ((oldState & SCREEN_ON_BIT) != 0) {
2040 // was bright
2041 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2042 } else {
2043 // was dim
2044 steps = (int)(ANIM_STEPS*ratio);
2045 }
2046 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2047 // If the "stay on while plugged in" option is
2048 // turned on, then the screen will often not
2049 // automatically turn off while plugged in. To
2050 // still have a sense of when it is inactive, we
2051 // will then count going dim as turning off.
2052 mScreenOffTime = SystemClock.elapsedRealtime();
2053 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002054 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002057 long identity = Binder.clearCallingIdentity();
2058 try {
2059 mBatteryStats.noteScreenBrightness(brightness);
2060 } catch (RemoteException e) {
2061 // Nothing interesting to do.
2062 } finally {
2063 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002065 if (!mSkippedScreenOn) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002066 int dt = steps * NOMINAL_FRAME_TIME_MS;
2067 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002068 if (DEBUG_SCREEN_ON) {
2069 RuntimeException e = new RuntimeException("here");
2070 e.fillInStackTrace();
2071 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2072 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002075
Joe Onorato60607a902010-10-23 14:49:30 -07002076 if (mSpew) {
2077 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2078 + " dimMask=0x" + Integer.toHexString(dimMask)
2079 + " onMask=0x" + Integer.toHexString(onMask)
2080 + " difference=0x" + Integer.toHexString(difference)
2081 + " realDifference=0x" + Integer.toHexString(realDifference)
2082 + " forceState=0x" + Integer.toHexString(forceState)
2083 );
2084 }
2085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002087 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002088 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002091 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 if ((newState & BATTERY_LOW_BIT) != 0 &&
2093 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2094 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2095 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002096 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002097 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
2099 if (onMask != 0) {
2100 int brightness = getPreferredBrightness();
2101 if ((newState & BATTERY_LOW_BIT) != 0 &&
2102 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2103 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2104 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002105 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002106 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109
Jim Miller92e66dd2012-02-21 18:57:12 -08002110 /**
2111 * Note: by design this class does not hold mLocks while calling native methods.
2112 * Nor should it. Ever.
2113 */
2114 class ScreenBrightnessAnimator extends HandlerThread {
2115 static final int ANIMATE_LIGHTS = 10;
2116 static final int POWER_OFF = 11;
2117 volatile int startValue;
2118 volatile int endValue;
2119 volatile int currentValue;
2120 private int currentMask;
2121 private int duration;
2122 private long startTimeMillis;
2123 private final String prefix;
2124
2125 public ScreenBrightnessAnimator(String name, int priority) {
2126 super(name, priority);
2127 prefix = name;
2128 }
2129
2130 @Override
2131 protected void onLooperPrepared() {
2132 mScreenBrightnessHandler = new Handler() {
2133 public void handleMessage(Message msg) {
2134 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation
Mike Lockwood3a322132009-11-24 00:30:52 -05002135 ? LightsService.BRIGHTNESS_MODE_SENSOR
2136 : LightsService.BRIGHTNESS_MODE_USER);
Jim Miller92e66dd2012-02-21 18:57:12 -08002137 if (msg.what == ANIMATE_LIGHTS) {
2138 final int mask = msg.arg1;
2139 int value = msg.arg2;
2140 long tStart = SystemClock.uptimeMillis();
2141 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
2142 if (mDebugLightAnimation) Log.v(TAG, "Set brightness: " + value);
2143 mLcdLight.setBrightness(value, brightnessMode);
2144 }
2145 long elapsed = SystemClock.uptimeMillis() - tStart;
2146 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
2147 mButtonLight.setBrightness(value);
2148 }
2149 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
2150 mKeyboardLight.setBrightness(value);
2151 }
2152
2153 if (elapsed > 100) {
2154 Log.e(TAG, "Excessive delay setting brightness: " + elapsed
2155 + "ms, mask=" + mask);
2156 }
2157
2158 // Throttle brightness updates to frame refresh rate
2159 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 0;
2160 synchronized(this) {
2161 currentValue = value;
2162 }
2163 animateInternal(mask, false, delay);
2164 } else if (msg.what == POWER_OFF) {
2165 if (!mHeadless) {
2166 int mode = msg.arg1;
2167 nativeStartSurfaceFlingerAnimation(mode);
2168 }
2169 }
2170 }
2171 };
2172 synchronized (this) {
2173 mInitComplete = true;
2174 notifyAll();
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002175 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002176 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002177
2178 private void animateInternal(int mask, boolean turningOff, int delay) {
2179 synchronized (this) {
2180 if (currentValue != endValue) {
2181 final long now = SystemClock.elapsedRealtime();
2182 final int elapsed = (int) (now - startTimeMillis);
2183 int newValue;
2184 if (elapsed < duration) {
2185 int delta = endValue - startValue;
2186 newValue = startValue + delta * elapsed / duration;
2187 newValue = Math.max(Power.BRIGHTNESS_OFF, newValue);
2188 newValue = Math.min(Power.BRIGHTNESS_ON, newValue);
2189 } else {
2190 newValue = endValue;
2191 mInitialAnimation = false;
2192 }
2193
2194 if (mDebugLightAnimation) {
2195 Log.v(TAG, "Animating light: " + "start:" + startValue
2196 + ", end:" + endValue + ", elapsed:" + elapsed
2197 + ", duration:" + duration + ", current:" + currentValue
2198 + ", delay:" + delay);
2199 }
2200
2201 if (turningOff) {
2202 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR
2203 ? 0 : mAnimationSetting;
2204 if (mDebugLightAnimation) Log.v(TAG, "Doing power-off anim, mode=" + mode);
2205 mScreenBrightnessHandler.obtainMessage(POWER_OFF, mode, 0).sendToTarget();
2206 }
2207 Message msg = mScreenBrightnessHandler
2208 .obtainMessage(ANIMATE_LIGHTS, mask, newValue);
2209 mScreenBrightnessHandler.sendMessageDelayed(msg, delay);
2210 }
2211 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002212 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002213
2214 public void dump(PrintWriter pw, String string) {
2215 pw.println(prefix + "animating: " + "start:" + startValue + ", end:" + endValue
2216 + ", duration:" + duration + ", current:" + currentValue);
2217 }
2218
2219 public void animateTo(int target, int mask, int animationDuration) {
2220 synchronized(this) {
2221 startValue = currentValue;
2222 endValue = target;
2223 currentMask = mask;
2224 duration = (int) (mWindowScaleAnimation * animationDuration);
2225 startTimeMillis = SystemClock.elapsedRealtime();
2226 mInitialAnimation = currentValue == 0 && target > 0;
2227
2228 if (mDebugLightAnimation) {
2229 Log.v(TAG, "animateTo(target=" + target + ", mask=" + mask
2230 + ", duration=" + animationDuration +")"
2231 + ", currentValue=" + currentValue
2232 + ", startTime=" + startTimeMillis);
2233 }
2234
2235 if (target != currentValue) {
2236 final boolean turningOff = endValue == Power.BRIGHTNESS_OFF;
2237 if (turningOff) {
2238 // Cancel all pending animations since we're turning off
2239 mScreenBrightnessHandler.removeCallbacksAndMessages(null);
2240 screenOffFinishedAnimatingLocked(mScreenOffReason);
2241 duration = 200; // TODO: how long should this be?
2242 }
2243 animateInternal(mask, turningOff, 0);
2244 }
2245 }
2246 }
2247
2248 public int getCurrentBrightness() {
2249 synchronized (this) {
2250 return currentValue;
2251 }
2252 }
2253
2254 public boolean isAnimating() {
2255 synchronized (this) {
2256 return currentValue != endValue;
2257 }
2258 }
2259
2260 public void cancelAnimation() {
2261 animateTo(endValue, currentMask, 0);
The Android Open Source Project10592532009-03-18 17:39:46 -07002262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264
Jim Miller92e66dd2012-02-21 18:57:12 -08002265 private void setLightBrightness(int mask, int value) {
2266 mScreenBrightnessAnimator.animateTo(value, mask, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 private int getPreferredBrightness() {
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002270 if (mScreenBrightnessOverride >= 0) {
2271 return mScreenBrightnessOverride;
2272 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
2273 && mAutoBrightessEnabled) {
2274 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002276 final int brightness = mScreenBrightnessSetting;
2277 // Don't let applications turn the screen all the way off
2278 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002281 private int applyButtonState(int state) {
2282 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002283 if ((state & BATTERY_LOW_BIT) != 0) {
2284 // do not override brightness if the battery is low
2285 return state;
2286 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002287 if (mButtonBrightnessOverride >= 0) {
2288 brightness = mButtonBrightnessOverride;
2289 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2290 brightness = mLightSensorButtonBrightness;
2291 }
2292 if (brightness > 0) {
2293 return state | BUTTON_BRIGHT_BIT;
2294 } else if (brightness == 0) {
2295 return state & ~BUTTON_BRIGHT_BIT;
2296 } else {
2297 return state;
2298 }
2299 }
2300
2301 private int applyKeyboardState(int state) {
2302 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002303 if ((state & BATTERY_LOW_BIT) != 0) {
2304 // do not override brightness if the battery is low
2305 return state;
2306 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002307 if (!mKeyboardVisible) {
2308 brightness = 0;
2309 } else if (mButtonBrightnessOverride >= 0) {
2310 brightness = mButtonBrightnessOverride;
2311 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2312 brightness = mLightSensorKeyboardBrightness;
2313 }
2314 if (brightness > 0) {
2315 return state | KEYBOARD_BRIGHT_BIT;
2316 } else if (brightness == 0) {
2317 return state & ~KEYBOARD_BRIGHT_BIT;
2318 } else {
2319 return state;
2320 }
2321 }
2322
Charles Mendis322591c2009-10-29 11:06:59 -07002323 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 synchronized (mLocks) {
2325 return (mPowerState & SCREEN_ON_BIT) != 0;
2326 }
2327 }
2328
Charles Mendis322591c2009-10-29 11:06:59 -07002329 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 synchronized (mLocks) {
2331 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2332 }
2333 }
2334
Mike Lockwood497087e32009-11-08 18:33:03 -05002335 private boolean isScreenTurningOffLocked() {
Jim Miller92e66dd2012-02-21 18:57:12 -08002336 return (mScreenBrightnessAnimator.isAnimating()
2337 && mScreenBrightnessAnimator.endValue == Power.BRIGHTNESS_OFF);
Mike Lockwood497087e32009-11-08 18:33:03 -05002338 }
2339
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002340 private boolean shouldLog(long time) {
2341 synchronized (mLocks) {
2342 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2343 mWarningSpewThrottleTime = time;
2344 mWarningSpewThrottleCount = 0;
2345 return true;
2346 } else if (mWarningSpewThrottleCount < 30) {
2347 mWarningSpewThrottleCount++;
2348 return true;
2349 } else {
2350 return false;
2351 }
2352 }
2353 }
2354
Mike Lockwood200b30b2009-09-20 00:23:59 -04002355 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002356 if (isScreenTurningOffLocked()) {
2357 // cancel animation so userActivity will succeed
Jim Miller92e66dd2012-02-21 18:57:12 -08002358 mScreenBrightnessAnimator.cancelAnimation();
Mike Lockwoode090281422009-11-14 21:02:56 -05002359 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002360 boolean savedActivityAllowed = mUserActivityAllowed;
2361 mUserActivityAllowed = true;
2362 userActivity(SystemClock.uptimeMillis(), false);
2363 mUserActivityAllowed = savedActivityAllowed;
2364 }
2365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002368 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 }
2370
2371 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002372 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2373 != PackageManager.PERMISSION_GRANTED) {
2374 if (shouldLog(time)) {
2375 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2376 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2377 }
2378 return;
2379 }
2380
Joe Onorato7999bff2010-07-24 11:50:05 -04002381 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
2383
2384 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002385 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 }
2387
2388 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002389 userActivity(time, -1, noChangeLights, eventType, force);
2390 }
2391
2392 /*
2393 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2394 * on with user activity. Don't use this function.
2395 */
2396 public void clearUserActivityTimeout(long now, long timeout) {
2397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2398 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2399 userActivity(now, timeout, false, OTHER_EVENT, false);
2400 }
2401
2402 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2403 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404
Joe Onorato1a542c72010-11-08 09:48:20 -08002405 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002406 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002407 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002408 }
2409 return;
2410 }
2411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 synchronized (mLocks) {
2413 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002414 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 + " mUserActivityAllowed=" + mUserActivityAllowed
2416 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002417 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2418 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002419 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002420 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 }
Mike Lockwood05067122009-10-27 23:07:25 -04002422 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002423 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002424 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002425 return;
2426 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002427 // Disable proximity sensor if if user presses power key while we are in the
2428 // "waiting for proximity sensor to go negative" state.
2429 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2430 mProximitySensorActive = false;
2431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (mLastEventTime <= time || force) {
2433 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002434 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002435 // Only turn on button backlights if a button was pressed
2436 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002437 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2439 } else {
2440 // don't clear button/keyboard backlights when the screen is touched.
2441 mUserState |= SCREEN_BRIGHT;
2442 }
2443
Dianne Hackborn617f8772009-03-31 15:04:46 -07002444 int uid = Binder.getCallingUid();
2445 long ident = Binder.clearCallingIdentity();
2446 try {
2447 mBatteryStats.noteUserActivity(uid, eventType);
2448 } catch (RemoteException e) {
2449 // Ignore
2450 } finally {
2451 Binder.restoreCallingIdentity(ident);
2452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002453
Michael Chane96440f2009-05-06 10:27:36 -07002454 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002455 setPowerState(mUserState | mWakeLockState, noChangeLights,
2456 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002457 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 }
2459 }
2460 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002461
2462 if (mPolicy != null) {
2463 mPolicy.userActivity();
2464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 }
2466
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002467 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2468 try {
2469 int i;
2470 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2471 if (sensorValue < mAutoBrightnessLevels[i]) {
2472 break;
2473 }
2474 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002475 // This is the range of brightness values that we can use.
2476 final int minval = values[0];
2477 final int maxval = values[mAutoBrightnessLevels.length];
2478 // This is the range we will be scaling. We put some padding
2479 // at the low and high end to give the adjustment a little better
2480 // impact on the actual observed value.
2481 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION;
2482 // This is the desired brightness value from 0.0 to 1.0.
2483 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range);
2484 // Apply a scaling to the value based on the adjustment.
2485 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) {
2486 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting);
2487 if (adj <= .00001) {
2488 valf = 1;
2489 } else {
2490 valf /= adj;
2491 }
2492 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) {
2493 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting);
2494 valf *= adj;
2495 }
2496 // Apply an additional offset to the value based on the adjustment.
2497 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE;
2498 // Convert the 0.0-1.0 value back to a brightness integer.
2499 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2);
2500 if (val < minval) val = minval;
2501 else if (val > maxval) val = maxval;
2502 return val;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002503 } catch (Exception e) {
2504 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002505 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002506 return 255;
2507 }
2508 }
2509
Mike Lockwood20f87d72009-11-05 16:08:51 -05002510 private Runnable mProximityTask = new Runnable() {
2511 public void run() {
2512 synchronized (mLocks) {
2513 if (mProximityPendingValue != -1) {
2514 proximityChangedLocked(mProximityPendingValue == 1);
2515 mProximityPendingValue = -1;
2516 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002517 if (mProximityPartialLock.isHeld()) {
2518 mProximityPartialLock.release();
2519 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002520 }
2521 }
2522 };
2523
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002524 private Runnable mAutoBrightnessTask = new Runnable() {
2525 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002526 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002527 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2528 int value = (int)mLightSensorPendingValue;
2529 mLightSensorPendingDecrease = false;
2530 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002531 lightSensorChangedLocked(value, false);
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002532 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002533 }
2534 }
2535 };
2536
Jim Miller92e66dd2012-02-21 18:57:12 -08002537 private boolean mInitialAnimation; // used to prevent lightsensor changes while turning on
2538
Mike Lockwoodb2865412010-02-02 22:40:33 -05002539 private void dockStateChanged(int state) {
2540 synchronized (mLocks) {
2541 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2542 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002543 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002544 mHighestLightSensorValue = -1;
2545 }
2546 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2547 // force lights recalculation
2548 int value = (int)mLightSensorValue;
2549 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002550 lightSensorChangedLocked(value, false);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002551 }
2552 }
2553 }
2554
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002555 private void lightSensorChangedLocked(int value, boolean immediate) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002556 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002557 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002558 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002559
Joe Onorato06eb33a2010-10-25 14:09:21 -07002560 // Don't do anything if the screen is off.
2561 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2562 if (mDebugLightSensor) {
2563 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2564 }
2565 return;
2566 }
2567
Mike Lockwoodb2865412010-02-02 22:40:33 -05002568 // do not allow light sensor value to decrease
2569 if (mHighestLightSensorValue < value) {
2570 mHighestLightSensorValue = value;
2571 }
2572
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002573 if (mLightSensorValue != value) {
2574 mLightSensorValue = value;
2575 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002576 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2577 // we only do this if we are undocked, since lighting should be stable when
2578 // stationary in a dock.
2579 int lcdValue = getAutoBrightnessValue(
2580 (mIsDocked ? value : mHighestLightSensorValue),
2581 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002582 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002583 int keyboardValue;
2584 if (mKeyboardVisible) {
2585 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2586 } else {
2587 keyboardValue = 0;
2588 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002589 mLightSensorScreenBrightness = lcdValue;
2590 mLightSensorButtonBrightness = buttonValue;
2591 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002592
2593 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002594 Slog.d(TAG, "lcdValue " + lcdValue);
2595 Slog.d(TAG, "buttonValue " + buttonValue);
2596 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002597 }
2598
Mike Lockwood4984e732009-11-01 08:16:33 -05002599 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002600 if (!mSkippedScreenOn && !mInitialAnimation) {
2601 int steps = immediate ? IMMEDIATE_ANIM_STEPS : AUTOBRIGHTNESS_ANIM_STEPS;
2602 mScreenBrightnessAnimator.cancelAnimation();
2603 mScreenBrightnessAnimator.animateTo(lcdValue,
2604 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002605 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002606 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002607 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002608 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002609 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002610 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002611 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002612 }
2613 }
2614 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002615 }
2616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 /**
2618 * The user requested that we go to sleep (probably with the power button).
2619 * This overrides all wake locks that are held.
2620 */
2621 public void goToSleep(long time)
2622 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002623 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2624 }
2625
2626 /**
2627 * The user requested that we go to sleep (probably with the power button).
2628 * This overrides all wake locks that are held.
2629 */
2630 public void goToSleepWithReason(long time, int reason)
2631 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2633 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002634 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 }
2636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002639 * Reboot the device immediately, passing 'reason' (may be null)
2640 * to the underlying __reboot system call. Should not return.
2641 */
2642 public void reboot(String reason)
2643 {
2644 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002645
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002646 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2647 throw new IllegalStateException("Too early to call reboot()");
2648 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002649
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002650 final String finalReason = reason;
2651 Runnable runnable = new Runnable() {
2652 public void run() {
2653 synchronized (this) {
2654 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002655 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002656
San Mehat1e512792010-01-07 10:40:29 -08002657 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002658 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002659 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002660 mHandler.post(runnable);
2661
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002662 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002663 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002664 while (true) {
2665 try {
2666 runnable.wait();
2667 } catch (InterruptedException e) {
2668 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002669 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002670 }
2671 }
2672
Dan Egnor60d87622009-12-16 16:32:58 -08002673 /**
2674 * Crash the runtime (causing a complete restart of the Android framework).
2675 * Requires REBOOT permission. Mostly for testing. Should not return.
2676 */
2677 public void crash(final String message)
2678 {
2679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2680 Thread t = new Thread("PowerManagerService.crash()") {
2681 public void run() { throw new RuntimeException(message); }
2682 };
2683 try {
2684 t.start();
2685 t.join();
2686 } catch (InterruptedException e) {
2687 Log.wtf(TAG, e);
2688 }
2689 }
2690
Mike Lockwood435eb642009-12-03 08:40:18 -05002691 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692
2693 if (mLastEventTime <= time) {
2694 mLastEventTime = time;
2695 // cancel all of the wake locks
2696 mWakeLockState = SCREEN_OFF;
2697 int N = mLocks.size();
2698 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002699 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 for (int i=0; i<N; i++) {
2701 WakeLock wl = mLocks.get(i);
2702 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002703 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2704 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2705 proxLock = true;
2706 } else {
2707 mLocks.get(i).activated = false;
2708 numCleared++;
2709 }
2710 }
2711 }
2712 if (!proxLock) {
2713 mProxIgnoredBecauseScreenTurnedOff = true;
2714 if (mDebugProximitySensor) {
2715 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002718 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002719 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002721 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 cancelTimerLocked();
2723 }
2724 }
2725
2726 public long timeSinceScreenOn() {
2727 synchronized (mLocks) {
2728 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2729 return 0;
2730 }
2731 return SystemClock.elapsedRealtime() - mScreenOffTime;
2732 }
2733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002736 synchronized (mLocks) {
2737 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002738 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002739 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002740 if (mKeyboardVisible != visible) {
2741 mKeyboardVisible = visible;
2742 // don't signal user activity if the screen is off; other code
2743 // will take care of turning on due to a true change to the lid
2744 // switch and synchronized with the lock screen.
2745 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002746 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002747 // force recompute of backlight values
2748 if (mLightSensorValue >= 0) {
2749 int value = (int)mLightSensorValue;
2750 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002751 lightSensorChangedLocked(value, false);
Mike Lockwooddf024922009-10-29 21:29:15 -04002752 }
2753 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002754 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2755 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002756 }
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759
2760 /**
2761 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002762 * When disabling user activity we also reset user power state so the keyguard can reset its
2763 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 */
2765 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002766 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002767 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 synchronized (mLocks) {
2770 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002771 if (!enabled) {
2772 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2773 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 }
2776 }
2777
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002778 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002779 synchronized (mLocks) {
2780 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2781 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2782 mAutoBrightessEnabled = enabled;
2783 // This will get us a new value
2784 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002785 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002786 }
2787 }
2788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 /** Sets the screen off timeouts:
2790 * mKeylightDelay
2791 * mDimDelay
2792 * mScreenOffDelay
2793 * */
2794 private void setScreenOffTimeoutsLocked() {
2795 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002796 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 mDimDelay = -1;
2798 mScreenOffDelay = 0;
2799 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2800 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2801 mDimDelay = -1;
2802 mScreenOffDelay = 0;
2803 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002804 int totalDelay = mScreenOffTimeoutSetting;
2805 if (totalDelay > mMaximumScreenOffTimeout) {
2806 totalDelay = mMaximumScreenOffTimeout;
2807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2809 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002810 // negative number means stay on as long as possible.
2811 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 } else if (mKeylightDelay < totalDelay) {
2813 // subtract the time that the keylight delay. This will give us the
2814 // remainder of the time that we need to sleep to get the accurate
2815 // screen off timeout.
2816 mScreenOffDelay = totalDelay - mKeylightDelay;
2817 } else {
2818 mScreenOffDelay = 0;
2819 }
2820 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2821 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2822 mScreenOffDelay = LONG_DIM_TIME;
2823 } else {
2824 mDimDelay = -1;
2825 }
2826 }
2827 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002828 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2830 + " mDimScreen=" + mDimScreen);
2831 }
2832 }
2833
2834 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002835 * Refreshes cached secure settings. Called once on startup, and
2836 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 */
Doug Zongker43866e02010-01-07 12:09:54 -08002838 private void updateSettingsValues() {
2839 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002841 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002843 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
2845
2846 private class LockList extends ArrayList<WakeLock>
2847 {
2848 void addLock(WakeLock wl)
2849 {
2850 int index = getIndex(wl.binder);
2851 if (index < 0) {
2852 this.add(wl);
2853 }
2854 }
2855
2856 WakeLock removeLock(IBinder binder)
2857 {
2858 int index = getIndex(binder);
2859 if (index >= 0) {
2860 return this.remove(index);
2861 } else {
2862 return null;
2863 }
2864 }
2865
2866 int getIndex(IBinder binder)
2867 {
2868 int N = this.size();
2869 for (int i=0; i<N; i++) {
2870 if (this.get(i).binder == binder) {
2871 return i;
2872 }
2873 }
2874 return -1;
2875 }
2876
2877 int gatherState()
2878 {
2879 int result = 0;
2880 int N = this.size();
2881 for (int i=0; i<N; i++) {
2882 WakeLock wl = this.get(i);
2883 if (wl.activated) {
2884 if (isScreenLock(wl.flags)) {
2885 result |= wl.minState;
2886 }
2887 }
2888 }
2889 return result;
2890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002891
Michael Chane96440f2009-05-06 10:27:36 -07002892 int reactivateScreenLocksLocked()
2893 {
2894 int result = 0;
2895 int N = this.size();
2896 for (int i=0; i<N; i++) {
2897 WakeLock wl = this.get(i);
2898 if (isScreenLock(wl.flags)) {
2899 wl.activated = true;
2900 result |= wl.minState;
2901 }
2902 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002903 if (mDebugProximitySensor) {
2904 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2905 + mProxIgnoredBecauseScreenTurnedOff);
2906 }
2907 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002908 return result;
2909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 }
2911
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002912 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 synchronized (mLocks) {
2914 mPolicy = p;
2915 mLocks.notifyAll();
2916 }
2917 }
2918
2919 WindowManagerPolicy getPolicyLocked() {
2920 while (mPolicy == null || !mDoneBooting) {
2921 try {
2922 mLocks.wait();
2923 } catch (InterruptedException e) {
2924 // Ignore
2925 }
2926 }
2927 return mPolicy;
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002931 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2932 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2933 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002934 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002935 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002936 }
2937
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002938 // wait until sensors are enabled before turning on screen.
2939 // some devices will not activate the light sensor properly on boot
2940 // unless we do this.
2941 if (mUseSoftwareAutoBrightness) {
2942 // turn the screen on
2943 setPowerState(SCREEN_BRIGHT);
2944 } else {
2945 // turn everything on
2946 setPowerState(ALL_BRIGHT);
2947 }
2948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002950 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002952
Joe Onoratod28f7532010-11-06 12:56:53 -07002953 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2954
Dianne Hackborn617f8772009-03-31 15:04:46 -07002955 long identity = Binder.clearCallingIdentity();
2956 try {
2957 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2958 mBatteryStats.noteScreenOn();
2959 } catch (RemoteException e) {
2960 // Nothing interesting to do.
2961 } finally {
2962 Binder.restoreCallingIdentity(identity);
2963 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002964 }
2965 }
2966
2967 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002969 synchronized (mLocks) {
2970 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2972 updateWakeLockLocked();
2973 mLocks.notifyAll();
2974 }
2975 }
2976
Joe Onoratob08a1af2010-10-11 19:28:58 -07002977 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 public void monitor() {
2979 synchronized (mLocks) { }
2980 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002981
2982 public int getSupportedWakeLockFlags() {
2983 int result = PowerManager.PARTIAL_WAKE_LOCK
2984 | PowerManager.FULL_WAKE_LOCK
2985 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2986
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002987 if (mProximitySensor != null) {
2988 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2989 }
2990
2991 return result;
2992 }
2993
Mike Lockwood237a2992009-09-15 14:42:16 -04002994 public void setBacklightBrightness(int brightness) {
2995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2996 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002997 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002998 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002999 mLcdLight.setBrightness(brightness);
3000 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
3001 mButtonLight.setBrightness(brightness);
3002 long identity = Binder.clearCallingIdentity();
3003 try {
3004 mBatteryStats.noteScreenBrightness(brightness);
3005 } catch (RemoteException e) {
3006 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
3007 } finally {
3008 Binder.restoreCallingIdentity(identity);
3009 }
Jim Miller92e66dd2012-02-21 18:57:12 -08003010 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003011 }
3012 }
3013
3014 public void setAutoBrightnessAdjustment(float adj) {
3015 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3016 synchronized (mLocks) {
3017 mLightSensorAdjustSetting = adj;
3018 if (mSensorManager != null && mLightSensorEnabled) {
3019 // clear calling identity so sensor manager battery stats are accurate
3020 long identity = Binder.clearCallingIdentity();
3021 try {
3022 // force recompute of backlight values
3023 if (mLightSensorValue >= 0) {
3024 int value = (int)mLightSensorValue;
3025 mLightSensorValue = -1;
3026 handleLightSensorValue(value, true);
3027 }
3028 } finally {
3029 Binder.restoreCallingIdentity(identity);
3030 }
Joe Onorato3d3db602010-10-18 16:08:16 -04003031 }
Mike Lockwood237a2992009-09-15 14:42:16 -04003032 }
3033 }
3034
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003035 public void setAttentionLight(boolean on, int color) {
3036 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05003037 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003038 }
3039
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003040 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003041 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003042 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003043 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003044 if (!mProximitySensorEnabled) {
3045 // clear calling identity so sensor manager battery stats are accurate
3046 long identity = Binder.clearCallingIdentity();
3047 try {
3048 mSensorManager.registerListener(mProximityListener, mProximitySensor,
3049 SensorManager.SENSOR_DELAY_NORMAL);
3050 mProximitySensorEnabled = true;
3051 } finally {
3052 Binder.restoreCallingIdentity(identity);
3053 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003054 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003055 }
3056
3057 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003058 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003059 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003060 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003061 if (mProximitySensorEnabled) {
3062 // clear calling identity so sensor manager battery stats are accurate
3063 long identity = Binder.clearCallingIdentity();
3064 try {
3065 mSensorManager.unregisterListener(mProximityListener);
3066 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003067 if (mProximityPartialLock.isHeld()) {
3068 mProximityPartialLock.release();
3069 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003070 mProximitySensorEnabled = false;
3071 } finally {
3072 Binder.restoreCallingIdentity(identity);
3073 }
3074 if (mProximitySensorActive) {
3075 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003076 if (mDebugProximitySensor) {
3077 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
3078 + mProxIgnoredBecauseScreenTurnedOff);
3079 }
3080 if (!mProxIgnoredBecauseScreenTurnedOff) {
3081 forceUserActivityLocked();
3082 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003083 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003084 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003085 }
3086
Mike Lockwood20f87d72009-11-05 16:08:51 -05003087 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003088 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003089 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003090 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003091 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003092 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003093 return;
3094 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003095 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003096 if (mDebugProximitySensor) {
3097 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3098 + mProxIgnoredBecauseScreenTurnedOff);
3099 }
3100 if (!mProxIgnoredBecauseScreenTurnedOff) {
3101 goToSleepLocked(SystemClock.uptimeMillis(),
3102 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3103 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003104 mProximitySensorActive = true;
3105 } else {
3106 // proximity sensor negative events trigger as user activity.
3107 // temporarily set mUserActivityAllowed to true so this will work
3108 // even when the keyguard is on.
3109 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003110 if (mDebugProximitySensor) {
3111 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3112 + mProxIgnoredBecauseScreenTurnedOff);
3113 }
3114 if (!mProxIgnoredBecauseScreenTurnedOff) {
3115 forceUserActivityLocked();
3116 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003117
3118 if (mProximityWakeLockCount == 0) {
3119 // disable sensor if we have no listeners left after proximity negative
3120 disableProximityLockLocked();
3121 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003122 }
3123 }
3124
Joe Onoratod28f7532010-11-06 12:56:53 -07003125 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003126 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003127 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3128 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3129 }
3130 if (!mAutoBrightessEnabled) {
3131 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003132 }
3133 if (mSensorManager != null && mLightSensorEnabled != enable) {
3134 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003135 // clear calling identity so sensor manager battery stats are accurate
3136 long identity = Binder.clearCallingIdentity();
3137 try {
3138 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003139 // reset our highest value when reenabling
3140 mHighestLightSensorValue = -1;
3141 // force recompute of backlight values
3142 if (mLightSensorValue >= 0) {
3143 int value = (int)mLightSensorValue;
3144 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003145 handleLightSensorValue(value, true);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003146 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003147 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003148 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003149 } else {
3150 mSensorManager.unregisterListener(mLightListener);
3151 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003152 mLightSensorPendingDecrease = false;
3153 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003154 }
3155 } finally {
3156 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003157 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003158 }
3159 }
3160
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003161 SensorEventListener mProximityListener = new SensorEventListener() {
3162 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003163 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003164 synchronized (mLocks) {
3165 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003166 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3167 mLastProximityEventTime = milliseconds;
3168 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003169 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003170
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003171 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003172 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3173 distance < mProximitySensor.getMaximumRange());
3174
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003175 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003176 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003177 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003178 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3179 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3180 mProximityPendingValue = (active ? 1 : 0);
3181 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003182 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003183 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003184 // process the value immediately
3185 mProximityPendingValue = -1;
3186 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003187 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003188
3189 // update mProximityPartialLock state
3190 boolean held = mProximityPartialLock.isHeld();
3191 if (!held && proximityTaskQueued) {
3192 // hold wakelock until mProximityTask runs
3193 mProximityPartialLock.acquire();
3194 } else if (held && !proximityTaskQueued) {
3195 mProximityPartialLock.release();
3196 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003197 }
3198 }
3199
3200 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3201 // ignore
3202 }
3203 };
3204
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003205 private void handleLightSensorValue(int value, boolean immediate) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003206 long milliseconds = SystemClock.elapsedRealtime();
3207 if (mLightSensorValue == -1 ||
3208 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3209 // process the value immediately if screen has just turned on
3210 mHandler.removeCallbacks(mAutoBrightnessTask);
3211 mLightSensorPendingDecrease = false;
3212 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003213 lightSensorChangedLocked(value, immediate);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003214 } else {
3215 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3216 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3217 (value == mLightSensorValue) ||
3218 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3219 // delay processing to debounce the sensor
3220 mHandler.removeCallbacks(mAutoBrightnessTask);
3221 mLightSensorPendingDecrease = (value < mLightSensorValue);
3222 mLightSensorPendingIncrease = (value > mLightSensorValue);
3223 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3224 mLightSensorPendingValue = value;
3225 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3226 }
3227 } else {
3228 mLightSensorPendingValue = value;
3229 }
3230 }
3231 }
3232
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003233 SensorEventListener mLightListener = new SensorEventListener() {
3234 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003235 if (mDebugLightSensor) {
3236 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3237 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003238 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003239 // ignore light sensor while screen is turning off
3240 if (isScreenTurningOffLocked()) {
3241 return;
3242 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003243 handleLightSensorValue((int)event.values[0], false);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003244 }
3245 }
3246
3247 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3248 // ignore
3249 }
3250 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251}