blob: 5c047c490e0ce9f61472b80259dec8b33fd5ca8a [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();
583 synchronized (mLocks) {
584 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700585 // We make sure to start out with the screen on due to user activity.
586 // (They did just boot their device, after all.)
587 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700588 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 void initInThread() {
593 mHandler = new Handler();
594
595 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700596 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
598 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
599 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
600 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
601 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
602 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500603 mProximityPartialLock = new UnsynchronizedWakeLock(
604 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605
606 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
607 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
608 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
609 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
610
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700611 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400612
Joe Onoratob08a1af2010-10-11 19:28:58 -0700613 mAnimateScreenLights = resources.getBoolean(
614 com.android.internal.R.bool.config_animateScreenLights);
615
Joe Onorato6d747652010-10-11 15:15:31 -0700616 mUnplugTurnsOnScreen = resources.getBoolean(
617 com.android.internal.R.bool.config_unplugTurnsOnScreen);
618
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400619 mScreenBrightnessDim = resources.getInteger(
620 com.android.internal.R.integer.config_screenBrightnessDim);
621
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400622 // read settings for auto-brightness
623 mUseSoftwareAutoBrightness = resources.getBoolean(
624 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400625 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700626 mAutoBrightnessLevels = resources.getIntArray(
627 com.android.internal.R.array.config_autoBrightnessLevels);
628 mLcdBacklightValues = resources.getIntArray(
629 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
630 mButtonBacklightValues = resources.getIntArray(
631 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
632 mKeyboardBacklightValues = resources.getIntArray(
633 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500634 mLightSensorWarmupTime = resources.getInteger(
635 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700636 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700637
638 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
640 "(" + Settings.System.NAME + "=?) or ("
641 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700642 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700643 + Settings.System.NAME + "=?) or ("
644 + Settings.System.NAME + "=?) or ("
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800645 + Settings.System.NAME + "=?) or ("
646 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 + Settings.System.NAME + "=?)",
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800648 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS,
649 SCREEN_BRIGHTNESS_MODE, SCREEN_AUTO_BRIGHTNESS_ADJ,
650 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 null);
652 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
653 SettingsObserver settingsObserver = new SettingsObserver();
654 mSettings.addObserver(settingsObserver);
655
656 // pretend that the settings changed so we will get their initial state
657 settingsObserver.update(mSettings, null);
658
659 // register for the battery changed notifications
660 IntentFilter filter = new IntentFilter();
661 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
662 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500663 filter = new IntentFilter();
664 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
665 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500666 filter = new IntentFilter();
667 filter.addAction(Intent.ACTION_DOCK_EVENT);
668 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669
Doug Zongker43866e02010-01-07 12:09:54 -0800670 // Listen for secure settings changes
671 mContext.getContentResolver().registerContentObserver(
672 Settings.Secure.CONTENT_URI, true,
673 new ContentObserver(new Handler()) {
674 public void onChange(boolean selfChange) {
675 updateSettingsValues();
676 }
677 });
678 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 synchronized (mHandlerThread) {
681 mInitComplete = true;
682 mHandlerThread.notifyAll();
683 }
684 }
685
686 private class WakeLock implements IBinder.DeathRecipient
687 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700688 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 super();
690 flags = f;
691 binder = b;
692 tag = t;
693 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (u != MY_UID || (
696 !"KEEP_SCREEN_ON_FLAG".equals(tag)
697 && !"KeyInputQueue".equals(tag))) {
698 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
699 ? BatteryStats.WAKE_TYPE_PARTIAL
700 : BatteryStats.WAKE_TYPE_FULL;
701 } else {
702 monitorType = -1;
703 }
704 try {
705 b.linkToDeath(this, 0);
706 } catch (RemoteException e) {
707 binderDied();
708 }
709 }
710 public void binderDied() {
711 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500712 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714 }
715 final int flags;
716 final IBinder binder;
717 final String tag;
718 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400719 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700721 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 boolean activated = true;
723 int minState;
724 }
725
726 private void updateWakeLockLocked() {
727 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
728 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
729 mStayOnWhilePluggedInScreenDimLock.acquire();
730 mStayOnWhilePluggedInPartialLock.acquire();
731 } else {
732 mStayOnWhilePluggedInScreenDimLock.release();
733 mStayOnWhilePluggedInPartialLock.release();
734 }
735 }
736
737 private boolean isScreenLock(int flags)
738 {
739 int n = flags & LOCK_MASK;
740 return n == PowerManager.FULL_WAKE_LOCK
741 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400742 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
743 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 }
745
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700746 void enforceWakeSourcePermission(int uid, int pid) {
747 if (uid == Process.myUid()) {
748 return;
749 }
750 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
751 pid, uid, null);
752 }
753
754 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700756 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700757 if (uid != Process.myUid()) {
758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
759 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700760 if (ws != null) {
761 enforceWakeSourcePermission(uid, pid);
762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 long ident = Binder.clearCallingIdentity();
764 try {
765 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700766 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 }
768 } finally {
769 Binder.restoreCallingIdentity(ident);
770 }
771 }
772
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700773 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700774 if (wl.monitorType >= 0) {
775 long origId = Binder.clearCallingIdentity();
776 try {
777 if (ws != null) {
778 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
779 wl.monitorType);
780 } else {
781 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
782 }
783 } catch (RemoteException e) {
784 // Ignore
785 } finally {
786 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700787 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700788 }
789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700791 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700792 if (wl.monitorType >= 0) {
793 long origId = Binder.clearCallingIdentity();
794 try {
795 if (ws != null) {
796 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
797 wl.monitorType);
798 } else {
799 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
800 }
801 } catch (RemoteException e) {
802 // Ignore
803 } finally {
804 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700805 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700806 }
807 }
808
809 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
810 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800812 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 }
814
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700815 if (ws != null && ws.size() == 0) {
816 ws = null;
817 }
818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 int index = mLocks.getIndex(lock);
820 WakeLock wl;
821 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700822 boolean diffsource;
823 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700825 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 switch (wl.flags & LOCK_MASK)
827 {
828 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500829 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400830 wl.minState = SCREEN_BRIGHT;
831 } else {
832 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 break;
835 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
836 wl.minState = SCREEN_BRIGHT;
837 break;
838 case PowerManager.SCREEN_DIM_WAKE_LOCK:
839 wl.minState = SCREEN_DIM;
840 break;
841 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700842 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 break;
844 default:
845 // just log and bail. we're in the server, so don't
846 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800847 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 + " flags=" + flags);
849 return;
850 }
851 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700852 if (ws != null) {
853 wl.ws = new WorkSource(ws);
854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700856 diffsource = false;
857 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 } else {
859 wl = mLocks.get(index);
860 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700861 oldsource = wl.ws;
862 if (oldsource != null) {
863 if (ws == null) {
864 wl.ws = null;
865 diffsource = true;
866 } else {
867 diffsource = oldsource.diff(ws);
868 }
869 } else if (ws != null) {
870 diffsource = true;
871 } else {
872 diffsource = false;
873 }
874 if (diffsource) {
875 wl.ws = new WorkSource(ws);
876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878 if (isScreenLock(flags)) {
879 // if this causes a wakeup, we reactivate all of the locks and
880 // set it to whatever they want. otherwise, we modulate that
881 // by the current state so we never turn it more on than
882 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400883 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
884 mProximityWakeLockCount++;
885 if (mProximityWakeLockCount == 1) {
886 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400889 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
890 int oldWakeLockState = mWakeLockState;
891 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400892
893 // Disable proximity sensor if if user presses power key while we are in the
894 // "waiting for proximity sensor to go negative" state.
895 if ((mWakeLockState & SCREEN_ON_BIT) != 0
896 && mProximitySensorActive && mProximityWakeLockCount == 0) {
897 mProximitySensorActive = false;
898 }
899
Joe Onorato8274a0e2010-10-05 17:38:09 -0400900 if (mSpew) {
901 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
902 + " mWakeLockState=0x"
903 + Integer.toHexString(mWakeLockState)
904 + " previous wakeLockState=0x"
905 + Integer.toHexString(oldWakeLockState));
906 }
907 } else {
908 if (mSpew) {
909 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
910 + " mLocks.gatherState()=0x"
911 + Integer.toHexString(mLocks.gatherState())
912 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
913 }
914 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400916 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
920 if (newlock) {
921 mPartialCount++;
922 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800923 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
925 }
926 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700929 if (diffsource) {
930 // If the lock sources have changed, need to first release the
931 // old ones.
932 noteStopWakeLocked(wl, oldsource);
933 }
934 if (newlock || diffsource) {
935 noteStartWakeLocked(wl, ws);
936 }
937 }
938
939 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
940 int uid = Binder.getCallingUid();
941 int pid = Binder.getCallingPid();
942 if (ws != null && ws.size() == 0) {
943 ws = null;
944 }
945 if (ws != null) {
946 enforceWakeSourcePermission(uid, pid);
947 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700948 synchronized (mLocks) {
949 int index = mLocks.getIndex(lock);
950 if (index < 0) {
951 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700953 WakeLock wl = mLocks.get(index);
954 WorkSource oldsource = wl.ws;
955 wl.ws = ws != null ? new WorkSource(ws) : null;
956 noteStopWakeLocked(wl, oldsource);
957 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 }
960
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500961 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700962 int uid = Binder.getCallingUid();
963 if (uid != Process.myUid()) {
964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
967 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500968 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970 }
971
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500972 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 WakeLock wl = mLocks.removeLock(lock);
974 if (wl == null) {
975 return;
976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800979 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
981 }
982
983 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400984 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
985 mProximityWakeLockCount--;
986 if (mProximityWakeLockCount == 0) {
987 if (mProximitySensorActive &&
988 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
989 // wait for proximity sensor to go negative before disabling sensor
990 if (mDebugProximitySensor) {
991 Slog.d(TAG, "waiting for proximity sensor to go negative");
992 }
993 } else {
994 disableProximityLockLocked();
995 }
996 }
997 } else {
998 mWakeLockState = mLocks.gatherState();
999 // goes in the middle to reduce flicker
1000 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
1001 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
1002 }
1003 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
1007 mPartialCount--;
1008 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001009 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 Power.releaseWakeLock(PARTIAL_NAME);
1011 }
1012 }
1013 // Unlink the lock from the binder.
1014 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
Dianne Hackborn70be1672010-09-14 11:13:03 -07001016 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 private class PokeLock implements IBinder.DeathRecipient
1020 {
1021 PokeLock(int p, IBinder b, String t) {
1022 super();
1023 this.pokey = p;
1024 this.binder = b;
1025 this.tag = t;
1026 try {
1027 b.linkToDeath(this, 0);
1028 } catch (RemoteException e) {
1029 binderDied();
1030 }
1031 }
1032 public void binderDied() {
1033 setPokeLock(0, this.binder, this.tag);
1034 }
1035 int pokey;
1036 IBinder binder;
1037 String tag;
1038 boolean awakeOnSet;
1039 }
1040
1041 public void setPokeLock(int pokey, IBinder token, String tag) {
1042 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1043 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001044 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 return;
1046 }
1047
1048 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1049 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1050 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1051 }
1052
1053 synchronized (mLocks) {
1054 if (pokey != 0) {
1055 PokeLock p = mPokeLocks.get(token);
1056 int oldPokey = 0;
1057 if (p != null) {
1058 oldPokey = p.pokey;
1059 p.pokey = pokey;
1060 } else {
1061 p = new PokeLock(pokey, token, tag);
1062 mPokeLocks.put(token, p);
1063 }
1064 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1065 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1066 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1067 p.awakeOnSet = true;
1068 }
1069 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001070 PokeLock rLock = mPokeLocks.remove(token);
1071 if (rLock != null) {
1072 token.unlinkToDeath(rLock, 0);
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
1076 int oldPokey = mPokey;
1077 int cumulative = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 boolean awakeOnSet = false;
1079 for (PokeLock p: mPokeLocks.values()) {
1080 cumulative |= p.pokey;
1081 if (p.awakeOnSet) {
1082 awakeOnSet = true;
1083 }
1084 }
1085 mPokey = cumulative;
1086 mPokeAwakeOnSet = awakeOnSet;
1087
1088 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1089 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 if (oldCumulativeTimeout != newCumulativeTimeout) {
1092 setScreenOffTimeoutsLocked();
1093 // reset the countdown timer, but use the existing nextState so it doesn't
1094 // change anything
1095 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1096 }
1097 }
1098 }
1099
1100 private static String lockType(int type)
1101 {
1102 switch (type)
1103 {
1104 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001105 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001107 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001109 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001111 return "PARTIAL_WAKE_LOCK ";
1112 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1113 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 default:
David Brown251faa62009-08-02 22:04:36 -07001115 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117 }
1118
1119 private static String dumpPowerState(int state) {
1120 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1121 ? "KEYBOARD_BRIGHT_BIT " : "")
1122 + (((state & SCREEN_BRIGHT_BIT) != 0)
1123 ? "SCREEN_BRIGHT_BIT " : "")
1124 + (((state & SCREEN_ON_BIT) != 0)
1125 ? "SCREEN_ON_BIT " : "")
1126 + (((state & BATTERY_LOW_BIT) != 0)
1127 ? "BATTERY_LOW_BIT " : "");
1128 }
1129
1130 @Override
1131 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1132 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1133 != PackageManager.PERMISSION_GRANTED) {
1134 pw.println("Permission Denial: can't dump PowerManager from from pid="
1135 + Binder.getCallingPid()
1136 + ", uid=" + Binder.getCallingUid());
1137 return;
1138 }
1139
1140 long now = SystemClock.uptimeMillis();
1141
Mike Lockwoodca44df82010-02-25 13:48:49 -05001142 synchronized (mLocks) {
1143 pw.println("Power Manager State:");
1144 pw.println(" mIsPowered=" + mIsPowered
1145 + " mPowerState=" + mPowerState
1146 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1147 + " ms");
1148 pw.println(" mPartialCount=" + mPartialCount);
1149 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1150 pw.println(" mUserState=" + dumpPowerState(mUserState));
1151 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1152 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1153 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1154 + " " + ((mNextTimeout-now)/1000) + "s from now");
1155 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001156 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001157 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1158 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001159 pw.println(" mScreenOffReason=" + mScreenOffReason
1160 + " mUserState=" + mUserState);
1161 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1162 + ',' + mBroadcastQueue[2] + "}");
1163 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1164 + ',' + mBroadcastWhy[2] + "}");
1165 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1166 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1167 + " mUserActivityAllowed=" + mUserActivityAllowed);
1168 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1169 + " mScreenOffDelay=" + mScreenOffDelay);
1170 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1171 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1172 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1173 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1174 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1175 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1176 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1177 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1178 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1179 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1180 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1181 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1182 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1183 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1184 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1185 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08001186 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled
1187 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001188 pw.println(" mLightSensorValue=" + mLightSensorValue
1189 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001190 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1191 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001192 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1193 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1194 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1195 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1196 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
Jim Miller92e66dd2012-02-21 18:57:12 -08001197 mScreenBrightnessAnimator.dump(pw, " mScreenBrightnessAnimator: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198
Mike Lockwoodca44df82010-02-25 13:48:49 -05001199 int N = mLocks.size();
1200 pw.println();
1201 pw.println("mLocks.size=" + N + ":");
1202 for (int i=0; i<N; i++) {
1203 WakeLock wl = mLocks.get(i);
1204 String type = lockType(wl.flags & LOCK_MASK);
1205 String acquireCausesWakeup = "";
1206 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1207 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1208 }
1209 String activated = "";
1210 if (wl.activated) {
1211 activated = " activated";
1212 }
1213 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001214 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1215 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001217
1218 pw.println();
1219 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1220 for (PokeLock p: mPokeLocks.values()) {
1221 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001222 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1223 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001224 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1225 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1226 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1227 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001229
Mike Lockwoodca44df82010-02-25 13:48:49 -05001230 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233
Joe Onorato7999bff2010-07-24 11:50:05 -04001234 private void setTimeoutLocked(long now, int nextState) {
1235 setTimeoutLocked(now, -1, nextState);
1236 }
1237
1238 // If they gave a timeoutOverride it is the number of seconds
1239 // to screen-off. Figure out where in the countdown cycle we
1240 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001241 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1242 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001243 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001244 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001245 long when = 0;
1246 if (timeoutOverride <= 0) {
1247 switch (nextState)
1248 {
1249 case SCREEN_BRIGHT:
1250 when = now + mKeylightDelay;
1251 break;
1252 case SCREEN_DIM:
1253 if (mDimDelay >= 0) {
1254 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001255 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001256 } else {
1257 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1258 }
1259 case SCREEN_OFF:
1260 synchronized (mLocks) {
1261 when = now + mScreenOffDelay;
1262 }
1263 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001264 default:
1265 when = now;
1266 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001268 } else {
1269 override: {
1270 if (timeoutOverride <= mScreenOffDelay) {
1271 when = now + timeoutOverride;
1272 nextState = SCREEN_OFF;
1273 break override;
1274 }
1275 timeoutOverride -= mScreenOffDelay;
1276
1277 if (mDimDelay >= 0) {
1278 if (timeoutOverride <= mDimDelay) {
1279 when = now + timeoutOverride;
1280 nextState = SCREEN_DIM;
1281 break override;
1282 }
1283 timeoutOverride -= mDimDelay;
1284 }
1285
1286 when = now + timeoutOverride;
1287 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001289 }
1290 if (mSpew) {
1291 Slog.d(TAG, "setTimeoutLocked now=" + now
1292 + " timeoutOverride=" + timeoutOverride
1293 + " nextState=" + nextState + " when=" + when);
1294 }
Joe Onorato797e6882010-08-26 14:46:01 -04001295
1296 mHandler.removeCallbacks(mTimeoutTask);
1297 mTimeoutTask.nextState = nextState;
1298 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1299 ? (originalTimeoutOverride - timeoutOverride)
1300 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001301 mHandler.postAtTime(mTimeoutTask, when);
1302 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 }
1306
1307 private void cancelTimerLocked()
1308 {
1309 mHandler.removeCallbacks(mTimeoutTask);
1310 mTimeoutTask.nextState = -1;
1311 }
1312
1313 private class TimeoutTask implements Runnable
1314 {
1315 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001316 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 public void run()
1318 {
1319 synchronized (mLocks) {
1320 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001321 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
1323
1324 if (nextState == -1) {
1325 return;
1326 }
1327
1328 mUserState = this.nextState;
1329 setPowerState(this.nextState | mWakeLockState);
1330
1331 long now = SystemClock.uptimeMillis();
1332
1333 switch (this.nextState)
1334 {
1335 case SCREEN_BRIGHT:
1336 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001337 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 break;
1339 }
1340 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001341 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 break;
1343 }
1344 }
1345 }
1346 }
1347
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001348 private void sendNotificationLocked(boolean on, int why) {
1349 if (!mInitialized) {
1350 // No notifications sent until first initialization is done.
1351 // This is so that when we are moving from our initial state
1352 // which looks like the screen was off to it being on, we do not
1353 // go through the process of waiting for the higher-level user
1354 // space to be ready before turning up the display brightness.
1355 // (And also do not send needless broadcasts about the screen.)
1356 return;
1357 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001358
1359 if (DEBUG_SCREEN_ON) {
1360 RuntimeException here = new RuntimeException("here");
1361 here.fillInStackTrace();
1362 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1363 }
1364
Joe Onorato64c62ba2009-03-24 20:13:57 -07001365 if (!on) {
1366 mStillNeedSleepNotification = false;
1367 }
1368
Joe Onorato128e7292009-03-24 18:41:31 -07001369 // Add to the queue.
1370 int index = 0;
1371 while (mBroadcastQueue[index] != -1) {
1372 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
Joe Onorato128e7292009-03-24 18:41:31 -07001374 mBroadcastQueue[index] = on ? 1 : 0;
1375 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
Joe Onorato128e7292009-03-24 18:41:31 -07001377 // If we added it position 2, then there is a pair that can be stripped.
1378 // If we added it position 1 and we're turning the screen off, we can strip
1379 // the pair and do nothing, because the screen is already off, and therefore
1380 // keyguard has already been enabled.
1381 // However, if we added it at position 1 and we're turning it on, then position
1382 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1383 // on, so have to run the queue then.
1384 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001385 // While we're collapsing them, if it's going off, and the new reason
1386 // is more significant than the first, then use the new one.
1387 if (!on && mBroadcastWhy[0] > why) {
1388 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001389 }
1390 mBroadcastQueue[0] = on ? 1 : 0;
1391 mBroadcastQueue[1] = -1;
1392 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001393 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001394 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001395 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001396 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001397 index = 0;
1398 }
1399 if (index == 1 && !on) {
1400 mBroadcastQueue[0] = -1;
1401 mBroadcastQueue[1] = -1;
1402 index = -1;
1403 // The wake lock was being held, but we're not actually going to do any
1404 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001405 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001407 }
1408
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001409 // The broadcast queue has changed; make sure the screen is on if it
1410 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001411 if (mSkippedScreenOn) {
1412 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1413 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001414
Joe Onorato128e7292009-03-24 18:41:31 -07001415 // Now send the message.
1416 if (index >= 0) {
1417 // Acquire the broadcast wake lock before changing the power
1418 // state. It will be release after the broadcast is sent.
1419 // We always increment the ref count for each notification in the queue
1420 // and always decrement when that notification is handled.
1421 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001422 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001423 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001427 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1428 new WindowManagerPolicy.ScreenOnListener() {
Jim Miller92e66dd2012-02-21 18:57:12 -08001429 public void onScreenOn() {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001430 synchronized (mLocks) {
1431 if (mPreparingForScreenOn) {
1432 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001433 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001434 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1435 4, mBroadcastWakeLock.mCount);
1436 mBroadcastWakeLock.release();
1437 }
1438 }
1439 }
1440 };
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 private Runnable mNotificationTask = new Runnable()
1443 {
1444 public void run()
1445 {
Joe Onorato128e7292009-03-24 18:41:31 -07001446 while (true) {
1447 int value;
1448 int why;
1449 WindowManagerPolicy policy;
1450 synchronized (mLocks) {
1451 value = mBroadcastQueue[0];
1452 why = mBroadcastWhy[0];
1453 for (int i=0; i<2; i++) {
1454 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1455 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1456 }
1457 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001458 if (value == 1 && !mPreparingForScreenOn) {
1459 mPreparingForScreenOn = true;
1460 mBroadcastWakeLock.acquire();
1461 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1462 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
Joe Onorato128e7292009-03-24 18:41:31 -07001465 if (value == 1) {
1466 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001467
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001468 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001469 try {
1470 ActivityManagerNative.getDefault().wakingUp();
1471 } catch (RemoteException e) {
1472 // ignore it
1473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
Joe Onorato128e7292009-03-24 18:41:31 -07001475 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001476 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001477 }
1478 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1479 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1480 mScreenOnBroadcastDone, mHandler, 0, null, null);
1481 } else {
1482 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001483 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001484 mBroadcastWakeLock.mCount);
1485 mBroadcastWakeLock.release();
1486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 }
Joe Onorato128e7292009-03-24 18:41:31 -07001489 else if (value == 0) {
1490 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491
Joe Onorato128e7292009-03-24 18:41:31 -07001492 policy.screenTurnedOff(why);
1493 try {
1494 ActivityManagerNative.getDefault().goingToSleep();
1495 } catch (RemoteException e) {
1496 // ignore it.
1497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498
Joe Onorato128e7292009-03-24 18:41:31 -07001499 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1500 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1501 mScreenOffBroadcastDone, mHandler, 0, null, null);
1502 } else {
1503 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001505 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001506 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001507 mBroadcastWakeLock.release();
1508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510 }
Joe Onorato128e7292009-03-24 18:41:31 -07001511 else {
1512 // If we're in this case, then this handler is running for a previous
1513 // paired transaction. mBroadcastWakeLock will already have been released.
1514 break;
1515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 }
1518 };
1519
1520 long mScreenOnStart;
1521 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1522 public void onReceive(Context context, Intent intent) {
1523 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1526 mBroadcastWakeLock.release();
1527 }
1528 }
1529 };
1530
1531 long mScreenOffStart;
1532 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1533 public void onReceive(Context context, Intent intent) {
1534 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001535 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1537 mBroadcastWakeLock.release();
1538 }
1539 }
1540 };
1541
1542 void logPointerUpEvent() {
1543 if (LOG_TOUCH_DOWNS) {
1544 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1545 mLastTouchDown = 0;
1546 }
1547 }
1548
1549 void logPointerDownEvent() {
1550 if (LOG_TOUCH_DOWNS) {
1551 // If we are not already timing a down/up sequence
1552 if (mLastTouchDown == 0) {
1553 mLastTouchDown = SystemClock.elapsedRealtime();
1554 mTouchCycles++;
1555 }
1556 }
1557 }
1558
1559 /**
1560 * Prevents the screen from turning on even if it *should* turn on due
1561 * to a subsequent full wake lock being acquired.
1562 * <p>
1563 * This is a temporary hack that allows an activity to "cover up" any
1564 * display glitches that happen during the activity's startup
1565 * sequence. (Specifically, this API was added to work around a
1566 * cosmetic bug in the "incoming call" sequence, where the lock screen
1567 * would flicker briefly before the incoming call UI became visible.)
1568 * TODO: There ought to be a more elegant way of doing this,
1569 * probably by having the PowerManager and ActivityManager
1570 * work together to let apps specify that the screen on/off
1571 * state should be synchronized with the Activity lifecycle.
1572 * <p>
1573 * Note that calling preventScreenOn(true) will NOT turn the screen
1574 * off if it's currently on. (This API only affects *future*
1575 * acquisitions of full wake locks.)
1576 * But calling preventScreenOn(false) WILL turn the screen on if
1577 * it's currently off because of a prior preventScreenOn(true) call.
1578 * <p>
1579 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1580 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1581 * call doesn't occur within 5 seconds, we'll turn the screen back on
1582 * ourselves (and log a warning about it); this prevents a buggy app
1583 * from disabling the screen forever.)
1584 * <p>
1585 * TODO: this feature should really be controlled by a new type of poke
1586 * lock (rather than an IPowerManager call).
1587 */
1588 public void preventScreenOn(boolean prevent) {
1589 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1590
1591 synchronized (mLocks) {
1592 if (prevent) {
1593 // First of all, grab a partial wake lock to
1594 // make sure the CPU stays on during the entire
1595 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1596 mPreventScreenOnPartialLock.acquire();
1597
1598 // Post a forceReenableScreen() call (for 5 seconds in the
1599 // future) to make sure the matching preventScreenOn(false) call
1600 // has happened by then.
1601 mHandler.removeCallbacks(mForceReenableScreenTask);
1602 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1603
1604 // Finally, set the flag that prevents the screen from turning on.
1605 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001606 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 mPreventScreenOn = true;
1608 } else {
1609 // (Re)enable the screen.
1610 mPreventScreenOn = false;
1611
1612 // We're "undoing" a the prior preventScreenOn(true) call, so we
1613 // no longer need the 5-second safeguard.
1614 mHandler.removeCallbacks(mForceReenableScreenTask);
1615
1616 // Forcibly turn on the screen if it's supposed to be on. (This
1617 // handles the case where the screen is currently off because of
1618 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001619 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1623 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001624 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001626 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628 }
1629
1630 // Release the partial wake lock that we held during the
1631 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1632 mPreventScreenOnPartialLock.release();
1633 }
1634 }
1635 }
1636
1637 public void setScreenBrightnessOverride(int brightness) {
1638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1639
Mike Lockwoodf527c712010-06-10 14:12:33 -04001640 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 synchronized (mLocks) {
1642 if (mScreenBrightnessOverride != brightness) {
1643 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001644 if (isScreenOn()) {
1645 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648 }
1649 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001650
1651 public void setButtonBrightnessOverride(int brightness) {
1652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1653
Mike Lockwoodf527c712010-06-10 14:12:33 -04001654 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001655 synchronized (mLocks) {
1656 if (mButtonBrightnessOverride != brightness) {
1657 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001658 if (isScreenOn()) {
1659 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1660 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001661 }
1662 }
1663 }
1664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 /**
1666 * Sanity-check that gets called 5 seconds after any call to
1667 * preventScreenOn(true). This ensures that the original call
1668 * is followed promptly by a call to preventScreenOn(false).
1669 */
1670 private void forceReenableScreen() {
1671 // We shouldn't get here at all if mPreventScreenOn is false, since
1672 // we should have already removed any existing
1673 // mForceReenableScreenTask messages...
1674 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001675 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 return;
1677 }
1678
1679 // Uh oh. It's been 5 seconds since a call to
1680 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1681 // This means the app that called preventScreenOn(true) is either
1682 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1683 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1684 // crashed before doing so.)
1685
1686 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001687 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 + "Forcing the screen back on...");
1689 preventScreenOn(false);
1690 }
1691
1692 private Runnable mForceReenableScreenTask = new Runnable() {
1693 public void run() {
1694 forceReenableScreen();
1695 }
1696 };
1697
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001698 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001699 if (DEBUG_SCREEN_ON) {
1700 RuntimeException e = new RuntimeException("here");
1701 e.fillInStackTrace();
1702 Slog.i(TAG, "Set screen state: " + on, e);
1703 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001704 if (on) {
1705 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1706 // If we are turning the screen state on, but the screen
1707 // light is currently off, then make sure that we set the
1708 // light at this point to 0. This is the case where we are
1709 // turning on the screen and waiting for the UI to be drawn
1710 // before showing it to the user. We want the light off
1711 // until it is ready to be shown to the user, not it using
1712 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001713 if (DEBUG_SCREEN_ON) {
1714 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1715 + Integer.toHexString(mPowerState)
1716 + " mSkippedScreenOn=" + mSkippedScreenOn);
1717 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001718 mScreenBrightnessAnimator.animateTo(Power.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
Dianne Hackborn474fd742011-10-10 18:40:22 -07001719 }
1720 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001721 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001722 if (err == 0) {
1723 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1724 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001725 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001726 if (!on) {
1727 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001728 mButtonLight.turnOff();
1729 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001730 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001731 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001732 }
1733 return err;
1734 }
1735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 private void setPowerState(int state)
1737 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001738 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
Mike Lockwood435eb642009-12-03 08:40:18 -05001741 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 {
1743 synchronized (mLocks) {
1744 int err;
1745
1746 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001747 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001749 + " noChangeLights=" + noChangeLights
1750 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
1752
1753 if (noChangeLights) {
1754 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1755 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001756 if (mProximitySensorActive) {
1757 // don't turn on the screen when the proximity sensor lock is held
1758 newState = (newState & ~SCREEN_BRIGHT);
1759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760
1761 if (batteryIsLow()) {
1762 newState |= BATTERY_LOW_BIT;
1763 } else {
1764 newState &= ~BATTERY_LOW_BIT;
1765 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001766 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 return;
1768 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001769
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001770 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 newState |= ALL_BRIGHT;
1772 }
1773
1774 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1775 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1776
Mike Lockwood51b844962009-11-16 21:51:18 -05001777 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001778 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001780 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001782 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001784 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001786 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001788 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1790 }
1791
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001792 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793
1794 if (oldScreenOn != newScreenOn) {
1795 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001796 // When the user presses the power button, we need to always send out the
1797 // notification that it's going to sleep so the keyguard goes on. But
1798 // we can't do that until the screen fades out, so we don't show the keyguard
1799 // too early.
1800 if (mStillNeedSleepNotification) {
1801 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1802 }
1803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 // Turn on the screen UNLESS there was a prior
1805 // preventScreenOn(true) request. (Note that the lifetime
1806 // of a single preventScreenOn() request is limited to 5
1807 // seconds to prevent a buggy app from disabling the
1808 // screen forever; see forceReenableScreen().)
1809 boolean reallyTurnScreenOn = true;
1810 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001811 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 + mPreventScreenOn);
1813 }
1814
1815 if (mPreventScreenOn) {
1816 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001817 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
1819 reallyTurnScreenOn = false;
1820 }
1821 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001822 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 long identity = Binder.clearCallingIdentity();
1824 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001825 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 mBatteryStats.noteScreenOn();
1827 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001828 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 } finally {
1830 Binder.restoreCallingIdentity(identity);
1831 }
1832 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001833 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 // But continue as if we really did turn the screen on...
1835 err = 0;
1836 }
1837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 mLastTouchDown = 0;
1839 mTotalTouchDownTime = 0;
1840 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001841 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 mTotalTouchDownTime, mTouchCycles);
1843 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001845 // Update the lights *after* taking care of turning the
1846 // screen on, so we do this after our notifications are
1847 // enqueued and thus will delay turning on the screen light
1848 // until the windows are correctly displayed.
1849 if (stateChanged) {
1850 updateLightsLocked(newState, 0);
1851 }
1852 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001856 // Update the lights *before* taking care of turning the
1857 // screen off, so we can initiate any animations that are desired.
1858 if (stateChanged) {
1859 updateLightsLocked(newState, 0);
1860 }
1861
Mike Lockwood497087e32009-11-08 18:33:03 -05001862 // cancel light sensor task
1863 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001864 mLightSensorPendingDecrease = false;
1865 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 mScreenOffTime = SystemClock.elapsedRealtime();
1867 long identity = Binder.clearCallingIdentity();
1868 try {
1869 mBatteryStats.noteScreenOff();
1870 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001871 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 } finally {
1873 Binder.restoreCallingIdentity(identity);
1874 }
1875 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001876 mScreenOffReason = reason;
Jim Miller92e66dd2012-02-21 18:57:12 -08001877 if (!mScreenBrightnessAnimator.isAnimating()) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001878 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 err = 0;
1881 mLastTouchDown = 0;
1882 }
1883 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001884 } else if (stateChanged) {
1885 // Screen on/off didn't change, but lights may have.
1886 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001888
1889 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1890
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001891 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001894
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001895 private void updateNativePowerStateLocked() {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001896 if (!mHeadless) {
1897 nativeSetPowerState(
1898 (mPowerState & SCREEN_ON_BIT) != 0,
1899 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1900 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001902
Mike Lockwood435eb642009-12-03 08:40:18 -05001903 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001905 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001907 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1908 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001910 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001912 mScreenOffReason = reason;
1913 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
1915 return err;
1916 }
1917
1918 private boolean batteryIsLow() {
1919 return (!mIsPowered &&
1920 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1921 }
1922
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001923 private boolean shouldDeferScreenOnLocked() {
1924 if (mPreparingForScreenOn) {
1925 // Currently waiting for confirmation from the policy that it
1926 // is okay to turn on the screen. Don't allow the screen to go
1927 // on until that is done.
1928 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1929 "updateLights: delaying screen on due to mPreparingForScreenOn");
1930 return true;
1931 } else {
1932 // If there is a screen-on command in the notification queue, we
1933 // can't turn the screen on until it has been processed (and we
1934 // have set mPreparingForScreenOn) or it has been dropped.
1935 for (int i=0; i<mBroadcastQueue.length; i++) {
1936 if (mBroadcastQueue[i] == 1) {
1937 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1938 "updateLights: delaying screen on due to notification queue");
1939 return true;
1940 }
1941 }
1942 }
1943 return false;
1944 }
1945
The Android Open Source Project10592532009-03-18 17:39:46 -07001946 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001947 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001948
1949 // If the screen is not currently on, we will want to delay actually
1950 // turning the lights on if we are still getting the UI put up.
Jim Miller92e66dd2012-02-21 18:57:12 -08001951 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001952 // Don't turn screen on until we know we are really ready to.
1953 // This is to avoid letting the screen go on before things like the
1954 // lock screen have been displayed.
Jim Miller92e66dd2012-02-21 18:57:12 -08001955 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001956 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1957 }
1958 }
1959
Joe Onorato60607a902010-10-23 14:49:30 -07001960 if ((newState & SCREEN_ON_BIT) != 0) {
1961 // Only turn on the buttons or keyboard if the screen is also on.
1962 // We should never see the buttons on but not the screen.
1963 newState = applyButtonState(newState);
1964 newState = applyKeyboardState(newState);
1965 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001966 final int realDifference = (newState ^ oldState);
1967 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001969 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 int offMask = 0;
1973 int dimMask = 0;
1974 int onMask = 0;
1975
1976 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001979 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1980 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001982 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984 }
1985
1986 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001987 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1988 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001990 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992 }
1993
1994 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001995 int nominalCurrentValue = -1;
1996 // If there was an actual difference in the light state, then
1997 // figure out the "ideal" current value based on the previous
1998 // state. Otherwise, this is a change due to the brightness
1999 // override, so we want to animate from whatever the current
2000 // value is.
2001 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
2002 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
2003 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
2004 nominalCurrentValue = preferredBrightness;
2005 break;
2006 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002007 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002008 break;
2009 case 0:
2010 nominalCurrentValue = Power.BRIGHTNESS_OFF;
2011 break;
2012 case SCREEN_BRIGHT_BIT:
2013 default:
2014 // not possible
Jim Miller92e66dd2012-02-21 18:57:12 -08002015 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness();
Joe Onoratob08a1af2010-10-11 19:28:58 -07002016 break;
Joe Onorato128e7292009-03-24 18:41:31 -07002017 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002018 }
2019 int brightness = preferredBrightness;
2020 int steps = ANIM_STEPS;
2021 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
2022 // dim or turn off backlight, depending on if the screen is on
2023 // the scale is because the brightness ramp isn't linear and this biases
2024 // it so the later parts take longer.
2025 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002026 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002027 if (ratio > 1.0f) ratio = 1.0f;
2028 if ((newState & SCREEN_ON_BIT) == 0) {
2029 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2030 // was bright
2031 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002033 // was dim
2034 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002036 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002038 if ((oldState & SCREEN_ON_BIT) != 0) {
2039 // was bright
2040 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2041 } else {
2042 // was dim
2043 steps = (int)(ANIM_STEPS*ratio);
2044 }
2045 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2046 // If the "stay on while plugged in" option is
2047 // turned on, then the screen will often not
2048 // automatically turn off while plugged in. To
2049 // still have a sense of when it is inactive, we
2050 // will then count going dim as turning off.
2051 mScreenOffTime = SystemClock.elapsedRealtime();
2052 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002053 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
2055 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002056 long identity = Binder.clearCallingIdentity();
2057 try {
2058 mBatteryStats.noteScreenBrightness(brightness);
2059 } catch (RemoteException e) {
2060 // Nothing interesting to do.
2061 } finally {
2062 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002064 if (!mSkippedScreenOn) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002065 int dt = steps * NOMINAL_FRAME_TIME_MS;
2066 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002067 if (DEBUG_SCREEN_ON) {
2068 RuntimeException e = new RuntimeException("here");
2069 e.fillInStackTrace();
2070 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2071 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002074
Joe Onorato60607a902010-10-23 14:49:30 -07002075 if (mSpew) {
2076 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2077 + " dimMask=0x" + Integer.toHexString(dimMask)
2078 + " onMask=0x" + Integer.toHexString(onMask)
2079 + " difference=0x" + Integer.toHexString(difference)
2080 + " realDifference=0x" + Integer.toHexString(realDifference)
2081 + " forceState=0x" + Integer.toHexString(forceState)
2082 );
2083 }
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002086 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002087 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002090 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 if ((newState & BATTERY_LOW_BIT) != 0 &&
2092 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2093 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2094 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002095 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002096 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 if (onMask != 0) {
2099 int brightness = getPreferredBrightness();
2100 if ((newState & BATTERY_LOW_BIT) != 0 &&
2101 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2102 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2103 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002104 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002105 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108
Jim Miller92e66dd2012-02-21 18:57:12 -08002109 /**
2110 * Note: by design this class does not hold mLocks while calling native methods.
2111 * Nor should it. Ever.
2112 */
2113 class ScreenBrightnessAnimator extends HandlerThread {
2114 static final int ANIMATE_LIGHTS = 10;
2115 static final int POWER_OFF = 11;
2116 volatile int startValue;
2117 volatile int endValue;
2118 volatile int currentValue;
2119 private int currentMask;
2120 private int duration;
2121 private long startTimeMillis;
2122 private final String prefix;
2123
2124 public ScreenBrightnessAnimator(String name, int priority) {
2125 super(name, priority);
2126 prefix = name;
2127 }
2128
2129 @Override
2130 protected void onLooperPrepared() {
2131 mScreenBrightnessHandler = new Handler() {
2132 public void handleMessage(Message msg) {
2133 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation
Mike Lockwood3a322132009-11-24 00:30:52 -05002134 ? LightsService.BRIGHTNESS_MODE_SENSOR
2135 : LightsService.BRIGHTNESS_MODE_USER);
Jim Miller92e66dd2012-02-21 18:57:12 -08002136 if (msg.what == ANIMATE_LIGHTS) {
2137 final int mask = msg.arg1;
2138 int value = msg.arg2;
2139 long tStart = SystemClock.uptimeMillis();
2140 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
2141 if (mDebugLightAnimation) Log.v(TAG, "Set brightness: " + value);
2142 mLcdLight.setBrightness(value, brightnessMode);
2143 }
2144 long elapsed = SystemClock.uptimeMillis() - tStart;
2145 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
2146 mButtonLight.setBrightness(value);
2147 }
2148 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
2149 mKeyboardLight.setBrightness(value);
2150 }
2151
2152 if (elapsed > 100) {
2153 Log.e(TAG, "Excessive delay setting brightness: " + elapsed
2154 + "ms, mask=" + mask);
2155 }
2156
2157 // Throttle brightness updates to frame refresh rate
2158 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 0;
2159 synchronized(this) {
2160 currentValue = value;
2161 }
2162 animateInternal(mask, false, delay);
2163 } else if (msg.what == POWER_OFF) {
2164 if (!mHeadless) {
2165 int mode = msg.arg1;
2166 nativeStartSurfaceFlingerAnimation(mode);
2167 }
2168 }
2169 }
2170 };
2171 synchronized (this) {
2172 mInitComplete = true;
2173 notifyAll();
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002174 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002175 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002176
2177 private void animateInternal(int mask, boolean turningOff, int delay) {
2178 synchronized (this) {
2179 if (currentValue != endValue) {
2180 final long now = SystemClock.elapsedRealtime();
2181 final int elapsed = (int) (now - startTimeMillis);
2182 int newValue;
2183 if (elapsed < duration) {
2184 int delta = endValue - startValue;
2185 newValue = startValue + delta * elapsed / duration;
2186 newValue = Math.max(Power.BRIGHTNESS_OFF, newValue);
2187 newValue = Math.min(Power.BRIGHTNESS_ON, newValue);
2188 } else {
2189 newValue = endValue;
2190 mInitialAnimation = false;
2191 }
2192
2193 if (mDebugLightAnimation) {
2194 Log.v(TAG, "Animating light: " + "start:" + startValue
2195 + ", end:" + endValue + ", elapsed:" + elapsed
2196 + ", duration:" + duration + ", current:" + currentValue
2197 + ", delay:" + delay);
2198 }
2199
2200 if (turningOff) {
2201 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR
2202 ? 0 : mAnimationSetting;
2203 if (mDebugLightAnimation) Log.v(TAG, "Doing power-off anim, mode=" + mode);
2204 mScreenBrightnessHandler.obtainMessage(POWER_OFF, mode, 0).sendToTarget();
2205 }
2206 Message msg = mScreenBrightnessHandler
2207 .obtainMessage(ANIMATE_LIGHTS, mask, newValue);
2208 mScreenBrightnessHandler.sendMessageDelayed(msg, delay);
2209 }
2210 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002211 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002212
2213 public void dump(PrintWriter pw, String string) {
2214 pw.println(prefix + "animating: " + "start:" + startValue + ", end:" + endValue
2215 + ", duration:" + duration + ", current:" + currentValue);
2216 }
2217
2218 public void animateTo(int target, int mask, int animationDuration) {
2219 synchronized(this) {
2220 startValue = currentValue;
2221 endValue = target;
2222 currentMask = mask;
2223 duration = (int) (mWindowScaleAnimation * animationDuration);
2224 startTimeMillis = SystemClock.elapsedRealtime();
2225 mInitialAnimation = currentValue == 0 && target > 0;
2226
2227 if (mDebugLightAnimation) {
2228 Log.v(TAG, "animateTo(target=" + target + ", mask=" + mask
2229 + ", duration=" + animationDuration +")"
2230 + ", currentValue=" + currentValue
2231 + ", startTime=" + startTimeMillis);
2232 }
2233
2234 if (target != currentValue) {
2235 final boolean turningOff = endValue == Power.BRIGHTNESS_OFF;
2236 if (turningOff) {
2237 // Cancel all pending animations since we're turning off
2238 mScreenBrightnessHandler.removeCallbacksAndMessages(null);
2239 screenOffFinishedAnimatingLocked(mScreenOffReason);
2240 duration = 200; // TODO: how long should this be?
2241 }
2242 animateInternal(mask, turningOff, 0);
2243 }
2244 }
2245 }
2246
2247 public int getCurrentBrightness() {
2248 synchronized (this) {
2249 return currentValue;
2250 }
2251 }
2252
2253 public boolean isAnimating() {
2254 synchronized (this) {
2255 return currentValue != endValue;
2256 }
2257 }
2258
2259 public void cancelAnimation() {
2260 animateTo(endValue, currentMask, 0);
The Android Open Source Project10592532009-03-18 17:39:46 -07002261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 }
2263
Jim Miller92e66dd2012-02-21 18:57:12 -08002264 private void setLightBrightness(int mask, int value) {
2265 mScreenBrightnessAnimator.animateTo(value, mask, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 private int getPreferredBrightness() {
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002269 if (mScreenBrightnessOverride >= 0) {
2270 return mScreenBrightnessOverride;
2271 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
2272 && mAutoBrightessEnabled) {
2273 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002275 final int brightness = mScreenBrightnessSetting;
2276 // Don't let applications turn the screen all the way off
2277 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 }
2279
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002280 private int applyButtonState(int state) {
2281 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002282 if ((state & BATTERY_LOW_BIT) != 0) {
2283 // do not override brightness if the battery is low
2284 return state;
2285 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002286 if (mButtonBrightnessOverride >= 0) {
2287 brightness = mButtonBrightnessOverride;
2288 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2289 brightness = mLightSensorButtonBrightness;
2290 }
2291 if (brightness > 0) {
2292 return state | BUTTON_BRIGHT_BIT;
2293 } else if (brightness == 0) {
2294 return state & ~BUTTON_BRIGHT_BIT;
2295 } else {
2296 return state;
2297 }
2298 }
2299
2300 private int applyKeyboardState(int state) {
2301 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002302 if ((state & BATTERY_LOW_BIT) != 0) {
2303 // do not override brightness if the battery is low
2304 return state;
2305 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002306 if (!mKeyboardVisible) {
2307 brightness = 0;
2308 } else if (mButtonBrightnessOverride >= 0) {
2309 brightness = mButtonBrightnessOverride;
2310 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2311 brightness = mLightSensorKeyboardBrightness;
2312 }
2313 if (brightness > 0) {
2314 return state | KEYBOARD_BRIGHT_BIT;
2315 } else if (brightness == 0) {
2316 return state & ~KEYBOARD_BRIGHT_BIT;
2317 } else {
2318 return state;
2319 }
2320 }
2321
Charles Mendis322591c2009-10-29 11:06:59 -07002322 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 synchronized (mLocks) {
2324 return (mPowerState & SCREEN_ON_BIT) != 0;
2325 }
2326 }
2327
Charles Mendis322591c2009-10-29 11:06:59 -07002328 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 synchronized (mLocks) {
2330 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2331 }
2332 }
2333
Mike Lockwood497087e32009-11-08 18:33:03 -05002334 private boolean isScreenTurningOffLocked() {
Jim Miller92e66dd2012-02-21 18:57:12 -08002335 return (mScreenBrightnessAnimator.isAnimating()
2336 && mScreenBrightnessAnimator.endValue == Power.BRIGHTNESS_OFF);
Mike Lockwood497087e32009-11-08 18:33:03 -05002337 }
2338
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002339 private boolean shouldLog(long time) {
2340 synchronized (mLocks) {
2341 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2342 mWarningSpewThrottleTime = time;
2343 mWarningSpewThrottleCount = 0;
2344 return true;
2345 } else if (mWarningSpewThrottleCount < 30) {
2346 mWarningSpewThrottleCount++;
2347 return true;
2348 } else {
2349 return false;
2350 }
2351 }
2352 }
2353
Mike Lockwood200b30b2009-09-20 00:23:59 -04002354 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002355 if (isScreenTurningOffLocked()) {
2356 // cancel animation so userActivity will succeed
Jim Miller92e66dd2012-02-21 18:57:12 -08002357 mScreenBrightnessAnimator.cancelAnimation();
Mike Lockwoode090281422009-11-14 21:02:56 -05002358 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002359 boolean savedActivityAllowed = mUserActivityAllowed;
2360 mUserActivityAllowed = true;
2361 userActivity(SystemClock.uptimeMillis(), false);
2362 mUserActivityAllowed = savedActivityAllowed;
2363 }
2364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002367 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 }
2369
2370 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002371 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2372 != PackageManager.PERMISSION_GRANTED) {
2373 if (shouldLog(time)) {
2374 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2375 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2376 }
2377 return;
2378 }
2379
Joe Onorato7999bff2010-07-24 11:50:05 -04002380 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 }
2382
2383 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002384 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
2386
2387 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002388 userActivity(time, -1, noChangeLights, eventType, force);
2389 }
2390
2391 /*
2392 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2393 * on with user activity. Don't use this function.
2394 */
2395 public void clearUserActivityTimeout(long now, long timeout) {
2396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2397 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2398 userActivity(now, timeout, false, OTHER_EVENT, false);
2399 }
2400
2401 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2402 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403
Joe Onorato1a542c72010-11-08 09:48:20 -08002404 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002405 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002406 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002407 }
2408 return;
2409 }
2410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 synchronized (mLocks) {
2412 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002413 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 + " mUserActivityAllowed=" + mUserActivityAllowed
2415 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002416 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2417 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002418 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002419 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 }
Mike Lockwood05067122009-10-27 23:07:25 -04002421 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002422 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002423 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002424 return;
2425 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002426 // Disable proximity sensor if if user presses power key while we are in the
2427 // "waiting for proximity sensor to go negative" state.
2428 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2429 mProximitySensorActive = false;
2430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 if (mLastEventTime <= time || force) {
2432 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002433 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002434 // Only turn on button backlights if a button was pressed
2435 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002436 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2438 } else {
2439 // don't clear button/keyboard backlights when the screen is touched.
2440 mUserState |= SCREEN_BRIGHT;
2441 }
2442
Dianne Hackborn617f8772009-03-31 15:04:46 -07002443 int uid = Binder.getCallingUid();
2444 long ident = Binder.clearCallingIdentity();
2445 try {
2446 mBatteryStats.noteUserActivity(uid, eventType);
2447 } catch (RemoteException e) {
2448 // Ignore
2449 } finally {
2450 Binder.restoreCallingIdentity(ident);
2451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002452
Michael Chane96440f2009-05-06 10:27:36 -07002453 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002454 setPowerState(mUserState | mWakeLockState, noChangeLights,
2455 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002456 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 }
2458 }
2459 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002460
2461 if (mPolicy != null) {
2462 mPolicy.userActivity();
2463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
2465
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002466 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2467 try {
2468 int i;
2469 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2470 if (sensorValue < mAutoBrightnessLevels[i]) {
2471 break;
2472 }
2473 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002474 // This is the range of brightness values that we can use.
2475 final int minval = values[0];
2476 final int maxval = values[mAutoBrightnessLevels.length];
2477 // This is the range we will be scaling. We put some padding
2478 // at the low and high end to give the adjustment a little better
2479 // impact on the actual observed value.
2480 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION;
2481 // This is the desired brightness value from 0.0 to 1.0.
2482 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range);
2483 // Apply a scaling to the value based on the adjustment.
2484 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) {
2485 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting);
2486 if (adj <= .00001) {
2487 valf = 1;
2488 } else {
2489 valf /= adj;
2490 }
2491 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) {
2492 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting);
2493 valf *= adj;
2494 }
2495 // Apply an additional offset to the value based on the adjustment.
2496 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE;
2497 // Convert the 0.0-1.0 value back to a brightness integer.
2498 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2);
2499 if (val < minval) val = minval;
2500 else if (val > maxval) val = maxval;
2501 return val;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002502 } catch (Exception e) {
2503 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002504 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002505 return 255;
2506 }
2507 }
2508
Mike Lockwood20f87d72009-11-05 16:08:51 -05002509 private Runnable mProximityTask = new Runnable() {
2510 public void run() {
2511 synchronized (mLocks) {
2512 if (mProximityPendingValue != -1) {
2513 proximityChangedLocked(mProximityPendingValue == 1);
2514 mProximityPendingValue = -1;
2515 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002516 if (mProximityPartialLock.isHeld()) {
2517 mProximityPartialLock.release();
2518 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002519 }
2520 }
2521 };
2522
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002523 private Runnable mAutoBrightnessTask = new Runnable() {
2524 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002525 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002526 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2527 int value = (int)mLightSensorPendingValue;
2528 mLightSensorPendingDecrease = false;
2529 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002530 lightSensorChangedLocked(value, false);
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002531 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002532 }
2533 }
2534 };
2535
Jim Miller92e66dd2012-02-21 18:57:12 -08002536 private boolean mInitialAnimation; // used to prevent lightsensor changes while turning on
2537
Mike Lockwoodb2865412010-02-02 22:40:33 -05002538 private void dockStateChanged(int state) {
2539 synchronized (mLocks) {
2540 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2541 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002542 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002543 mHighestLightSensorValue = -1;
2544 }
2545 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2546 // force lights recalculation
2547 int value = (int)mLightSensorValue;
2548 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002549 lightSensorChangedLocked(value, false);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002550 }
2551 }
2552 }
2553
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002554 private void lightSensorChangedLocked(int value, boolean immediate) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002555 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002556 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002557 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002558
Joe Onorato06eb33a2010-10-25 14:09:21 -07002559 // Don't do anything if the screen is off.
2560 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2561 if (mDebugLightSensor) {
2562 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2563 }
2564 return;
2565 }
2566
Mike Lockwoodb2865412010-02-02 22:40:33 -05002567 // do not allow light sensor value to decrease
2568 if (mHighestLightSensorValue < value) {
2569 mHighestLightSensorValue = value;
2570 }
2571
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002572 if (mLightSensorValue != value) {
2573 mLightSensorValue = value;
2574 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002575 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2576 // we only do this if we are undocked, since lighting should be stable when
2577 // stationary in a dock.
2578 int lcdValue = getAutoBrightnessValue(
2579 (mIsDocked ? value : mHighestLightSensorValue),
2580 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002581 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002582 int keyboardValue;
2583 if (mKeyboardVisible) {
2584 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2585 } else {
2586 keyboardValue = 0;
2587 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002588 mLightSensorScreenBrightness = lcdValue;
2589 mLightSensorButtonBrightness = buttonValue;
2590 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002591
2592 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002593 Slog.d(TAG, "lcdValue " + lcdValue);
2594 Slog.d(TAG, "buttonValue " + buttonValue);
2595 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002596 }
2597
Mike Lockwood4984e732009-11-01 08:16:33 -05002598 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002599 if (!mSkippedScreenOn && !mInitialAnimation) {
2600 int steps = immediate ? IMMEDIATE_ANIM_STEPS : AUTOBRIGHTNESS_ANIM_STEPS;
2601 mScreenBrightnessAnimator.cancelAnimation();
2602 mScreenBrightnessAnimator.animateTo(lcdValue,
2603 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002604 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002605 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002606 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002607 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002608 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002609 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002610 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002611 }
2612 }
2613 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002614 }
2615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 /**
2617 * The user requested that we go to sleep (probably with the power button).
2618 * This overrides all wake locks that are held.
2619 */
2620 public void goToSleep(long time)
2621 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002622 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2623 }
2624
2625 /**
2626 * The user requested that we go to sleep (probably with the power button).
2627 * This overrides all wake locks that are held.
2628 */
2629 public void goToSleepWithReason(long time, int reason)
2630 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2632 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002633 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 }
2635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002638 * Reboot the device immediately, passing 'reason' (may be null)
2639 * to the underlying __reboot system call. Should not return.
2640 */
2641 public void reboot(String reason)
2642 {
2643 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002644
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002645 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2646 throw new IllegalStateException("Too early to call reboot()");
2647 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002648
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002649 final String finalReason = reason;
2650 Runnable runnable = new Runnable() {
2651 public void run() {
2652 synchronized (this) {
2653 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002654 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002655
San Mehat1e512792010-01-07 10:40:29 -08002656 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002657 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002658 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002659 mHandler.post(runnable);
2660
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002661 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002662 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002663 while (true) {
2664 try {
2665 runnable.wait();
2666 } catch (InterruptedException e) {
2667 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002668 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002669 }
2670 }
2671
Dan Egnor60d87622009-12-16 16:32:58 -08002672 /**
2673 * Crash the runtime (causing a complete restart of the Android framework).
2674 * Requires REBOOT permission. Mostly for testing. Should not return.
2675 */
2676 public void crash(final String message)
2677 {
2678 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2679 Thread t = new Thread("PowerManagerService.crash()") {
2680 public void run() { throw new RuntimeException(message); }
2681 };
2682 try {
2683 t.start();
2684 t.join();
2685 } catch (InterruptedException e) {
2686 Log.wtf(TAG, e);
2687 }
2688 }
2689
Mike Lockwood435eb642009-12-03 08:40:18 -05002690 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691
2692 if (mLastEventTime <= time) {
2693 mLastEventTime = time;
2694 // cancel all of the wake locks
2695 mWakeLockState = SCREEN_OFF;
2696 int N = mLocks.size();
2697 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002698 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 for (int i=0; i<N; i++) {
2700 WakeLock wl = mLocks.get(i);
2701 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002702 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2703 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2704 proxLock = true;
2705 } else {
2706 mLocks.get(i).activated = false;
2707 numCleared++;
2708 }
2709 }
2710 }
2711 if (!proxLock) {
2712 mProxIgnoredBecauseScreenTurnedOff = true;
2713 if (mDebugProximitySensor) {
2714 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
2716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002717 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002718 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002720 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 cancelTimerLocked();
2722 }
2723 }
2724
2725 public long timeSinceScreenOn() {
2726 synchronized (mLocks) {
2727 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2728 return 0;
2729 }
2730 return SystemClock.elapsedRealtime() - mScreenOffTime;
2731 }
2732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002735 synchronized (mLocks) {
2736 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002737 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002738 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002739 if (mKeyboardVisible != visible) {
2740 mKeyboardVisible = visible;
2741 // don't signal user activity if the screen is off; other code
2742 // will take care of turning on due to a true change to the lid
2743 // switch and synchronized with the lock screen.
2744 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002745 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002746 // force recompute of backlight values
2747 if (mLightSensorValue >= 0) {
2748 int value = (int)mLightSensorValue;
2749 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002750 lightSensorChangedLocked(value, false);
Mike Lockwooddf024922009-10-29 21:29:15 -04002751 }
2752 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002753 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2754 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002755 }
2756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 }
2758
2759 /**
2760 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002761 * When disabling user activity we also reset user power state so the keyguard can reset its
2762 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 */
2764 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002765 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002766 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 synchronized (mLocks) {
2769 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002770 if (!enabled) {
2771 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2772 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 }
2775 }
2776
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002777 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002778 synchronized (mLocks) {
2779 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2780 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2781 mAutoBrightessEnabled = enabled;
2782 // This will get us a new value
2783 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002784 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002785 }
2786 }
2787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 /** Sets the screen off timeouts:
2789 * mKeylightDelay
2790 * mDimDelay
2791 * mScreenOffDelay
2792 * */
2793 private void setScreenOffTimeoutsLocked() {
2794 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002795 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 mDimDelay = -1;
2797 mScreenOffDelay = 0;
2798 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2799 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2800 mDimDelay = -1;
2801 mScreenOffDelay = 0;
2802 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002803 int totalDelay = mScreenOffTimeoutSetting;
2804 if (totalDelay > mMaximumScreenOffTimeout) {
2805 totalDelay = mMaximumScreenOffTimeout;
2806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2808 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002809 // negative number means stay on as long as possible.
2810 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 } else if (mKeylightDelay < totalDelay) {
2812 // subtract the time that the keylight delay. This will give us the
2813 // remainder of the time that we need to sleep to get the accurate
2814 // screen off timeout.
2815 mScreenOffDelay = totalDelay - mKeylightDelay;
2816 } else {
2817 mScreenOffDelay = 0;
2818 }
2819 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2820 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2821 mScreenOffDelay = LONG_DIM_TIME;
2822 } else {
2823 mDimDelay = -1;
2824 }
2825 }
2826 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002827 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2829 + " mDimScreen=" + mDimScreen);
2830 }
2831 }
2832
2833 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002834 * Refreshes cached secure settings. Called once on startup, and
2835 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 */
Doug Zongker43866e02010-01-07 12:09:54 -08002837 private void updateSettingsValues() {
2838 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002840 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002842 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 }
2844
2845 private class LockList extends ArrayList<WakeLock>
2846 {
2847 void addLock(WakeLock wl)
2848 {
2849 int index = getIndex(wl.binder);
2850 if (index < 0) {
2851 this.add(wl);
2852 }
2853 }
2854
2855 WakeLock removeLock(IBinder binder)
2856 {
2857 int index = getIndex(binder);
2858 if (index >= 0) {
2859 return this.remove(index);
2860 } else {
2861 return null;
2862 }
2863 }
2864
2865 int getIndex(IBinder binder)
2866 {
2867 int N = this.size();
2868 for (int i=0; i<N; i++) {
2869 if (this.get(i).binder == binder) {
2870 return i;
2871 }
2872 }
2873 return -1;
2874 }
2875
2876 int gatherState()
2877 {
2878 int result = 0;
2879 int N = this.size();
2880 for (int i=0; i<N; i++) {
2881 WakeLock wl = this.get(i);
2882 if (wl.activated) {
2883 if (isScreenLock(wl.flags)) {
2884 result |= wl.minState;
2885 }
2886 }
2887 }
2888 return result;
2889 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002890
Michael Chane96440f2009-05-06 10:27:36 -07002891 int reactivateScreenLocksLocked()
2892 {
2893 int result = 0;
2894 int N = this.size();
2895 for (int i=0; i<N; i++) {
2896 WakeLock wl = this.get(i);
2897 if (isScreenLock(wl.flags)) {
2898 wl.activated = true;
2899 result |= wl.minState;
2900 }
2901 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002902 if (mDebugProximitySensor) {
2903 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2904 + mProxIgnoredBecauseScreenTurnedOff);
2905 }
2906 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002907 return result;
2908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
2910
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002911 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 synchronized (mLocks) {
2913 mPolicy = p;
2914 mLocks.notifyAll();
2915 }
2916 }
2917
2918 WindowManagerPolicy getPolicyLocked() {
2919 while (mPolicy == null || !mDoneBooting) {
2920 try {
2921 mLocks.wait();
2922 } catch (InterruptedException e) {
2923 // Ignore
2924 }
2925 }
2926 return mPolicy;
2927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002930 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2931 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2932 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002933 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002934 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002935 }
2936
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002937 // wait until sensors are enabled before turning on screen.
2938 // some devices will not activate the light sensor properly on boot
2939 // unless we do this.
2940 if (mUseSoftwareAutoBrightness) {
2941 // turn the screen on
2942 setPowerState(SCREEN_BRIGHT);
2943 } else {
2944 // turn everything on
2945 setPowerState(ALL_BRIGHT);
2946 }
2947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002949 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002951
Joe Onoratod28f7532010-11-06 12:56:53 -07002952 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2953
Dianne Hackborn617f8772009-03-31 15:04:46 -07002954 long identity = Binder.clearCallingIdentity();
2955 try {
2956 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2957 mBatteryStats.noteScreenOn();
2958 } catch (RemoteException e) {
2959 // Nothing interesting to do.
2960 } finally {
2961 Binder.restoreCallingIdentity(identity);
2962 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002963 }
2964 }
2965
2966 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002967 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002968 synchronized (mLocks) {
2969 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2971 updateWakeLockLocked();
2972 mLocks.notifyAll();
2973 }
2974 }
2975
Joe Onoratob08a1af2010-10-11 19:28:58 -07002976 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 public void monitor() {
2978 synchronized (mLocks) { }
2979 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002980
2981 public int getSupportedWakeLockFlags() {
2982 int result = PowerManager.PARTIAL_WAKE_LOCK
2983 | PowerManager.FULL_WAKE_LOCK
2984 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2985
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002986 if (mProximitySensor != null) {
2987 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2988 }
2989
2990 return result;
2991 }
2992
Mike Lockwood237a2992009-09-15 14:42:16 -04002993 public void setBacklightBrightness(int brightness) {
2994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2995 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002996 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002997 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002998 mLcdLight.setBrightness(brightness);
2999 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
3000 mButtonLight.setBrightness(brightness);
3001 long identity = Binder.clearCallingIdentity();
3002 try {
3003 mBatteryStats.noteScreenBrightness(brightness);
3004 } catch (RemoteException e) {
3005 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
3006 } finally {
3007 Binder.restoreCallingIdentity(identity);
3008 }
Jim Miller92e66dd2012-02-21 18:57:12 -08003009 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003010 }
3011 }
3012
3013 public void setAutoBrightnessAdjustment(float adj) {
3014 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3015 synchronized (mLocks) {
3016 mLightSensorAdjustSetting = adj;
3017 if (mSensorManager != null && mLightSensorEnabled) {
3018 // clear calling identity so sensor manager battery stats are accurate
3019 long identity = Binder.clearCallingIdentity();
3020 try {
3021 // force recompute of backlight values
3022 if (mLightSensorValue >= 0) {
3023 int value = (int)mLightSensorValue;
3024 mLightSensorValue = -1;
3025 handleLightSensorValue(value, true);
3026 }
3027 } finally {
3028 Binder.restoreCallingIdentity(identity);
3029 }
Joe Onorato3d3db602010-10-18 16:08:16 -04003030 }
Mike Lockwood237a2992009-09-15 14:42:16 -04003031 }
3032 }
3033
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003034 public void setAttentionLight(boolean on, int color) {
3035 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05003036 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003037 }
3038
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003039 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003040 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003041 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003042 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003043 if (!mProximitySensorEnabled) {
3044 // clear calling identity so sensor manager battery stats are accurate
3045 long identity = Binder.clearCallingIdentity();
3046 try {
3047 mSensorManager.registerListener(mProximityListener, mProximitySensor,
3048 SensorManager.SENSOR_DELAY_NORMAL);
3049 mProximitySensorEnabled = true;
3050 } finally {
3051 Binder.restoreCallingIdentity(identity);
3052 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003053 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003054 }
3055
3056 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003057 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003058 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003059 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003060 if (mProximitySensorEnabled) {
3061 // clear calling identity so sensor manager battery stats are accurate
3062 long identity = Binder.clearCallingIdentity();
3063 try {
3064 mSensorManager.unregisterListener(mProximityListener);
3065 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003066 if (mProximityPartialLock.isHeld()) {
3067 mProximityPartialLock.release();
3068 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003069 mProximitySensorEnabled = false;
3070 } finally {
3071 Binder.restoreCallingIdentity(identity);
3072 }
3073 if (mProximitySensorActive) {
3074 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003075 if (mDebugProximitySensor) {
3076 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
3077 + mProxIgnoredBecauseScreenTurnedOff);
3078 }
3079 if (!mProxIgnoredBecauseScreenTurnedOff) {
3080 forceUserActivityLocked();
3081 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003082 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003083 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003084 }
3085
Mike Lockwood20f87d72009-11-05 16:08:51 -05003086 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003087 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003088 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003089 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003090 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003091 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003092 return;
3093 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003094 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003095 if (mDebugProximitySensor) {
3096 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3097 + mProxIgnoredBecauseScreenTurnedOff);
3098 }
3099 if (!mProxIgnoredBecauseScreenTurnedOff) {
3100 goToSleepLocked(SystemClock.uptimeMillis(),
3101 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3102 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003103 mProximitySensorActive = true;
3104 } else {
3105 // proximity sensor negative events trigger as user activity.
3106 // temporarily set mUserActivityAllowed to true so this will work
3107 // even when the keyguard is on.
3108 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003109 if (mDebugProximitySensor) {
3110 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3111 + mProxIgnoredBecauseScreenTurnedOff);
3112 }
3113 if (!mProxIgnoredBecauseScreenTurnedOff) {
3114 forceUserActivityLocked();
3115 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003116
3117 if (mProximityWakeLockCount == 0) {
3118 // disable sensor if we have no listeners left after proximity negative
3119 disableProximityLockLocked();
3120 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003121 }
3122 }
3123
Joe Onoratod28f7532010-11-06 12:56:53 -07003124 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003125 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003126 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3127 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3128 }
3129 if (!mAutoBrightessEnabled) {
3130 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003131 }
3132 if (mSensorManager != null && mLightSensorEnabled != enable) {
3133 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003134 // clear calling identity so sensor manager battery stats are accurate
3135 long identity = Binder.clearCallingIdentity();
3136 try {
3137 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003138 // reset our highest value when reenabling
3139 mHighestLightSensorValue = -1;
3140 // force recompute of backlight values
3141 if (mLightSensorValue >= 0) {
3142 int value = (int)mLightSensorValue;
3143 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003144 handleLightSensorValue(value, true);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003145 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003146 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003147 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003148 } else {
3149 mSensorManager.unregisterListener(mLightListener);
3150 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003151 mLightSensorPendingDecrease = false;
3152 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003153 }
3154 } finally {
3155 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003156 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003157 }
3158 }
3159
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003160 SensorEventListener mProximityListener = new SensorEventListener() {
3161 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003162 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003163 synchronized (mLocks) {
3164 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003165 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3166 mLastProximityEventTime = milliseconds;
3167 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003168 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003169
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003170 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003171 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3172 distance < mProximitySensor.getMaximumRange());
3173
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003174 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003175 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003176 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003177 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3178 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3179 mProximityPendingValue = (active ? 1 : 0);
3180 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003181 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003182 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003183 // process the value immediately
3184 mProximityPendingValue = -1;
3185 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003186 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003187
3188 // update mProximityPartialLock state
3189 boolean held = mProximityPartialLock.isHeld();
3190 if (!held && proximityTaskQueued) {
3191 // hold wakelock until mProximityTask runs
3192 mProximityPartialLock.acquire();
3193 } else if (held && !proximityTaskQueued) {
3194 mProximityPartialLock.release();
3195 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003196 }
3197 }
3198
3199 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3200 // ignore
3201 }
3202 };
3203
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003204 private void handleLightSensorValue(int value, boolean immediate) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003205 long milliseconds = SystemClock.elapsedRealtime();
3206 if (mLightSensorValue == -1 ||
3207 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3208 // process the value immediately if screen has just turned on
3209 mHandler.removeCallbacks(mAutoBrightnessTask);
3210 mLightSensorPendingDecrease = false;
3211 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003212 lightSensorChangedLocked(value, immediate);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003213 } else {
3214 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3215 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3216 (value == mLightSensorValue) ||
3217 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3218 // delay processing to debounce the sensor
3219 mHandler.removeCallbacks(mAutoBrightnessTask);
3220 mLightSensorPendingDecrease = (value < mLightSensorValue);
3221 mLightSensorPendingIncrease = (value > mLightSensorValue);
3222 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3223 mLightSensorPendingValue = value;
3224 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3225 }
3226 } else {
3227 mLightSensorPendingValue = value;
3228 }
3229 }
3230 }
3231
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003232 SensorEventListener mLightListener = new SensorEventListener() {
3233 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003234 if (mDebugLightSensor) {
3235 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3236 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003237 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003238 // ignore light sensor while screen is turning off
3239 if (isScreenTurningOffLocked()) {
3240 return;
3241 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003242 handleLightSensorValue((int)event.values[0], false);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003243 }
3244 }
3245
3246 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3247 // ignore
3248 }
3249 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250}