blob: 2d2a88113b3409351c58566d186d0e4cfaebe040 [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
Jim Miller46f31c32012-03-01 14:36:07 -0800164 // animate screen lights in PowerManager (as opposed to SurfaceFlinger)
Joe Onoratob08a1af2010-10-11 19:28:58 -0700165 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800166
Jim Miller92e66dd2012-02-21 18:57:12 -0800167 static final int ANIM_STEPS = 60; // nominal # of frames at 60Hz
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400168 // Slower animation for autobrightness changes
Jim Miller92e66dd2012-02-21 18:57:12 -0800169 static final int AUTOBRIGHTNESS_ANIM_STEPS = 2 * ANIM_STEPS;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800170 // Number of steps when performing a more immediate brightness change.
171 static final int IMMEDIATE_ANIM_STEPS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173 // These magic numbers are the initial state of the LEDs at boot. Ideally
174 // we should read them from the driver, but our current hardware returns 0
175 // for the initial value. Oops!
176 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
177 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
178 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700181 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500184 private boolean mBootCompleted = false;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700185 private boolean mHeadless = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500187 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
188 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700189 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700190 private boolean mSkippedScreenOn = false;
191 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private int mPartialCount = 0;
193 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500194 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
195 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
196 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private int mUserState;
198 private boolean mKeyboardVisible = false;
199 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500200 private int mProximityWakeLockCount = 0;
201 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700202 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500203 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
204 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800205 private int mScreenOffTimeoutSetting;
206 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private int mKeylightDelay;
208 private int mDimDelay;
209 private int mScreenOffDelay;
210 private int mWakeLockState;
211 private long mLastEventTime = 0;
212 private long mScreenOffTime;
213 private volatile WindowManagerPolicy mPolicy;
214 private final LockList mLocks = new LockList();
215 private Intent mScreenOffIntent;
216 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500217 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500219 private LightsService.Light mLcdLight;
220 private LightsService.Light mButtonLight;
221 private LightsService.Light mKeyboardLight;
222 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private UnsynchronizedWakeLock mBroadcastWakeLock;
224 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
225 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
226 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500227 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700229 private Handler mScreenOffHandler;
Jim Miller92e66dd2012-02-21 18:57:12 -0800230 private Handler mScreenBrightnessHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500232 private final TimeoutTask mTimeoutTask = new TimeoutTask();
Jim Miller92e66dd2012-02-21 18:57:12 -0800233 private ScreenBrightnessAnimator mScreenBrightnessAnimator;
Joe Onorato128e7292009-03-24 18:41:31 -0700234 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private boolean mIsPowered = false;
236 private IActivityManager mActivityService;
237 private IBatteryStats mBatteryStats;
238 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700239 private SensorManager mSensorManager;
240 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400241 private Sensor mLightSensor;
242 private boolean mLightSensorEnabled;
243 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400244 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500245 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500246 private boolean mLightSensorPendingDecrease = false;
247 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700248 private float mLightSensorPendingValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800249 private float mLightSensorAdjustSetting = 0;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500250 private int mLightSensorScreenBrightness = -1;
251 private int mLightSensorButtonBrightness = -1;
252 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500254 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 private long mNextTimeout;
256 private volatile int mPokey = 0;
257 private volatile boolean mPokeAwakeOnSet = false;
258 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500259 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500260 // mLastScreenOnTime is the time the screen was last turned on
261 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 private boolean mPreventScreenOn;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800263 private int mScreenBrightnessSetting = DEFAULT_SCREEN_BRIGHTNESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500265 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400266 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400267 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700268 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700269 private int[] mAutoBrightnessLevels;
270 private int[] mLcdBacklightValues;
271 private int[] mButtonBacklightValues;
272 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500273 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700274 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700275 private int mWarningSpewThrottleCount;
276 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700277 private int mAnimationSetting = ANIM_SETTING_OFF;
Jim Miller92e66dd2012-02-21 18:57:12 -0800278 private float mWindowScaleAnimation;
Joe Onorato609695d2010-10-14 14:57:49 -0700279
280 // Must match with the ISurfaceComposer constants in C++.
281 private static final int ANIM_SETTING_ON = 0x01;
282 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283
284 // Used when logging number and duration of touch-down cycles
285 private long mTotalTouchDownTime;
286 private long mLastTouchDown;
287 private int mTouchCycles;
288
289 // could be either static or controllable at runtime
290 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400291 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwoodae92eb32011-10-25 10:11:46 -0400292 private static final boolean mDebugLightSensor = (false || mSpew);
Jim Miller92e66dd2012-02-21 18:57:12 -0800293 private static final boolean mDebugLightAnimation = (false || mSpew);
294
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700295 private native void nativeInit();
296 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700297 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298
299 /*
300 static PrintStream mLog;
301 static {
302 try {
303 mLog = new PrintStream("/data/power.log");
304 }
305 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800306 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 }
308 }
309 static class Log {
310 static void d(String tag, String s) {
311 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800312 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314 static void i(String tag, String s) {
315 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800316 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 }
318 static void w(String tag, String s) {
319 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800320 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322 static void e(String tag, String s) {
323 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800324 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326 }
327 */
328
329 /**
330 * This class works around a deadlock between the lock in PowerManager.WakeLock
331 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
332 * mToken object so it can be accessed from any thread, but it calls into here
333 * with its lock held. This class is essentially a reimplementation of
334 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
335 * only call it with our own locks held.
336 */
337 private class UnsynchronizedWakeLock {
338 int mFlags;
339 String mTag;
340 IBinder mToken;
341 int mCount = 0;
342 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500343 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344
345 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
346 mFlags = flags;
347 mTag = tag;
348 mToken = new Binder();
349 mRefCounted = refCounted;
350 }
351
352 public void acquire() {
353 if (!mRefCounted || mCount++ == 0) {
354 long ident = Binder.clearCallingIdentity();
355 try {
356 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700357 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500358 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 } finally {
360 Binder.restoreCallingIdentity(ident);
361 }
362 }
363 }
364
365 public void release() {
366 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500367 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500368 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
370 if (mCount < 0) {
371 throw new RuntimeException("WakeLock under-locked " + mTag);
372 }
373 }
374
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500375 public boolean isHeld()
376 {
377 return mHeld;
378 }
379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 public String toString() {
381 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500382 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 }
384 }
385
386 private final class BatteryReceiver extends BroadcastReceiver {
387 @Override
388 public void onReceive(Context context, Intent intent) {
389 synchronized (mLocks) {
390 boolean wasPowered = mIsPowered;
391 mIsPowered = mBatteryService.isPowered();
392
393 if (mIsPowered != wasPowered) {
394 // update mStayOnWhilePluggedIn wake lock
395 updateWakeLockLocked();
396
397 // treat plugging and unplugging the devices as a user activity.
398 // users find it disconcerting when they unplug the device
399 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500400 // to avoid turning on the screen when unplugging, we only trigger
401 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 // temporarily set mUserActivityAllowed to true so this will work
403 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700404 // However, you can also set config_unplugTurnsOnScreen to have it
405 // turn on. Some devices want this because they don't have a
406 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700408 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
409 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500410 forceUserActivityLocked();
411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
413 }
414 }
415 }
416 }
417
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500418 private final class BootCompletedReceiver extends BroadcastReceiver {
419 @Override
420 public void onReceive(Context context, Intent intent) {
421 bootCompleted();
422 }
423 }
424
Mike Lockwoodb2865412010-02-02 22:40:33 -0500425 private final class DockReceiver extends BroadcastReceiver {
426 @Override
427 public void onReceive(Context context, Intent intent) {
428 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
429 Intent.EXTRA_DOCK_STATE_UNDOCKED);
430 dockStateChanged(state);
431 }
432 }
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 /**
435 * Set the setting that determines whether the device stays on when plugged in.
436 * The argument is a bit string, with each bit specifying a power source that,
437 * when the device is connected to that source, causes the device to stay on.
438 * See {@link android.os.BatteryManager} for the list of power sources that
439 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
440 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
441 * @param val an {@code int} containing the bits that specify which power sources
442 * should cause the device to stay on.
443 */
444 public void setStayOnSetting(int val) {
445 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
446 Settings.System.putInt(mContext.getContentResolver(),
447 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
448 }
449
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800450 public void setMaximumScreenOffTimeount(int timeMs) {
451 mContext.enforceCallingOrSelfPermission(
452 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
453 synchronized (mLocks) {
454 mMaximumScreenOffTimeout = timeMs;
455 // recalculate everything
456 setScreenOffTimeoutsLocked();
457 }
458 }
459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700461 private int getInt(String name, int defValue) {
462 ContentValues values = mSettings.getValues(name);
463 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
464 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 }
466
Joe Onorato609695d2010-10-14 14:57:49 -0700467 private float getFloat(String name, float defValue) {
468 ContentValues values = mSettings.getValues(name);
469 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
470 return fVal != null ? fVal : defValue;
471 }
472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 public void update(Observable o, Object arg) {
474 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700475 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
476 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
477 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 updateWakeLockLocked();
479
Amith Yamasani8b619832010-09-22 16:11:59 -0700480 // SCREEN_OFF_TIMEOUT, default to 15 seconds
481 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482
Joe Onorato609695d2010-10-14 14:57:49 -0700483 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 //mDimScreen = getInt(DIM_SCREEN) != 0;
485
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800486 mScreenBrightnessSetting = getInt(SCREEN_BRIGHTNESS, DEFAULT_SCREEN_BRIGHTNESS);
487 mLightSensorAdjustSetting = getFloat(SCREEN_AUTO_BRIGHTNESS_ADJ, 0);
488
Amith Yamasani8b619832010-09-22 16:11:59 -0700489 // SCREEN_BRIGHTNESS_MODE, default to manual
490 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
491 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 // recalculate everything
494 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700495
Jim Miller92e66dd2012-02-21 18:57:12 -0800496 mWindowScaleAnimation = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
Joe Onorato609695d2010-10-14 14:57:49 -0700497 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
498 mAnimationSetting = 0;
Jim Miller92e66dd2012-02-21 18:57:12 -0800499 if (mWindowScaleAnimation > 0.5f) {
Joe Onorato609695d2010-10-14 14:57:49 -0700500 mAnimationSetting |= ANIM_SETTING_OFF;
501 }
502 if (transitionScale > 0.5f) {
503 // Uncomment this if you want the screen-on animation.
504 // mAnimationSetting |= ANIM_SETTING_ON;
505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
507 }
508 }
509
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700510 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 // Hack to get our uid... should have a func for this.
512 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700513 MY_UID = Process.myUid();
514 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 Binder.restoreCallingIdentity(token);
516
517 // XXX remove this when the kernel doesn't timeout wake locks
518 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
519
520 // assume nothing is on yet
521 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 // Add ourself to the Watchdog monitors.
524 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526
527 private ContentQueryMap mSettings;
528
Mike Lockwood3a322132009-11-24 00:30:52 -0500529 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700530 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500531 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 mContext = context;
533 mActivityService = activity;
534 mBatteryStats = BatteryStatsService.getService();
535 mBatteryService = battery;
536
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500537 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
538 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
539 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
540 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700541 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500542
Joe Onoratob08a1af2010-10-11 19:28:58 -0700543 nativeInit();
544 synchronized (mLocks) {
545 updateNativePowerStateLocked();
546 }
547
548 mInitComplete = false;
Jim Miller92e66dd2012-02-21 18:57:12 -0800549 mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread",
550 Process.THREAD_PRIORITY_DISPLAY);
551 mScreenBrightnessAnimator.start();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700552
Jim Miller92e66dd2012-02-21 18:57:12 -0800553 synchronized (mScreenBrightnessAnimator) {
Joe Onoratob08a1af2010-10-11 19:28:58 -0700554 while (!mInitComplete) {
555 try {
Jim Miller92e66dd2012-02-21 18:57:12 -0800556 mScreenBrightnessAnimator.wait();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700557 } catch (InterruptedException e) {
558 // Ignore
559 }
560 }
561 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800562
Joe Onoratob08a1af2010-10-11 19:28:58 -0700563 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 mHandlerThread = new HandlerThread("PowerManagerService") {
565 @Override
566 protected void onLooperPrepared() {
567 super.onLooperPrepared();
568 initInThread();
569 }
570 };
571 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 synchronized (mHandlerThread) {
574 while (!mInitComplete) {
575 try {
576 mHandlerThread.wait();
577 } catch (InterruptedException e) {
578 // Ignore
579 }
580 }
581 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800582
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700583 nativeInit();
Todd Poynor94d00242012-01-11 20:14:34 -0800584 Power.powerInitNative();
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700585 synchronized (mLocks) {
586 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700587 // We make sure to start out with the screen on due to user activity.
588 // (They did just boot their device, after all.)
589 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700590 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 void initInThread() {
595 mHandler = new Handler();
596
597 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700598 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
600 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
601 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
602 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
603 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
604 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500605 mProximityPartialLock = new UnsynchronizedWakeLock(
606 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
608 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
609 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
610 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
611 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
612
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700613 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400614
Joe Onoratob08a1af2010-10-11 19:28:58 -0700615 mAnimateScreenLights = resources.getBoolean(
616 com.android.internal.R.bool.config_animateScreenLights);
617
Joe Onorato6d747652010-10-11 15:15:31 -0700618 mUnplugTurnsOnScreen = resources.getBoolean(
619 com.android.internal.R.bool.config_unplugTurnsOnScreen);
620
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400621 mScreenBrightnessDim = resources.getInteger(
622 com.android.internal.R.integer.config_screenBrightnessDim);
623
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400624 // read settings for auto-brightness
625 mUseSoftwareAutoBrightness = resources.getBoolean(
626 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400627 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700628 mAutoBrightnessLevels = resources.getIntArray(
629 com.android.internal.R.array.config_autoBrightnessLevels);
630 mLcdBacklightValues = resources.getIntArray(
631 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
632 mButtonBacklightValues = resources.getIntArray(
633 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
634 mKeyboardBacklightValues = resources.getIntArray(
635 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500636 mLightSensorWarmupTime = resources.getInteger(
637 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700638 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700639
640 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
642 "(" + Settings.System.NAME + "=?) or ("
643 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700644 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700645 + Settings.System.NAME + "=?) or ("
646 + Settings.System.NAME + "=?) or ("
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800647 + Settings.System.NAME + "=?) or ("
648 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 + Settings.System.NAME + "=?)",
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800650 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS,
651 SCREEN_BRIGHTNESS_MODE, SCREEN_AUTO_BRIGHTNESS_ADJ,
652 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 null);
654 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
655 SettingsObserver settingsObserver = new SettingsObserver();
656 mSettings.addObserver(settingsObserver);
657
658 // pretend that the settings changed so we will get their initial state
659 settingsObserver.update(mSettings, null);
660
661 // register for the battery changed notifications
662 IntentFilter filter = new IntentFilter();
663 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
664 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500665 filter = new IntentFilter();
666 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
667 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500668 filter = new IntentFilter();
669 filter.addAction(Intent.ACTION_DOCK_EVENT);
670 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
Doug Zongker43866e02010-01-07 12:09:54 -0800672 // Listen for secure settings changes
673 mContext.getContentResolver().registerContentObserver(
674 Settings.Secure.CONTENT_URI, true,
675 new ContentObserver(new Handler()) {
676 public void onChange(boolean selfChange) {
677 updateSettingsValues();
678 }
679 });
680 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 synchronized (mHandlerThread) {
683 mInitComplete = true;
684 mHandlerThread.notifyAll();
685 }
686 }
687
688 private class WakeLock implements IBinder.DeathRecipient
689 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700690 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 super();
692 flags = f;
693 binder = b;
694 tag = t;
695 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700696 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 if (u != MY_UID || (
698 !"KEEP_SCREEN_ON_FLAG".equals(tag)
699 && !"KeyInputQueue".equals(tag))) {
700 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
701 ? BatteryStats.WAKE_TYPE_PARTIAL
702 : BatteryStats.WAKE_TYPE_FULL;
703 } else {
704 monitorType = -1;
705 }
706 try {
707 b.linkToDeath(this, 0);
708 } catch (RemoteException e) {
709 binderDied();
710 }
711 }
712 public void binderDied() {
713 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500714 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716 }
717 final int flags;
718 final IBinder binder;
719 final String tag;
720 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400721 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700723 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 boolean activated = true;
725 int minState;
726 }
727
728 private void updateWakeLockLocked() {
729 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
730 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
731 mStayOnWhilePluggedInScreenDimLock.acquire();
732 mStayOnWhilePluggedInPartialLock.acquire();
733 } else {
734 mStayOnWhilePluggedInScreenDimLock.release();
735 mStayOnWhilePluggedInPartialLock.release();
736 }
737 }
738
739 private boolean isScreenLock(int flags)
740 {
741 int n = flags & LOCK_MASK;
742 return n == PowerManager.FULL_WAKE_LOCK
743 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400744 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
745 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700748 void enforceWakeSourcePermission(int uid, int pid) {
749 if (uid == Process.myUid()) {
750 return;
751 }
752 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
753 pid, uid, null);
754 }
755
756 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700758 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700759 if (uid != Process.myUid()) {
760 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
761 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700762 if (ws != null) {
763 enforceWakeSourcePermission(uid, pid);
764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 long ident = Binder.clearCallingIdentity();
766 try {
767 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700768 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
770 } finally {
771 Binder.restoreCallingIdentity(ident);
772 }
773 }
774
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700775 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700776 if (wl.monitorType >= 0) {
777 long origId = Binder.clearCallingIdentity();
778 try {
779 if (ws != null) {
780 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
781 wl.monitorType);
782 } else {
783 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
784 }
785 } catch (RemoteException e) {
786 // Ignore
787 } finally {
788 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700789 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 }
791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700793 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700794 if (wl.monitorType >= 0) {
795 long origId = Binder.clearCallingIdentity();
796 try {
797 if (ws != null) {
798 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
799 wl.monitorType);
800 } else {
801 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
802 }
803 } catch (RemoteException e) {
804 // Ignore
805 } finally {
806 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700807 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700808 }
809 }
810
811 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
812 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800814 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700817 if (ws != null && ws.size() == 0) {
818 ws = null;
819 }
820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 int index = mLocks.getIndex(lock);
822 WakeLock wl;
823 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700824 boolean diffsource;
825 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700827 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 switch (wl.flags & LOCK_MASK)
829 {
830 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500831 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400832 wl.minState = SCREEN_BRIGHT;
833 } else {
834 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 break;
837 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
838 wl.minState = SCREEN_BRIGHT;
839 break;
840 case PowerManager.SCREEN_DIM_WAKE_LOCK:
841 wl.minState = SCREEN_DIM;
842 break;
843 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700844 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 break;
846 default:
847 // just log and bail. we're in the server, so don't
848 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800849 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 + " flags=" + flags);
851 return;
852 }
853 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700854 if (ws != null) {
855 wl.ws = new WorkSource(ws);
856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700858 diffsource = false;
859 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 } else {
861 wl = mLocks.get(index);
862 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700863 oldsource = wl.ws;
864 if (oldsource != null) {
865 if (ws == null) {
866 wl.ws = null;
867 diffsource = true;
868 } else {
869 diffsource = oldsource.diff(ws);
870 }
871 } else if (ws != null) {
872 diffsource = true;
873 } else {
874 diffsource = false;
875 }
876 if (diffsource) {
877 wl.ws = new WorkSource(ws);
878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880 if (isScreenLock(flags)) {
881 // if this causes a wakeup, we reactivate all of the locks and
882 // set it to whatever they want. otherwise, we modulate that
883 // by the current state so we never turn it more on than
884 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400885 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
886 mProximityWakeLockCount++;
887 if (mProximityWakeLockCount == 1) {
888 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400891 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
892 int oldWakeLockState = mWakeLockState;
893 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400894
895 // Disable proximity sensor if if user presses power key while we are in the
896 // "waiting for proximity sensor to go negative" state.
897 if ((mWakeLockState & SCREEN_ON_BIT) != 0
898 && mProximitySensorActive && mProximityWakeLockCount == 0) {
899 mProximitySensorActive = false;
900 }
901
Joe Onorato8274a0e2010-10-05 17:38:09 -0400902 if (mSpew) {
903 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
904 + " mWakeLockState=0x"
905 + Integer.toHexString(mWakeLockState)
906 + " previous wakeLockState=0x"
907 + Integer.toHexString(oldWakeLockState));
908 }
909 } else {
910 if (mSpew) {
911 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
912 + " mLocks.gatherState()=0x"
913 + Integer.toHexString(mLocks.gatherState())
914 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
915 }
916 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400918 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 }
921 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
922 if (newlock) {
923 mPartialCount++;
924 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800925 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927 }
928 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700931 if (diffsource) {
932 // If the lock sources have changed, need to first release the
933 // old ones.
934 noteStopWakeLocked(wl, oldsource);
935 }
936 if (newlock || diffsource) {
937 noteStartWakeLocked(wl, ws);
938 }
939 }
940
941 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
942 int uid = Binder.getCallingUid();
943 int pid = Binder.getCallingPid();
944 if (ws != null && ws.size() == 0) {
945 ws = null;
946 }
947 if (ws != null) {
948 enforceWakeSourcePermission(uid, pid);
949 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700950 synchronized (mLocks) {
951 int index = mLocks.getIndex(lock);
952 if (index < 0) {
953 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700955 WakeLock wl = mLocks.get(index);
956 WorkSource oldsource = wl.ws;
957 wl.ws = ws != null ? new WorkSource(ws) : null;
958 noteStopWakeLocked(wl, oldsource);
959 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 }
962
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500963 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700964 int uid = Binder.getCallingUid();
965 if (uid != Process.myUid()) {
966 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968
969 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500970 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
972 }
973
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500974 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 WakeLock wl = mLocks.removeLock(lock);
976 if (wl == null) {
977 return;
978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800981 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
983 }
984
985 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400986 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
987 mProximityWakeLockCount--;
988 if (mProximityWakeLockCount == 0) {
989 if (mProximitySensorActive &&
990 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
991 // wait for proximity sensor to go negative before disabling sensor
992 if (mDebugProximitySensor) {
993 Slog.d(TAG, "waiting for proximity sensor to go negative");
994 }
995 } else {
996 disableProximityLockLocked();
997 }
998 }
999 } else {
1000 mWakeLockState = mLocks.gatherState();
1001 // goes in the middle to reduce flicker
1002 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
1003 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
1004 }
1005 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
1009 mPartialCount--;
1010 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001011 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 Power.releaseWakeLock(PARTIAL_NAME);
1013 }
1014 }
1015 // Unlink the lock from the binder.
1016 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017
Dianne Hackborn70be1672010-09-14 11:13:03 -07001018 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
1020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 private class PokeLock implements IBinder.DeathRecipient
1022 {
1023 PokeLock(int p, IBinder b, String t) {
1024 super();
1025 this.pokey = p;
1026 this.binder = b;
1027 this.tag = t;
1028 try {
1029 b.linkToDeath(this, 0);
1030 } catch (RemoteException e) {
1031 binderDied();
1032 }
1033 }
1034 public void binderDied() {
1035 setPokeLock(0, this.binder, this.tag);
1036 }
1037 int pokey;
1038 IBinder binder;
1039 String tag;
1040 boolean awakeOnSet;
1041 }
1042
1043 public void setPokeLock(int pokey, IBinder token, String tag) {
1044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1045 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001046 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 return;
1048 }
1049
1050 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1051 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1052 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1053 }
1054
1055 synchronized (mLocks) {
1056 if (pokey != 0) {
1057 PokeLock p = mPokeLocks.get(token);
1058 int oldPokey = 0;
1059 if (p != null) {
1060 oldPokey = p.pokey;
1061 p.pokey = pokey;
1062 } else {
1063 p = new PokeLock(pokey, token, tag);
1064 mPokeLocks.put(token, p);
1065 }
1066 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1067 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1068 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1069 p.awakeOnSet = true;
1070 }
1071 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001072 PokeLock rLock = mPokeLocks.remove(token);
1073 if (rLock != null) {
1074 token.unlinkToDeath(rLock, 0);
1075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
1078 int oldPokey = mPokey;
1079 int cumulative = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 boolean awakeOnSet = false;
1081 for (PokeLock p: mPokeLocks.values()) {
1082 cumulative |= p.pokey;
1083 if (p.awakeOnSet) {
1084 awakeOnSet = true;
1085 }
1086 }
1087 mPokey = cumulative;
1088 mPokeAwakeOnSet = awakeOnSet;
1089
1090 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1091 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (oldCumulativeTimeout != newCumulativeTimeout) {
1094 setScreenOffTimeoutsLocked();
1095 // reset the countdown timer, but use the existing nextState so it doesn't
1096 // change anything
1097 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1098 }
1099 }
1100 }
1101
1102 private static String lockType(int type)
1103 {
1104 switch (type)
1105 {
1106 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001107 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001109 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001111 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001113 return "PARTIAL_WAKE_LOCK ";
1114 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1115 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 default:
David Brown251faa62009-08-02 22:04:36 -07001117 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
1120
1121 private static String dumpPowerState(int state) {
1122 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1123 ? "KEYBOARD_BRIGHT_BIT " : "")
1124 + (((state & SCREEN_BRIGHT_BIT) != 0)
1125 ? "SCREEN_BRIGHT_BIT " : "")
1126 + (((state & SCREEN_ON_BIT) != 0)
1127 ? "SCREEN_ON_BIT " : "")
1128 + (((state & BATTERY_LOW_BIT) != 0)
1129 ? "BATTERY_LOW_BIT " : "");
1130 }
1131
1132 @Override
1133 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1134 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1135 != PackageManager.PERMISSION_GRANTED) {
1136 pw.println("Permission Denial: can't dump PowerManager from from pid="
1137 + Binder.getCallingPid()
1138 + ", uid=" + Binder.getCallingUid());
1139 return;
1140 }
1141
1142 long now = SystemClock.uptimeMillis();
1143
Mike Lockwoodca44df82010-02-25 13:48:49 -05001144 synchronized (mLocks) {
1145 pw.println("Power Manager State:");
1146 pw.println(" mIsPowered=" + mIsPowered
1147 + " mPowerState=" + mPowerState
1148 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1149 + " ms");
1150 pw.println(" mPartialCount=" + mPartialCount);
1151 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1152 pw.println(" mUserState=" + dumpPowerState(mUserState));
1153 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1154 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1155 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1156 + " " + ((mNextTimeout-now)/1000) + "s from now");
1157 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001158 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001159 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1160 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001161 pw.println(" mScreenOffReason=" + mScreenOffReason
1162 + " mUserState=" + mUserState);
1163 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1164 + ',' + mBroadcastQueue[2] + "}");
1165 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1166 + ',' + mBroadcastWhy[2] + "}");
1167 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1168 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1169 + " mUserActivityAllowed=" + mUserActivityAllowed);
1170 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1171 + " mScreenOffDelay=" + mScreenOffDelay);
1172 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1173 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1174 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1175 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1176 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1177 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1178 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1179 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1180 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1181 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1182 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1183 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1184 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1185 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1186 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1187 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08001188 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled
1189 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001190 pw.println(" mLightSensorValue=" + mLightSensorValue
1191 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001192 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1193 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001194 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1195 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1196 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1197 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1198 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
Jim Miller92e66dd2012-02-21 18:57:12 -08001199 mScreenBrightnessAnimator.dump(pw, " mScreenBrightnessAnimator: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001200
Mike Lockwoodca44df82010-02-25 13:48:49 -05001201 int N = mLocks.size();
1202 pw.println();
1203 pw.println("mLocks.size=" + N + ":");
1204 for (int i=0; i<N; i++) {
1205 WakeLock wl = mLocks.get(i);
1206 String type = lockType(wl.flags & LOCK_MASK);
1207 String acquireCausesWakeup = "";
1208 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1209 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1210 }
1211 String activated = "";
1212 if (wl.activated) {
1213 activated = " activated";
1214 }
1215 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001216 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1217 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001219
1220 pw.println();
1221 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1222 for (PokeLock p: mPokeLocks.values()) {
1223 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001224 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1225 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001226 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1227 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1228 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1229 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001231
Mike Lockwoodca44df82010-02-25 13:48:49 -05001232 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235
Joe Onorato7999bff2010-07-24 11:50:05 -04001236 private void setTimeoutLocked(long now, int nextState) {
1237 setTimeoutLocked(now, -1, nextState);
1238 }
1239
1240 // If they gave a timeoutOverride it is the number of seconds
1241 // to screen-off. Figure out where in the countdown cycle we
1242 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001243 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1244 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001245 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001246 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001247 long when = 0;
1248 if (timeoutOverride <= 0) {
1249 switch (nextState)
1250 {
1251 case SCREEN_BRIGHT:
1252 when = now + mKeylightDelay;
1253 break;
1254 case SCREEN_DIM:
1255 if (mDimDelay >= 0) {
1256 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001257 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001258 } else {
1259 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1260 }
1261 case SCREEN_OFF:
1262 synchronized (mLocks) {
1263 when = now + mScreenOffDelay;
1264 }
1265 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001266 default:
1267 when = now;
1268 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001270 } else {
1271 override: {
1272 if (timeoutOverride <= mScreenOffDelay) {
1273 when = now + timeoutOverride;
1274 nextState = SCREEN_OFF;
1275 break override;
1276 }
1277 timeoutOverride -= mScreenOffDelay;
1278
1279 if (mDimDelay >= 0) {
1280 if (timeoutOverride <= mDimDelay) {
1281 when = now + timeoutOverride;
1282 nextState = SCREEN_DIM;
1283 break override;
1284 }
1285 timeoutOverride -= mDimDelay;
1286 }
1287
1288 when = now + timeoutOverride;
1289 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001291 }
1292 if (mSpew) {
1293 Slog.d(TAG, "setTimeoutLocked now=" + now
1294 + " timeoutOverride=" + timeoutOverride
1295 + " nextState=" + nextState + " when=" + when);
1296 }
Joe Onorato797e6882010-08-26 14:46:01 -04001297
1298 mHandler.removeCallbacks(mTimeoutTask);
1299 mTimeoutTask.nextState = nextState;
1300 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1301 ? (originalTimeoutOverride - timeoutOverride)
1302 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001303 mHandler.postAtTime(mTimeoutTask, when);
1304 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 }
1307 }
1308
1309 private void cancelTimerLocked()
1310 {
1311 mHandler.removeCallbacks(mTimeoutTask);
1312 mTimeoutTask.nextState = -1;
1313 }
1314
1315 private class TimeoutTask implements Runnable
1316 {
1317 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001318 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 public void run()
1320 {
1321 synchronized (mLocks) {
1322 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001323 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325
1326 if (nextState == -1) {
1327 return;
1328 }
1329
1330 mUserState = this.nextState;
1331 setPowerState(this.nextState | mWakeLockState);
1332
1333 long now = SystemClock.uptimeMillis();
1334
1335 switch (this.nextState)
1336 {
1337 case SCREEN_BRIGHT:
1338 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001339 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 break;
1341 }
1342 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001343 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 break;
1345 }
1346 }
1347 }
1348 }
1349
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001350 private void sendNotificationLocked(boolean on, int why) {
1351 if (!mInitialized) {
1352 // No notifications sent until first initialization is done.
1353 // This is so that when we are moving from our initial state
1354 // which looks like the screen was off to it being on, we do not
1355 // go through the process of waiting for the higher-level user
1356 // space to be ready before turning up the display brightness.
1357 // (And also do not send needless broadcasts about the screen.)
1358 return;
1359 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001360
1361 if (DEBUG_SCREEN_ON) {
1362 RuntimeException here = new RuntimeException("here");
1363 here.fillInStackTrace();
1364 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1365 }
1366
Joe Onorato64c62ba2009-03-24 20:13:57 -07001367 if (!on) {
1368 mStillNeedSleepNotification = false;
1369 }
1370
Joe Onorato128e7292009-03-24 18:41:31 -07001371 // Add to the queue.
1372 int index = 0;
1373 while (mBroadcastQueue[index] != -1) {
1374 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
Joe Onorato128e7292009-03-24 18:41:31 -07001376 mBroadcastQueue[index] = on ? 1 : 0;
1377 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378
Joe Onorato128e7292009-03-24 18:41:31 -07001379 // If we added it position 2, then there is a pair that can be stripped.
1380 // If we added it position 1 and we're turning the screen off, we can strip
1381 // the pair and do nothing, because the screen is already off, and therefore
1382 // keyguard has already been enabled.
1383 // However, if we added it at position 1 and we're turning it on, then position
1384 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1385 // on, so have to run the queue then.
1386 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001387 // While we're collapsing them, if it's going off, and the new reason
1388 // is more significant than the first, then use the new one.
1389 if (!on && mBroadcastWhy[0] > why) {
1390 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001391 }
1392 mBroadcastQueue[0] = on ? 1 : 0;
1393 mBroadcastQueue[1] = -1;
1394 mBroadcastQueue[2] = -1;
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();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001397 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001398 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001399 index = 0;
1400 }
1401 if (index == 1 && !on) {
1402 mBroadcastQueue[0] = -1;
1403 mBroadcastQueue[1] = -1;
1404 index = -1;
1405 // The wake lock was being held, but we're not actually going to do any
1406 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001409 }
1410
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001411 // The broadcast queue has changed; make sure the screen is on if it
1412 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001413 if (mSkippedScreenOn) {
1414 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1415 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001416
Joe Onorato128e7292009-03-24 18:41:31 -07001417 // Now send the message.
1418 if (index >= 0) {
1419 // Acquire the broadcast wake lock before changing the power
1420 // state. It will be release after the broadcast is sent.
1421 // We always increment the ref count for each notification in the queue
1422 // and always decrement when that notification is handled.
1423 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001424 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001425 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 }
1428
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001429 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1430 new WindowManagerPolicy.ScreenOnListener() {
Jim Miller92e66dd2012-02-21 18:57:12 -08001431 public void onScreenOn() {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001432 synchronized (mLocks) {
1433 if (mPreparingForScreenOn) {
1434 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001435 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001436 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1437 4, mBroadcastWakeLock.mCount);
1438 mBroadcastWakeLock.release();
1439 }
1440 }
1441 }
1442 };
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 private Runnable mNotificationTask = new Runnable()
1445 {
1446 public void run()
1447 {
Joe Onorato128e7292009-03-24 18:41:31 -07001448 while (true) {
1449 int value;
1450 int why;
1451 WindowManagerPolicy policy;
1452 synchronized (mLocks) {
1453 value = mBroadcastQueue[0];
1454 why = mBroadcastWhy[0];
1455 for (int i=0; i<2; i++) {
1456 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1457 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1458 }
1459 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001460 if (value == 1 && !mPreparingForScreenOn) {
1461 mPreparingForScreenOn = true;
1462 mBroadcastWakeLock.acquire();
1463 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1464 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
Joe Onorato128e7292009-03-24 18:41:31 -07001467 if (value == 1) {
1468 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001470 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001471 try {
1472 ActivityManagerNative.getDefault().wakingUp();
1473 } catch (RemoteException e) {
1474 // ignore it
1475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476
Joe Onorato128e7292009-03-24 18:41:31 -07001477 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001479 }
1480 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1481 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1482 mScreenOnBroadcastDone, mHandler, 0, null, null);
1483 } else {
1484 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001485 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001486 mBroadcastWakeLock.mCount);
1487 mBroadcastWakeLock.release();
1488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 }
Joe Onorato128e7292009-03-24 18:41:31 -07001491 else if (value == 0) {
1492 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001493
Joe Onorato128e7292009-03-24 18:41:31 -07001494 policy.screenTurnedOff(why);
1495 try {
1496 ActivityManagerNative.getDefault().goingToSleep();
1497 } catch (RemoteException e) {
1498 // ignore it.
1499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
Joe Onorato128e7292009-03-24 18:41:31 -07001501 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1502 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1503 mScreenOffBroadcastDone, mHandler, 0, null, null);
1504 } else {
1505 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001507 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001508 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001509 mBroadcastWakeLock.release();
1510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
Joe Onorato128e7292009-03-24 18:41:31 -07001513 else {
1514 // If we're in this case, then this handler is running for a previous
1515 // paired transaction. mBroadcastWakeLock will already have been released.
1516 break;
1517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 }
1519 }
1520 };
1521
1522 long mScreenOnStart;
1523 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1524 public void onReceive(Context context, Intent intent) {
1525 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1528 mBroadcastWakeLock.release();
1529 }
1530 }
1531 };
1532
1533 long mScreenOffStart;
1534 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1535 public void onReceive(Context context, Intent intent) {
1536 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001537 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1539 mBroadcastWakeLock.release();
1540 }
1541 }
1542 };
1543
1544 void logPointerUpEvent() {
1545 if (LOG_TOUCH_DOWNS) {
1546 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1547 mLastTouchDown = 0;
1548 }
1549 }
1550
1551 void logPointerDownEvent() {
1552 if (LOG_TOUCH_DOWNS) {
1553 // If we are not already timing a down/up sequence
1554 if (mLastTouchDown == 0) {
1555 mLastTouchDown = SystemClock.elapsedRealtime();
1556 mTouchCycles++;
1557 }
1558 }
1559 }
1560
1561 /**
1562 * Prevents the screen from turning on even if it *should* turn on due
1563 * to a subsequent full wake lock being acquired.
1564 * <p>
1565 * This is a temporary hack that allows an activity to "cover up" any
1566 * display glitches that happen during the activity's startup
1567 * sequence. (Specifically, this API was added to work around a
1568 * cosmetic bug in the "incoming call" sequence, where the lock screen
1569 * would flicker briefly before the incoming call UI became visible.)
1570 * TODO: There ought to be a more elegant way of doing this,
1571 * probably by having the PowerManager and ActivityManager
1572 * work together to let apps specify that the screen on/off
1573 * state should be synchronized with the Activity lifecycle.
1574 * <p>
1575 * Note that calling preventScreenOn(true) will NOT turn the screen
1576 * off if it's currently on. (This API only affects *future*
1577 * acquisitions of full wake locks.)
1578 * But calling preventScreenOn(false) WILL turn the screen on if
1579 * it's currently off because of a prior preventScreenOn(true) call.
1580 * <p>
1581 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1582 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1583 * call doesn't occur within 5 seconds, we'll turn the screen back on
1584 * ourselves (and log a warning about it); this prevents a buggy app
1585 * from disabling the screen forever.)
1586 * <p>
1587 * TODO: this feature should really be controlled by a new type of poke
1588 * lock (rather than an IPowerManager call).
1589 */
1590 public void preventScreenOn(boolean prevent) {
1591 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1592
1593 synchronized (mLocks) {
1594 if (prevent) {
1595 // First of all, grab a partial wake lock to
1596 // make sure the CPU stays on during the entire
1597 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1598 mPreventScreenOnPartialLock.acquire();
1599
1600 // Post a forceReenableScreen() call (for 5 seconds in the
1601 // future) to make sure the matching preventScreenOn(false) call
1602 // has happened by then.
1603 mHandler.removeCallbacks(mForceReenableScreenTask);
1604 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1605
1606 // Finally, set the flag that prevents the screen from turning on.
1607 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001608 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 mPreventScreenOn = true;
1610 } else {
1611 // (Re)enable the screen.
1612 mPreventScreenOn = false;
1613
1614 // We're "undoing" a the prior preventScreenOn(true) call, so we
1615 // no longer need the 5-second safeguard.
1616 mHandler.removeCallbacks(mForceReenableScreenTask);
1617
1618 // Forcibly turn on the screen if it's supposed to be on. (This
1619 // handles the case where the screen is currently off because of
1620 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001621 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001623 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1625 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001626 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001628 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 }
1630 }
1631
1632 // Release the partial wake lock that we held during the
1633 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1634 mPreventScreenOnPartialLock.release();
1635 }
1636 }
1637 }
1638
1639 public void setScreenBrightnessOverride(int brightness) {
1640 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1641
Mike Lockwoodf527c712010-06-10 14:12:33 -04001642 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 synchronized (mLocks) {
1644 if (mScreenBrightnessOverride != brightness) {
1645 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001646 if (isScreenOn()) {
1647 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
1651 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001652
1653 public void setButtonBrightnessOverride(int brightness) {
1654 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1655
Mike Lockwoodf527c712010-06-10 14:12:33 -04001656 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001657 synchronized (mLocks) {
1658 if (mButtonBrightnessOverride != brightness) {
1659 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001660 if (isScreenOn()) {
1661 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1662 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001663 }
1664 }
1665 }
1666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 /**
1668 * Sanity-check that gets called 5 seconds after any call to
1669 * preventScreenOn(true). This ensures that the original call
1670 * is followed promptly by a call to preventScreenOn(false).
1671 */
1672 private void forceReenableScreen() {
1673 // We shouldn't get here at all if mPreventScreenOn is false, since
1674 // we should have already removed any existing
1675 // mForceReenableScreenTask messages...
1676 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001677 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 return;
1679 }
1680
1681 // Uh oh. It's been 5 seconds since a call to
1682 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1683 // This means the app that called preventScreenOn(true) is either
1684 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1685 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1686 // crashed before doing so.)
1687
1688 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001689 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 + "Forcing the screen back on...");
1691 preventScreenOn(false);
1692 }
1693
1694 private Runnable mForceReenableScreenTask = new Runnable() {
1695 public void run() {
1696 forceReenableScreen();
1697 }
1698 };
1699
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001700 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001701 if (DEBUG_SCREEN_ON) {
1702 RuntimeException e = new RuntimeException("here");
1703 e.fillInStackTrace();
1704 Slog.i(TAG, "Set screen state: " + on, e);
1705 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001706 if (on) {
1707 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1708 // If we are turning the screen state on, but the screen
1709 // light is currently off, then make sure that we set the
1710 // light at this point to 0. This is the case where we are
1711 // turning on the screen and waiting for the UI to be drawn
1712 // before showing it to the user. We want the light off
1713 // until it is ready to be shown to the user, not it using
1714 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001715 if (DEBUG_SCREEN_ON) {
1716 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1717 + Integer.toHexString(mPowerState)
1718 + " mSkippedScreenOn=" + mSkippedScreenOn);
1719 }
Jim Miller46f31c32012-03-01 14:36:07 -08001720 mScreenBrightnessHandler.removeMessages(ScreenBrightnessAnimator.ANIMATE_LIGHTS);
Jim Miller92e66dd2012-02-21 18:57:12 -08001721 mScreenBrightnessAnimator.animateTo(Power.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
Dianne Hackborn474fd742011-10-10 18:40:22 -07001722 }
1723 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001724 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001725 if (err == 0) {
1726 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1727 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001728 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001729 if (!on) {
1730 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001731 mButtonLight.turnOff();
1732 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001733 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001734 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001735 }
1736 return err;
1737 }
1738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 private void setPowerState(int state)
1740 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001741 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743
Mike Lockwood435eb642009-12-03 08:40:18 -05001744 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 {
1746 synchronized (mLocks) {
1747 int err;
1748
1749 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001750 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001752 + " noChangeLights=" + noChangeLights
1753 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
Daniel Sandler7d276c32012-01-30 14:33:52 -05001755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (noChangeLights) {
1757 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1758 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001759 if (mProximitySensorActive) {
1760 // don't turn on the screen when the proximity sensor lock is held
1761 newState = (newState & ~SCREEN_BRIGHT);
1762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763
1764 if (batteryIsLow()) {
1765 newState |= BATTERY_LOW_BIT;
1766 } else {
1767 newState &= ~BATTERY_LOW_BIT;
1768 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001769 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 return;
1771 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001772
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001773 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 newState |= ALL_BRIGHT;
1775 }
1776
1777 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1778 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1779
Mike Lockwood51b844962009-11-16 21:51:18 -05001780 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001783 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001787 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001789 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001791 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1793 }
1794
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001795 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796
Daniel Sandler7d276c32012-01-30 14:33:52 -05001797 if (stateChanged && reason == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT) {
Daniel Sandler0af48952012-04-10 15:14:35 -04001798 if (mPolicy != null && mPolicy.isScreenSaverEnabled()) {
Daniel Sandler7d276c32012-01-30 14:33:52 -05001799 if (mSpew) {
1800 Slog.d(TAG, "setPowerState: running screen saver instead of turning off screen");
1801 }
1802 if (mPolicy.startScreenSaver()) {
1803 // was successful
1804 return;
1805 }
1806 }
1807 }
1808
1809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 if (oldScreenOn != newScreenOn) {
1811 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001812 // When the user presses the power button, we need to always send out the
1813 // notification that it's going to sleep so the keyguard goes on. But
1814 // we can't do that until the screen fades out, so we don't show the keyguard
1815 // too early.
1816 if (mStillNeedSleepNotification) {
1817 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1818 }
1819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 // Turn on the screen UNLESS there was a prior
1821 // preventScreenOn(true) request. (Note that the lifetime
1822 // of a single preventScreenOn() request is limited to 5
1823 // seconds to prevent a buggy app from disabling the
1824 // screen forever; see forceReenableScreen().)
1825 boolean reallyTurnScreenOn = true;
1826 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 + mPreventScreenOn);
1829 }
1830
1831 if (mPreventScreenOn) {
1832 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001833 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 reallyTurnScreenOn = false;
1836 }
1837 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001838 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 long identity = Binder.clearCallingIdentity();
1840 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001841 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 mBatteryStats.noteScreenOn();
1843 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001844 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 } finally {
1846 Binder.restoreCallingIdentity(identity);
1847 }
1848 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001849 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 // But continue as if we really did turn the screen on...
1851 err = 0;
1852 }
1853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 mLastTouchDown = 0;
1855 mTotalTouchDownTime = 0;
1856 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001857 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 mTotalTouchDownTime, mTouchCycles);
1859 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001861 // Update the lights *after* taking care of turning the
1862 // screen on, so we do this after our notifications are
1863 // enqueued and thus will delay turning on the screen light
1864 // until the windows are correctly displayed.
1865 if (stateChanged) {
1866 updateLightsLocked(newState, 0);
1867 }
1868 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001872 // Update the lights *before* taking care of turning the
1873 // screen off, so we can initiate any animations that are desired.
Craig Mautner44bf70f2012-03-13 11:38:38 -07001874 mScreenOffReason = reason;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001875 if (stateChanged) {
1876 updateLightsLocked(newState, 0);
1877 }
1878
Mike Lockwood497087e32009-11-08 18:33:03 -05001879 // cancel light sensor task
1880 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001881 mLightSensorPendingDecrease = false;
1882 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 mScreenOffTime = SystemClock.elapsedRealtime();
1884 long identity = Binder.clearCallingIdentity();
1885 try {
1886 mBatteryStats.noteScreenOff();
1887 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001888 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 } finally {
1890 Binder.restoreCallingIdentity(identity);
1891 }
1892 mPowerState &= ~SCREEN_ON_BIT;
Jim Miller92e66dd2012-02-21 18:57:12 -08001893 if (!mScreenBrightnessAnimator.isAnimating()) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001894 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 err = 0;
1897 mLastTouchDown = 0;
1898 }
1899 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001900 } else if (stateChanged) {
1901 // Screen on/off didn't change, but lights may have.
1902 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001904
1905 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1906
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001907 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001910
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001911 private void updateNativePowerStateLocked() {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001912 if (!mHeadless) {
1913 nativeSetPowerState(
1914 (mPowerState & SCREEN_ON_BIT) != 0,
1915 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1916 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001918
Mike Lockwood435eb642009-12-03 08:40:18 -05001919 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001921 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001923 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1924 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001926 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001928 mScreenOffReason = reason;
1929 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
1931 return err;
1932 }
1933
1934 private boolean batteryIsLow() {
1935 return (!mIsPowered &&
1936 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1937 }
1938
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001939 private boolean shouldDeferScreenOnLocked() {
1940 if (mPreparingForScreenOn) {
1941 // Currently waiting for confirmation from the policy that it
1942 // is okay to turn on the screen. Don't allow the screen to go
1943 // on until that is done.
1944 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1945 "updateLights: delaying screen on due to mPreparingForScreenOn");
1946 return true;
1947 } else {
1948 // If there is a screen-on command in the notification queue, we
1949 // can't turn the screen on until it has been processed (and we
1950 // have set mPreparingForScreenOn) or it has been dropped.
1951 for (int i=0; i<mBroadcastQueue.length; i++) {
1952 if (mBroadcastQueue[i] == 1) {
1953 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1954 "updateLights: delaying screen on due to notification queue");
1955 return true;
1956 }
1957 }
1958 }
1959 return false;
1960 }
1961
The Android Open Source Project10592532009-03-18 17:39:46 -07001962 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001963 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001964
1965 // If the screen is not currently on, we will want to delay actually
1966 // turning the lights on if we are still getting the UI put up.
Jim Miller92e66dd2012-02-21 18:57:12 -08001967 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001968 // Don't turn screen on until we know we are really ready to.
1969 // This is to avoid letting the screen go on before things like the
1970 // lock screen have been displayed.
Jim Miller92e66dd2012-02-21 18:57:12 -08001971 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001972 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1973 }
1974 }
1975
Joe Onorato60607a902010-10-23 14:49:30 -07001976 if ((newState & SCREEN_ON_BIT) != 0) {
1977 // Only turn on the buttons or keyboard if the screen is also on.
1978 // We should never see the buttons on but not the screen.
1979 newState = applyButtonState(newState);
1980 newState = applyKeyboardState(newState);
1981 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001982 final int realDifference = (newState ^ oldState);
1983 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001985 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 int offMask = 0;
1989 int dimMask = 0;
1990 int onMask = 0;
1991
1992 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001995 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1996 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001998 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000 }
2001
2002 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002003 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
2004 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002006 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008 }
2009
2010 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002011 int nominalCurrentValue = -1;
2012 // If there was an actual difference in the light state, then
2013 // figure out the "ideal" current value based on the previous
2014 // state. Otherwise, this is a change due to the brightness
2015 // override, so we want to animate from whatever the current
2016 // value is.
2017 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
2018 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
2019 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
2020 nominalCurrentValue = preferredBrightness;
2021 break;
2022 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002023 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002024 break;
2025 case 0:
2026 nominalCurrentValue = Power.BRIGHTNESS_OFF;
2027 break;
2028 case SCREEN_BRIGHT_BIT:
2029 default:
2030 // not possible
Jim Miller92e66dd2012-02-21 18:57:12 -08002031 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness();
Joe Onoratob08a1af2010-10-11 19:28:58 -07002032 break;
Joe Onorato128e7292009-03-24 18:41:31 -07002033 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 }
2035 int brightness = preferredBrightness;
2036 int steps = ANIM_STEPS;
2037 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
2038 // dim or turn off backlight, depending on if the screen is on
2039 // the scale is because the brightness ramp isn't linear and this biases
2040 // it so the later parts take longer.
2041 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002042 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002043 if (ratio > 1.0f) ratio = 1.0f;
2044 if ((newState & SCREEN_ON_BIT) == 0) {
2045 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2046 // was bright
2047 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002049 // was dim
2050 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002052 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002054 if ((oldState & SCREEN_ON_BIT) != 0) {
2055 // was bright
2056 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2057 } else {
2058 // was dim
2059 steps = (int)(ANIM_STEPS*ratio);
2060 }
2061 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2062 // If the "stay on while plugged in" option is
2063 // turned on, then the screen will often not
2064 // automatically turn off while plugged in. To
2065 // still have a sense of when it is inactive, we
2066 // will then count going dim as turning off.
2067 mScreenOffTime = SystemClock.elapsedRealtime();
2068 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002069 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002072 long identity = Binder.clearCallingIdentity();
2073 try {
2074 mBatteryStats.noteScreenBrightness(brightness);
2075 } catch (RemoteException e) {
2076 // Nothing interesting to do.
2077 } finally {
2078 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002080 if (!mSkippedScreenOn) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002081 int dt = steps * NOMINAL_FRAME_TIME_MS;
2082 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002083 if (DEBUG_SCREEN_ON) {
2084 RuntimeException e = new RuntimeException("here");
2085 e.fillInStackTrace();
2086 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2087 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002090
Joe Onorato60607a902010-10-23 14:49:30 -07002091 if (mSpew) {
2092 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2093 + " dimMask=0x" + Integer.toHexString(dimMask)
2094 + " onMask=0x" + Integer.toHexString(onMask)
2095 + " difference=0x" + Integer.toHexString(difference)
2096 + " realDifference=0x" + Integer.toHexString(realDifference)
2097 + " forceState=0x" + Integer.toHexString(forceState)
2098 );
2099 }
2100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002102 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002103 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002106 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 if ((newState & BATTERY_LOW_BIT) != 0 &&
2108 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2109 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2110 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002111 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002112 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 if (onMask != 0) {
2115 int brightness = getPreferredBrightness();
2116 if ((newState & BATTERY_LOW_BIT) != 0 &&
2117 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2118 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2119 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002120 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002121 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124
Jim Miller92e66dd2012-02-21 18:57:12 -08002125 /**
2126 * Note: by design this class does not hold mLocks while calling native methods.
2127 * Nor should it. Ever.
2128 */
2129 class ScreenBrightnessAnimator extends HandlerThread {
2130 static final int ANIMATE_LIGHTS = 10;
Jim Miller46f31c32012-03-01 14:36:07 -08002131 static final int ANIMATE_POWER_OFF = 11;
Jim Miller92e66dd2012-02-21 18:57:12 -08002132 volatile int startValue;
2133 volatile int endValue;
2134 volatile int currentValue;
2135 private int currentMask;
2136 private int duration;
2137 private long startTimeMillis;
2138 private final String prefix;
2139
2140 public ScreenBrightnessAnimator(String name, int priority) {
2141 super(name, priority);
2142 prefix = name;
2143 }
2144
2145 @Override
2146 protected void onLooperPrepared() {
2147 mScreenBrightnessHandler = new Handler() {
2148 public void handleMessage(Message msg) {
2149 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation
Mike Lockwood3a322132009-11-24 00:30:52 -05002150 ? LightsService.BRIGHTNESS_MODE_SENSOR
2151 : LightsService.BRIGHTNESS_MODE_USER);
Jim Miller92e66dd2012-02-21 18:57:12 -08002152 if (msg.what == ANIMATE_LIGHTS) {
2153 final int mask = msg.arg1;
2154 int value = msg.arg2;
2155 long tStart = SystemClock.uptimeMillis();
2156 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
2157 if (mDebugLightAnimation) Log.v(TAG, "Set brightness: " + value);
2158 mLcdLight.setBrightness(value, brightnessMode);
2159 }
2160 long elapsed = SystemClock.uptimeMillis() - tStart;
2161 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
2162 mButtonLight.setBrightness(value);
2163 }
2164 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
2165 mKeyboardLight.setBrightness(value);
2166 }
2167
2168 if (elapsed > 100) {
2169 Log.e(TAG, "Excessive delay setting brightness: " + elapsed
2170 + "ms, mask=" + mask);
2171 }
2172
2173 // Throttle brightness updates to frame refresh rate
2174 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 0;
2175 synchronized(this) {
2176 currentValue = value;
2177 }
2178 animateInternal(mask, false, delay);
Jim Miller46f31c32012-03-01 14:36:07 -08002179 } else if (msg.what == ANIMATE_POWER_OFF) {
2180 int mode = msg.arg1;
2181 nativeStartSurfaceFlingerAnimation(mode);
Jim Miller92e66dd2012-02-21 18:57:12 -08002182 }
2183 }
2184 };
2185 synchronized (this) {
2186 mInitComplete = true;
2187 notifyAll();
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002188 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002189 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002190
2191 private void animateInternal(int mask, boolean turningOff, int delay) {
2192 synchronized (this) {
2193 if (currentValue != endValue) {
2194 final long now = SystemClock.elapsedRealtime();
2195 final int elapsed = (int) (now - startTimeMillis);
2196 int newValue;
2197 if (elapsed < duration) {
2198 int delta = endValue - startValue;
2199 newValue = startValue + delta * elapsed / duration;
2200 newValue = Math.max(Power.BRIGHTNESS_OFF, newValue);
2201 newValue = Math.min(Power.BRIGHTNESS_ON, newValue);
2202 } else {
2203 newValue = endValue;
2204 mInitialAnimation = false;
2205 }
2206
2207 if (mDebugLightAnimation) {
2208 Log.v(TAG, "Animating light: " + "start:" + startValue
2209 + ", end:" + endValue + ", elapsed:" + elapsed
2210 + ", duration:" + duration + ", current:" + currentValue
2211 + ", delay:" + delay);
2212 }
2213
Jim Miller46f31c32012-03-01 14:36:07 -08002214 if (turningOff && !mHeadless && !mAnimateScreenLights) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002215 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR
2216 ? 0 : mAnimationSetting;
2217 if (mDebugLightAnimation) Log.v(TAG, "Doing power-off anim, mode=" + mode);
Jim Miller46f31c32012-03-01 14:36:07 -08002218 mScreenBrightnessHandler.obtainMessage(ANIMATE_POWER_OFF, mode, 0)
2219 .sendToTarget();
Jim Miller92e66dd2012-02-21 18:57:12 -08002220 }
2221 Message msg = mScreenBrightnessHandler
2222 .obtainMessage(ANIMATE_LIGHTS, mask, newValue);
2223 mScreenBrightnessHandler.sendMessageDelayed(msg, delay);
2224 }
2225 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002226 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002227
2228 public void dump(PrintWriter pw, String string) {
2229 pw.println(prefix + "animating: " + "start:" + startValue + ", end:" + endValue
2230 + ", duration:" + duration + ", current:" + currentValue);
2231 }
2232
2233 public void animateTo(int target, int mask, int animationDuration) {
2234 synchronized(this) {
2235 startValue = currentValue;
2236 endValue = target;
2237 currentMask = mask;
2238 duration = (int) (mWindowScaleAnimation * animationDuration);
2239 startTimeMillis = SystemClock.elapsedRealtime();
2240 mInitialAnimation = currentValue == 0 && target > 0;
2241
2242 if (mDebugLightAnimation) {
2243 Log.v(TAG, "animateTo(target=" + target + ", mask=" + mask
2244 + ", duration=" + animationDuration +")"
2245 + ", currentValue=" + currentValue
2246 + ", startTime=" + startTimeMillis);
2247 }
2248
2249 if (target != currentValue) {
Jim Miller18651802012-03-07 14:19:56 -08002250 final boolean doScreenAnim = (mask & (SCREEN_BRIGHT_BIT | SCREEN_ON_BIT)) != 0;
Jim Miller92e66dd2012-02-21 18:57:12 -08002251 final boolean turningOff = endValue == Power.BRIGHTNESS_OFF;
Jim Miller18651802012-03-07 14:19:56 -08002252 if (turningOff && doScreenAnim) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002253 // Cancel all pending animations since we're turning off
2254 mScreenBrightnessHandler.removeCallbacksAndMessages(null);
2255 screenOffFinishedAnimatingLocked(mScreenOffReason);
2256 duration = 200; // TODO: how long should this be?
2257 }
Jim Miller18651802012-03-07 14:19:56 -08002258 if (doScreenAnim) {
2259 animateInternal(mask, turningOff, 0);
2260 }
2261 // TODO: Handle keyboard light animation when we have devices that support it
Jim Miller92e66dd2012-02-21 18:57:12 -08002262 }
2263 }
2264 }
2265
2266 public int getCurrentBrightness() {
2267 synchronized (this) {
2268 return currentValue;
2269 }
2270 }
2271
2272 public boolean isAnimating() {
2273 synchronized (this) {
2274 return currentValue != endValue;
2275 }
2276 }
2277
2278 public void cancelAnimation() {
2279 animateTo(endValue, currentMask, 0);
The Android Open Source Project10592532009-03-18 17:39:46 -07002280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282
Jim Miller92e66dd2012-02-21 18:57:12 -08002283 private void setLightBrightness(int mask, int value) {
2284 mScreenBrightnessAnimator.animateTo(value, mask, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 private int getPreferredBrightness() {
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002288 if (mScreenBrightnessOverride >= 0) {
2289 return mScreenBrightnessOverride;
2290 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
2291 && mAutoBrightessEnabled) {
2292 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002294 final int brightness = mScreenBrightnessSetting;
2295 // Don't let applications turn the screen all the way off
2296 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
2298
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002299 private int applyButtonState(int state) {
2300 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002301 if ((state & BATTERY_LOW_BIT) != 0) {
2302 // do not override brightness if the battery is low
2303 return state;
2304 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002305 if (mButtonBrightnessOverride >= 0) {
2306 brightness = mButtonBrightnessOverride;
2307 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2308 brightness = mLightSensorButtonBrightness;
2309 }
2310 if (brightness > 0) {
2311 return state | BUTTON_BRIGHT_BIT;
2312 } else if (brightness == 0) {
2313 return state & ~BUTTON_BRIGHT_BIT;
2314 } else {
2315 return state;
2316 }
2317 }
2318
2319 private int applyKeyboardState(int state) {
2320 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002321 if ((state & BATTERY_LOW_BIT) != 0) {
2322 // do not override brightness if the battery is low
2323 return state;
2324 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002325 if (!mKeyboardVisible) {
2326 brightness = 0;
2327 } else if (mButtonBrightnessOverride >= 0) {
2328 brightness = mButtonBrightnessOverride;
2329 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2330 brightness = mLightSensorKeyboardBrightness;
2331 }
2332 if (brightness > 0) {
2333 return state | KEYBOARD_BRIGHT_BIT;
2334 } else if (brightness == 0) {
2335 return state & ~KEYBOARD_BRIGHT_BIT;
2336 } else {
2337 return state;
2338 }
2339 }
2340
Charles Mendis322591c2009-10-29 11:06:59 -07002341 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 synchronized (mLocks) {
2343 return (mPowerState & SCREEN_ON_BIT) != 0;
2344 }
2345 }
2346
Charles Mendis322591c2009-10-29 11:06:59 -07002347 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 synchronized (mLocks) {
2349 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2350 }
2351 }
2352
Mike Lockwood497087e32009-11-08 18:33:03 -05002353 private boolean isScreenTurningOffLocked() {
Jim Miller92e66dd2012-02-21 18:57:12 -08002354 return (mScreenBrightnessAnimator.isAnimating()
2355 && mScreenBrightnessAnimator.endValue == Power.BRIGHTNESS_OFF);
Mike Lockwood497087e32009-11-08 18:33:03 -05002356 }
2357
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002358 private boolean shouldLog(long time) {
2359 synchronized (mLocks) {
2360 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2361 mWarningSpewThrottleTime = time;
2362 mWarningSpewThrottleCount = 0;
2363 return true;
2364 } else if (mWarningSpewThrottleCount < 30) {
2365 mWarningSpewThrottleCount++;
2366 return true;
2367 } else {
2368 return false;
2369 }
2370 }
2371 }
2372
Mike Lockwood200b30b2009-09-20 00:23:59 -04002373 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002374 if (isScreenTurningOffLocked()) {
2375 // cancel animation so userActivity will succeed
Jim Miller92e66dd2012-02-21 18:57:12 -08002376 mScreenBrightnessAnimator.cancelAnimation();
Mike Lockwoode090281422009-11-14 21:02:56 -05002377 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002378 boolean savedActivityAllowed = mUserActivityAllowed;
2379 mUserActivityAllowed = true;
2380 userActivity(SystemClock.uptimeMillis(), false);
2381 mUserActivityAllowed = savedActivityAllowed;
2382 }
2383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2385 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002386 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 }
2388
2389 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002390 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2391 != PackageManager.PERMISSION_GRANTED) {
2392 if (shouldLog(time)) {
2393 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2394 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2395 }
2396 return;
2397 }
2398
Joe Onorato7999bff2010-07-24 11:50:05 -04002399 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
2401
2402 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002403 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
2405
2406 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002407 userActivity(time, -1, noChangeLights, eventType, force);
2408 }
2409
2410 /*
2411 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2412 * on with user activity. Don't use this function.
2413 */
2414 public void clearUserActivityTimeout(long now, long timeout) {
2415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2416 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2417 userActivity(now, timeout, false, OTHER_EVENT, false);
2418 }
2419
2420 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2421 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422
Joe Onorato1a542c72010-11-08 09:48:20 -08002423 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002424 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002425 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002426 }
2427 return;
2428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 synchronized (mLocks) {
2431 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002432 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 + " mUserActivityAllowed=" + mUserActivityAllowed
2434 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002435 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2436 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002437 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002438 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 }
Mike Lockwood05067122009-10-27 23:07:25 -04002440 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002441 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002442 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002443 return;
2444 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002445 // Disable proximity sensor if if user presses power key while we are in the
2446 // "waiting for proximity sensor to go negative" state.
2447 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2448 mProximitySensorActive = false;
2449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 if (mLastEventTime <= time || force) {
2451 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002452 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002453 // Only turn on button backlights if a button was pressed
2454 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002455 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2457 } else {
2458 // don't clear button/keyboard backlights when the screen is touched.
2459 mUserState |= SCREEN_BRIGHT;
2460 }
2461
Dianne Hackborn617f8772009-03-31 15:04:46 -07002462 int uid = Binder.getCallingUid();
2463 long ident = Binder.clearCallingIdentity();
2464 try {
2465 mBatteryStats.noteUserActivity(uid, eventType);
2466 } catch (RemoteException e) {
2467 // Ignore
2468 } finally {
2469 Binder.restoreCallingIdentity(ident);
2470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002471
Michael Chane96440f2009-05-06 10:27:36 -07002472 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002473 setPowerState(mUserState | mWakeLockState, noChangeLights,
2474 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002475 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
2477 }
2478 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002479
2480 if (mPolicy != null) {
2481 mPolicy.userActivity();
2482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002485 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2486 try {
2487 int i;
2488 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2489 if (sensorValue < mAutoBrightnessLevels[i]) {
2490 break;
2491 }
2492 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002493 // This is the range of brightness values that we can use.
2494 final int minval = values[0];
2495 final int maxval = values[mAutoBrightnessLevels.length];
2496 // This is the range we will be scaling. We put some padding
2497 // at the low and high end to give the adjustment a little better
2498 // impact on the actual observed value.
2499 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION;
2500 // This is the desired brightness value from 0.0 to 1.0.
2501 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range);
2502 // Apply a scaling to the value based on the adjustment.
2503 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) {
2504 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting);
2505 if (adj <= .00001) {
2506 valf = 1;
2507 } else {
2508 valf /= adj;
2509 }
2510 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) {
2511 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting);
2512 valf *= adj;
2513 }
2514 // Apply an additional offset to the value based on the adjustment.
2515 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE;
2516 // Convert the 0.0-1.0 value back to a brightness integer.
2517 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2);
2518 if (val < minval) val = minval;
2519 else if (val > maxval) val = maxval;
2520 return val;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002521 } catch (Exception e) {
2522 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002523 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002524 return 255;
2525 }
2526 }
2527
Mike Lockwood20f87d72009-11-05 16:08:51 -05002528 private Runnable mProximityTask = new Runnable() {
2529 public void run() {
2530 synchronized (mLocks) {
2531 if (mProximityPendingValue != -1) {
2532 proximityChangedLocked(mProximityPendingValue == 1);
2533 mProximityPendingValue = -1;
2534 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002535 if (mProximityPartialLock.isHeld()) {
2536 mProximityPartialLock.release();
2537 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002538 }
2539 }
2540 };
2541
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002542 private Runnable mAutoBrightnessTask = new Runnable() {
2543 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002544 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002545 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2546 int value = (int)mLightSensorPendingValue;
2547 mLightSensorPendingDecrease = false;
2548 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002549 lightSensorChangedLocked(value, false);
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002550 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002551 }
2552 }
2553 };
2554
Jim Miller92e66dd2012-02-21 18:57:12 -08002555 private boolean mInitialAnimation; // used to prevent lightsensor changes while turning on
2556
Mike Lockwoodb2865412010-02-02 22:40:33 -05002557 private void dockStateChanged(int state) {
2558 synchronized (mLocks) {
2559 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2560 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002561 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002562 mHighestLightSensorValue = -1;
2563 }
2564 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2565 // force lights recalculation
2566 int value = (int)mLightSensorValue;
2567 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002568 lightSensorChangedLocked(value, false);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002569 }
2570 }
2571 }
2572
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002573 private void lightSensorChangedLocked(int value, boolean immediate) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002574 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002575 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002576 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002577
Joe Onorato06eb33a2010-10-25 14:09:21 -07002578 // Don't do anything if the screen is off.
2579 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2580 if (mDebugLightSensor) {
2581 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2582 }
2583 return;
2584 }
2585
Mike Lockwoodb2865412010-02-02 22:40:33 -05002586 // do not allow light sensor value to decrease
2587 if (mHighestLightSensorValue < value) {
2588 mHighestLightSensorValue = value;
2589 }
2590
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002591 if (mLightSensorValue != value) {
2592 mLightSensorValue = value;
2593 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002594 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2595 // we only do this if we are undocked, since lighting should be stable when
2596 // stationary in a dock.
2597 int lcdValue = getAutoBrightnessValue(
2598 (mIsDocked ? value : mHighestLightSensorValue),
2599 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002600 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002601 int keyboardValue;
2602 if (mKeyboardVisible) {
2603 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2604 } else {
2605 keyboardValue = 0;
2606 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002607 mLightSensorScreenBrightness = lcdValue;
2608 mLightSensorButtonBrightness = buttonValue;
2609 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002610
2611 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002612 Slog.d(TAG, "lcdValue " + lcdValue);
2613 Slog.d(TAG, "buttonValue " + buttonValue);
2614 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002615 }
2616
Mike Lockwood4984e732009-11-01 08:16:33 -05002617 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002618 if (!mSkippedScreenOn && !mInitialAnimation) {
2619 int steps = immediate ? IMMEDIATE_ANIM_STEPS : AUTOBRIGHTNESS_ANIM_STEPS;
2620 mScreenBrightnessAnimator.cancelAnimation();
2621 mScreenBrightnessAnimator.animateTo(lcdValue,
2622 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002623 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002624 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002625 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002626 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002627 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002628 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002629 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002630 }
2631 }
2632 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002633 }
2634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 /**
2636 * The user requested that we go to sleep (probably with the power button).
2637 * This overrides all wake locks that are held.
2638 */
2639 public void goToSleep(long time)
2640 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002641 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2642 }
2643
2644 /**
2645 * The user requested that we go to sleep (probably with the power button).
2646 * This overrides all wake locks that are held.
2647 */
2648 public void goToSleepWithReason(long time, int reason)
2649 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2651 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002652 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002657 * Reboot the device immediately, passing 'reason' (may be null)
2658 * to the underlying __reboot system call. Should not return.
2659 */
2660 public void reboot(String reason)
2661 {
2662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002663
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002664 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2665 throw new IllegalStateException("Too early to call reboot()");
2666 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002667
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002668 final String finalReason = reason;
2669 Runnable runnable = new Runnable() {
2670 public void run() {
2671 synchronized (this) {
2672 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002673 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002674
San Mehat1e512792010-01-07 10:40:29 -08002675 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002676 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002677 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002678 mHandler.post(runnable);
2679
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002680 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002681 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002682 while (true) {
2683 try {
2684 runnable.wait();
2685 } catch (InterruptedException e) {
2686 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002687 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002688 }
2689 }
2690
Dan Egnor60d87622009-12-16 16:32:58 -08002691 /**
2692 * Crash the runtime (causing a complete restart of the Android framework).
2693 * Requires REBOOT permission. Mostly for testing. Should not return.
2694 */
2695 public void crash(final String message)
2696 {
2697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2698 Thread t = new Thread("PowerManagerService.crash()") {
2699 public void run() { throw new RuntimeException(message); }
2700 };
2701 try {
2702 t.start();
2703 t.join();
2704 } catch (InterruptedException e) {
2705 Log.wtf(TAG, e);
2706 }
2707 }
2708
Mike Lockwood435eb642009-12-03 08:40:18 -05002709 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710
2711 if (mLastEventTime <= time) {
2712 mLastEventTime = time;
2713 // cancel all of the wake locks
2714 mWakeLockState = SCREEN_OFF;
2715 int N = mLocks.size();
2716 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002717 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 for (int i=0; i<N; i++) {
2719 WakeLock wl = mLocks.get(i);
2720 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002721 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2722 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2723 proxLock = true;
2724 } else {
2725 mLocks.get(i).activated = false;
2726 numCleared++;
2727 }
2728 }
2729 }
2730 if (!proxLock) {
2731 mProxIgnoredBecauseScreenTurnedOff = true;
2732 if (mDebugProximitySensor) {
2733 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002737 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002739 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 cancelTimerLocked();
2741 }
2742 }
2743
2744 public long timeSinceScreenOn() {
2745 synchronized (mLocks) {
2746 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2747 return 0;
2748 }
2749 return SystemClock.elapsedRealtime() - mScreenOffTime;
2750 }
2751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002754 synchronized (mLocks) {
2755 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002756 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002757 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002758 if (mKeyboardVisible != visible) {
2759 mKeyboardVisible = visible;
2760 // don't signal user activity if the screen is off; other code
2761 // will take care of turning on due to a true change to the lid
2762 // switch and synchronized with the lock screen.
2763 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002764 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002765 // force recompute of backlight values
2766 if (mLightSensorValue >= 0) {
2767 int value = (int)mLightSensorValue;
2768 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002769 lightSensorChangedLocked(value, false);
Mike Lockwooddf024922009-10-29 21:29:15 -04002770 }
2771 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002772 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2773 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002774 }
2775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
2777
2778 /**
2779 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002780 * When disabling user activity we also reset user power state so the keyguard can reset its
2781 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 */
2783 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002784 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002785 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 synchronized (mLocks) {
2788 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002789 if (!enabled) {
2790 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2791 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 }
2794 }
2795
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002796 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002797 synchronized (mLocks) {
2798 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2799 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2800 mAutoBrightessEnabled = enabled;
2801 // This will get us a new value
2802 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002803 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002804 }
2805 }
2806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 /** Sets the screen off timeouts:
2808 * mKeylightDelay
2809 * mDimDelay
2810 * mScreenOffDelay
2811 * */
2812 private void setScreenOffTimeoutsLocked() {
2813 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002814 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 mDimDelay = -1;
2816 mScreenOffDelay = 0;
2817 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2818 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2819 mDimDelay = -1;
2820 mScreenOffDelay = 0;
2821 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002822 int totalDelay = mScreenOffTimeoutSetting;
2823 if (totalDelay > mMaximumScreenOffTimeout) {
2824 totalDelay = mMaximumScreenOffTimeout;
2825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2827 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002828 // negative number means stay on as long as possible.
2829 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 } else if (mKeylightDelay < totalDelay) {
2831 // subtract the time that the keylight delay. This will give us the
2832 // remainder of the time that we need to sleep to get the accurate
2833 // screen off timeout.
2834 mScreenOffDelay = totalDelay - mKeylightDelay;
2835 } else {
2836 mScreenOffDelay = 0;
2837 }
2838 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2839 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2840 mScreenOffDelay = LONG_DIM_TIME;
2841 } else {
2842 mDimDelay = -1;
2843 }
2844 }
2845 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002846 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2848 + " mDimScreen=" + mDimScreen);
2849 }
2850 }
2851
2852 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002853 * Refreshes cached secure settings. Called once on startup, and
2854 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 */
Doug Zongker43866e02010-01-07 12:09:54 -08002856 private void updateSettingsValues() {
2857 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002859 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002861 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
2863
2864 private class LockList extends ArrayList<WakeLock>
2865 {
2866 void addLock(WakeLock wl)
2867 {
2868 int index = getIndex(wl.binder);
2869 if (index < 0) {
2870 this.add(wl);
2871 }
2872 }
2873
2874 WakeLock removeLock(IBinder binder)
2875 {
2876 int index = getIndex(binder);
2877 if (index >= 0) {
2878 return this.remove(index);
2879 } else {
2880 return null;
2881 }
2882 }
2883
2884 int getIndex(IBinder binder)
2885 {
2886 int N = this.size();
2887 for (int i=0; i<N; i++) {
2888 if (this.get(i).binder == binder) {
2889 return i;
2890 }
2891 }
2892 return -1;
2893 }
2894
2895 int gatherState()
2896 {
2897 int result = 0;
2898 int N = this.size();
2899 for (int i=0; i<N; i++) {
2900 WakeLock wl = this.get(i);
2901 if (wl.activated) {
2902 if (isScreenLock(wl.flags)) {
2903 result |= wl.minState;
2904 }
2905 }
2906 }
2907 return result;
2908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002909
Michael Chane96440f2009-05-06 10:27:36 -07002910 int reactivateScreenLocksLocked()
2911 {
2912 int result = 0;
2913 int N = this.size();
2914 for (int i=0; i<N; i++) {
2915 WakeLock wl = this.get(i);
2916 if (isScreenLock(wl.flags)) {
2917 wl.activated = true;
2918 result |= wl.minState;
2919 }
2920 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002921 if (mDebugProximitySensor) {
2922 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2923 + mProxIgnoredBecauseScreenTurnedOff);
2924 }
2925 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002926 return result;
2927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002930 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 synchronized (mLocks) {
2932 mPolicy = p;
2933 mLocks.notifyAll();
2934 }
2935 }
2936
2937 WindowManagerPolicy getPolicyLocked() {
2938 while (mPolicy == null || !mDoneBooting) {
2939 try {
2940 mLocks.wait();
2941 } catch (InterruptedException e) {
2942 // Ignore
2943 }
2944 }
2945 return mPolicy;
2946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002949 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2950 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2951 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002952 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002953 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002954 }
2955
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002956 // wait until sensors are enabled before turning on screen.
2957 // some devices will not activate the light sensor properly on boot
2958 // unless we do this.
2959 if (mUseSoftwareAutoBrightness) {
2960 // turn the screen on
2961 setPowerState(SCREEN_BRIGHT);
2962 } else {
2963 // turn everything on
2964 setPowerState(ALL_BRIGHT);
2965 }
2966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002970
Joe Onoratod28f7532010-11-06 12:56:53 -07002971 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2972
Dianne Hackborn617f8772009-03-31 15:04:46 -07002973 long identity = Binder.clearCallingIdentity();
2974 try {
2975 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2976 mBatteryStats.noteScreenOn();
2977 } catch (RemoteException e) {
2978 // Nothing interesting to do.
2979 } finally {
2980 Binder.restoreCallingIdentity(identity);
2981 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002982 }
2983 }
2984
2985 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002987 synchronized (mLocks) {
2988 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2990 updateWakeLockLocked();
2991 mLocks.notifyAll();
2992 }
2993 }
2994
Joe Onoratob08a1af2010-10-11 19:28:58 -07002995 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 public void monitor() {
2997 synchronized (mLocks) { }
2998 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002999
3000 public int getSupportedWakeLockFlags() {
3001 int result = PowerManager.PARTIAL_WAKE_LOCK
3002 | PowerManager.FULL_WAKE_LOCK
3003 | PowerManager.SCREEN_DIM_WAKE_LOCK;
3004
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003005 if (mProximitySensor != null) {
3006 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
3007 }
3008
3009 return result;
3010 }
3011
Mike Lockwood237a2992009-09-15 14:42:16 -04003012 public void setBacklightBrightness(int brightness) {
3013 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3014 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07003015 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04003016 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07003017 mLcdLight.setBrightness(brightness);
3018 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
3019 mButtonLight.setBrightness(brightness);
3020 long identity = Binder.clearCallingIdentity();
3021 try {
3022 mBatteryStats.noteScreenBrightness(brightness);
3023 } catch (RemoteException e) {
3024 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
3025 } finally {
3026 Binder.restoreCallingIdentity(identity);
3027 }
Jim Miller92e66dd2012-02-21 18:57:12 -08003028 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003029 }
3030 }
3031
3032 public void setAutoBrightnessAdjustment(float adj) {
3033 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3034 synchronized (mLocks) {
3035 mLightSensorAdjustSetting = adj;
3036 if (mSensorManager != null && mLightSensorEnabled) {
3037 // clear calling identity so sensor manager battery stats are accurate
3038 long identity = Binder.clearCallingIdentity();
3039 try {
3040 // force recompute of backlight values
3041 if (mLightSensorValue >= 0) {
3042 int value = (int)mLightSensorValue;
3043 mLightSensorValue = -1;
3044 handleLightSensorValue(value, true);
3045 }
3046 } finally {
3047 Binder.restoreCallingIdentity(identity);
3048 }
Joe Onorato3d3db602010-10-18 16:08:16 -04003049 }
Mike Lockwood237a2992009-09-15 14:42:16 -04003050 }
3051 }
3052
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003053 public void setAttentionLight(boolean on, int color) {
3054 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05003055 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003056 }
3057
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003058 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003059 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003060 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003061 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003062 if (!mProximitySensorEnabled) {
3063 // clear calling identity so sensor manager battery stats are accurate
3064 long identity = Binder.clearCallingIdentity();
3065 try {
3066 mSensorManager.registerListener(mProximityListener, mProximitySensor,
3067 SensorManager.SENSOR_DELAY_NORMAL);
3068 mProximitySensorEnabled = true;
3069 } finally {
3070 Binder.restoreCallingIdentity(identity);
3071 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003072 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003073 }
3074
3075 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003076 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003077 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003078 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003079 if (mProximitySensorEnabled) {
3080 // clear calling identity so sensor manager battery stats are accurate
3081 long identity = Binder.clearCallingIdentity();
3082 try {
3083 mSensorManager.unregisterListener(mProximityListener);
3084 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003085 if (mProximityPartialLock.isHeld()) {
3086 mProximityPartialLock.release();
3087 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003088 mProximitySensorEnabled = false;
3089 } finally {
3090 Binder.restoreCallingIdentity(identity);
3091 }
3092 if (mProximitySensorActive) {
3093 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003094 if (mDebugProximitySensor) {
3095 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
3096 + mProxIgnoredBecauseScreenTurnedOff);
3097 }
3098 if (!mProxIgnoredBecauseScreenTurnedOff) {
3099 forceUserActivityLocked();
3100 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003101 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003102 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003103 }
3104
Mike Lockwood20f87d72009-11-05 16:08:51 -05003105 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003106 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003107 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003108 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003109 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003110 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003111 return;
3112 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003113 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003114 if (mDebugProximitySensor) {
3115 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3116 + mProxIgnoredBecauseScreenTurnedOff);
3117 }
3118 if (!mProxIgnoredBecauseScreenTurnedOff) {
3119 goToSleepLocked(SystemClock.uptimeMillis(),
3120 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3121 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003122 mProximitySensorActive = true;
3123 } else {
3124 // proximity sensor negative events trigger as user activity.
3125 // temporarily set mUserActivityAllowed to true so this will work
3126 // even when the keyguard is on.
3127 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003128 if (mDebugProximitySensor) {
3129 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3130 + mProxIgnoredBecauseScreenTurnedOff);
3131 }
3132 if (!mProxIgnoredBecauseScreenTurnedOff) {
3133 forceUserActivityLocked();
3134 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003135
3136 if (mProximityWakeLockCount == 0) {
3137 // disable sensor if we have no listeners left after proximity negative
3138 disableProximityLockLocked();
3139 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003140 }
3141 }
3142
Joe Onoratod28f7532010-11-06 12:56:53 -07003143 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003144 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003145 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3146 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3147 }
3148 if (!mAutoBrightessEnabled) {
3149 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003150 }
3151 if (mSensorManager != null && mLightSensorEnabled != enable) {
3152 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003153 // clear calling identity so sensor manager battery stats are accurate
3154 long identity = Binder.clearCallingIdentity();
3155 try {
3156 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003157 // reset our highest value when reenabling
3158 mHighestLightSensorValue = -1;
3159 // force recompute of backlight values
3160 if (mLightSensorValue >= 0) {
3161 int value = (int)mLightSensorValue;
3162 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003163 handleLightSensorValue(value, true);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003164 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003165 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003166 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003167 } else {
3168 mSensorManager.unregisterListener(mLightListener);
3169 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003170 mLightSensorPendingDecrease = false;
3171 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003175 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003176 }
3177 }
3178
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003179 SensorEventListener mProximityListener = new SensorEventListener() {
3180 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003181 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003182 synchronized (mLocks) {
3183 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003184 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3185 mLastProximityEventTime = milliseconds;
3186 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003187 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003188
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003189 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003190 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3191 distance < mProximitySensor.getMaximumRange());
3192
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003193 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003194 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003195 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003196 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3197 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3198 mProximityPendingValue = (active ? 1 : 0);
3199 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003200 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003201 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003202 // process the value immediately
3203 mProximityPendingValue = -1;
3204 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003205 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003206
3207 // update mProximityPartialLock state
3208 boolean held = mProximityPartialLock.isHeld();
3209 if (!held && proximityTaskQueued) {
3210 // hold wakelock until mProximityTask runs
3211 mProximityPartialLock.acquire();
3212 } else if (held && !proximityTaskQueued) {
3213 mProximityPartialLock.release();
3214 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003215 }
3216 }
3217
3218 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3219 // ignore
3220 }
3221 };
3222
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003223 private void handleLightSensorValue(int value, boolean immediate) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003224 long milliseconds = SystemClock.elapsedRealtime();
3225 if (mLightSensorValue == -1 ||
3226 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3227 // process the value immediately if screen has just turned on
3228 mHandler.removeCallbacks(mAutoBrightnessTask);
3229 mLightSensorPendingDecrease = false;
3230 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003231 lightSensorChangedLocked(value, immediate);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003232 } else {
3233 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3234 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3235 (value == mLightSensorValue) ||
3236 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3237 // delay processing to debounce the sensor
3238 mHandler.removeCallbacks(mAutoBrightnessTask);
3239 mLightSensorPendingDecrease = (value < mLightSensorValue);
3240 mLightSensorPendingIncrease = (value > mLightSensorValue);
3241 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3242 mLightSensorPendingValue = value;
3243 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3244 }
3245 } else {
3246 mLightSensorPendingValue = value;
3247 }
3248 }
3249 }
3250
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003251 SensorEventListener mLightListener = new SensorEventListener() {
3252 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003253 if (mDebugLightSensor) {
3254 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3255 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003256 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003257 // ignore light sensor while screen is turning off
3258 if (isScreenTurningOffLocked()) {
3259 return;
3260 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003261 handleLightSensorValue((int)event.values[0], false);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003262 }
3263 }
3264
3265 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3266 // ignore
3267 }
3268 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269}