blob: 2cc270432b8750a77df7a8fabf826481e53da4bb [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;
20import com.android.server.am.BatteryStatsService;
Jeff Brown7304c342012-05-11 18:42:42 -070021import com.android.server.pm.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Jeff Brown25157e42012-04-16 12:13:05 -070040import android.hardware.SystemSensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070041import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.BatteryStats;
43import android.os.Binder;
44import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.IPowerManager;
48import android.os.LocalPowerManager;
Jim Miller92e66dd2012-02-21 18:57:12 -080049import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.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;
Jeff Brown7304c342012-05-11 18:42:42 -070073import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.io.PrintWriter;
75import java.util.ArrayList;
76import java.util.HashMap;
77import java.util.Observable;
78import java.util.Observer;
79
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080080public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040081 implements LocalPowerManager, Watchdog.Monitor {
Jim Miller92e66dd2012-02-21 18:57:12 -080082 private static final int NOMINAL_FRAME_TIME_MS = 1000/60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84 private static final String TAG = "PowerManagerService";
85 static final String PARTIAL_NAME = "PowerManagerService";
86
Jeff Brown7304c342012-05-11 18:42:42 -070087 // Wake lock that ensures that the CPU is running. The screen might not be on.
88 private static final int PARTIAL_WAKE_LOCK_ID = 1;
89
90 // Wake lock that ensures that the screen is on.
91 private static final int FULL_WAKE_LOCK_ID = 2;
92
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -070093 static final boolean DEBUG_SCREEN_ON = false;
94
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 private static final boolean LOG_PARTIAL_WL = false;
96
97 // Indicates whether touch-down cycles should be logged as part of the
98 // LOG_POWER_SCREEN_STATE log events
99 private static final boolean LOG_TOUCH_DOWNS = true;
100
101 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
102 | PowerManager.SCREEN_DIM_WAKE_LOCK
103 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700104 | PowerManager.FULL_WAKE_LOCK
105 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
107 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -0800108 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
110 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
111 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
112 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
113
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800114 // How long to wait to debounce light sensor changes in milliseconds
Mike Lockwood9b8136922009-11-06 15:53:59 -0500115 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700116
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800117 // light sensor events rate in microseconds
118 private static final int LIGHT_SENSOR_RATE = 1000000;
119
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800120 // Expansion of range of light values when applying scale from light
121 // sensor brightness setting, in the [0..255] brightness range.
122 private static final int LIGHT_SENSOR_RANGE_EXPANSION = 20;
123
124 // Scaling factor of the light sensor brightness setting when applying
125 // it to the final brightness.
126 private static final int LIGHT_SENSOR_OFFSET_SCALE = 8;
127
Mathias Agopian47f1fe52011-11-08 17:18:41 -0800128 // For debouncing the proximity sensor in milliseconds
Mike Lockwood20f87d72009-11-05 16:08:51 -0500129 private static final int PROXIMITY_SENSOR_DELAY = 1000;
130
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400131 // trigger proximity if distance is less than 5 cm
132 private static final float PROXIMITY_THRESHOLD = 5.0f;
133
Doug Zongker43866e02010-01-07 12:09:54 -0800134 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
136
Amith Yamasani8b619832010-09-22 16:11:59 -0700137 // Default timeout for screen off, if not found in settings database = 15 seconds.
138 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
139
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800140 // Screen brightness should always have a value, but just in case...
141 private static final int DEFAULT_SCREEN_BRIGHTNESS = 192;
142
Jeff Brown7304c342012-05-11 18:42:42 -0700143 // Threshold for BRIGHTNESS_LOW_BATTERY (percentage)
144 // Screen will stay dim if battery level is <= LOW_BATTERY_THRESHOLD
145 private static final int LOW_BATTERY_THRESHOLD = 10;
146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 // flags for setPowerState
Jim Miller92e66dd2012-02-21 18:57:12 -0800148 private static final int ALL_LIGHTS_OFF = 0x00000000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 private static final int SCREEN_ON_BIT = 0x00000001;
150 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
151 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
152 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
153 private static final int BATTERY_LOW_BIT = 0x00000010;
154
155 // values for setPowerState
156
157 // SCREEN_OFF == everything off
158 private static final int SCREEN_OFF = 0x00000000;
159
160 // SCREEN_DIM == screen on, screen backlight dim
161 private static final int SCREEN_DIM = SCREEN_ON_BIT;
162
163 // SCREEN_BRIGHT == screen on, screen backlight bright
164 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
165
166 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
167 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
168
169 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
170 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
171
172 // used for noChangeLights in setPowerState()
173 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
174
Jim Miller46f31c32012-03-01 14:36:07 -0800175 // animate screen lights in PowerManager (as opposed to SurfaceFlinger)
Joe Onoratob08a1af2010-10-11 19:28:58 -0700176 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800177
Jim Miller92e66dd2012-02-21 18:57:12 -0800178 static final int ANIM_STEPS = 60; // nominal # of frames at 60Hz
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400179 // Slower animation for autobrightness changes
Jim Miller92e66dd2012-02-21 18:57:12 -0800180 static final int AUTOBRIGHTNESS_ANIM_STEPS = 2 * ANIM_STEPS;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800181 // Number of steps when performing a more immediate brightness change.
182 static final int IMMEDIATE_ANIM_STEPS = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
184 // These magic numbers are the initial state of the LEDs at boot. Ideally
185 // we should read them from the driver, but our current hardware returns 0
186 // for the initial value. Oops!
187 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
Jeff Brown7304c342012-05-11 18:42:42 -0700188 static final int INITIAL_BUTTON_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF;
189 static final int INITIAL_KEYBOARD_BRIGHTNESS = PowerManager.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700192 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500195 private boolean mBootCompleted = false;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700196 private boolean mHeadless = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500198 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
199 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700200 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700201 private boolean mSkippedScreenOn = false;
202 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private int mPartialCount = 0;
204 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500205 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
206 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
207 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private int mUserState;
209 private boolean mKeyboardVisible = false;
210 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500211 private int mProximityWakeLockCount = 0;
212 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700213 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500214 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
215 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800216 private int mScreenOffTimeoutSetting;
217 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 private int mKeylightDelay;
219 private int mDimDelay;
220 private int mScreenOffDelay;
221 private int mWakeLockState;
222 private long mLastEventTime = 0;
223 private long mScreenOffTime;
224 private volatile WindowManagerPolicy mPolicy;
225 private final LockList mLocks = new LockList();
226 private Intent mScreenOffIntent;
227 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500228 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500230 private LightsService.Light mLcdLight;
231 private LightsService.Light mButtonLight;
232 private LightsService.Light mKeyboardLight;
233 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private UnsynchronizedWakeLock mBroadcastWakeLock;
235 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
236 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
237 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500238 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700240 private Handler mScreenOffHandler;
Jim Miller92e66dd2012-02-21 18:57:12 -0800241 private Handler mScreenBrightnessHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500243 private final TimeoutTask mTimeoutTask = new TimeoutTask();
Jim Miller92e66dd2012-02-21 18:57:12 -0800244 private ScreenBrightnessAnimator mScreenBrightnessAnimator;
Joe Onorato128e7292009-03-24 18:41:31 -0700245 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 private boolean mIsPowered = false;
247 private IActivityManager mActivityService;
248 private IBatteryStats mBatteryStats;
249 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700250 private SensorManager mSensorManager;
251 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400252 private Sensor mLightSensor;
253 private boolean mLightSensorEnabled;
254 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400255 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500256 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500257 private boolean mLightSensorPendingDecrease = false;
258 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700259 private float mLightSensorPendingValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800260 private float mLightSensorAdjustSetting = 0;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500261 private int mLightSensorScreenBrightness = -1;
262 private int mLightSensorButtonBrightness = -1;
263 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500265 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 private long mNextTimeout;
267 private volatile int mPokey = 0;
268 private volatile boolean mPokeAwakeOnSet = false;
269 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500270 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500271 // mLastScreenOnTime is the time the screen was last turned on
272 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 private boolean mPreventScreenOn;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800274 private int mScreenBrightnessSetting = DEFAULT_SCREEN_BRIGHTNESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500276 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400277 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400278 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700279 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700280 private int[] mAutoBrightnessLevels;
281 private int[] mLcdBacklightValues;
282 private int[] mButtonBacklightValues;
283 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500284 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700285 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700286 private int mWarningSpewThrottleCount;
287 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700288 private int mAnimationSetting = ANIM_SETTING_OFF;
Jim Miller92e66dd2012-02-21 18:57:12 -0800289 private float mWindowScaleAnimation;
Joe Onorato609695d2010-10-14 14:57:49 -0700290
291 // Must match with the ISurfaceComposer constants in C++.
292 private static final int ANIM_SETTING_ON = 0x01;
293 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
295 // Used when logging number and duration of touch-down cycles
296 private long mTotalTouchDownTime;
297 private long mLastTouchDown;
298 private int mTouchCycles;
299
300 // could be either static or controllable at runtime
301 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400302 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwoodae92eb32011-10-25 10:11:46 -0400303 private static final boolean mDebugLightSensor = (false || mSpew);
Jim Miller92e66dd2012-02-21 18:57:12 -0800304 private static final boolean mDebugLightAnimation = (false || mSpew);
305
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700306 private native void nativeInit();
307 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700308 private native void nativeStartSurfaceFlingerAnimation(int mode);
Jeff Brown7304c342012-05-11 18:42:42 -0700309 private static native void nativeAcquireWakeLock(int lock, String id);
310 private static native void nativeReleaseWakeLock(String id);
311 private static native int nativeSetScreenState(boolean on);
312 private static native void nativeShutdown();
313 private static native void nativeReboot(String reason) throws IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314
315 /*
316 static PrintStream mLog;
317 static {
318 try {
319 mLog = new PrintStream("/data/power.log");
320 }
321 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800322 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324 }
325 static class Log {
326 static void d(String tag, String s) {
327 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800328 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330 static void i(String tag, String s) {
331 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800332 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 }
334 static void w(String tag, String s) {
335 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800336 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338 static void e(String tag, String s) {
339 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800340 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 }
342 }
343 */
344
345 /**
346 * This class works around a deadlock between the lock in PowerManager.WakeLock
347 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
348 * mToken object so it can be accessed from any thread, but it calls into here
349 * with its lock held. This class is essentially a reimplementation of
350 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
351 * only call it with our own locks held.
352 */
353 private class UnsynchronizedWakeLock {
354 int mFlags;
355 String mTag;
356 IBinder mToken;
357 int mCount = 0;
358 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500359 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360
361 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
362 mFlags = flags;
363 mTag = tag;
364 mToken = new Binder();
365 mRefCounted = refCounted;
366 }
367
368 public void acquire() {
369 if (!mRefCounted || mCount++ == 0) {
370 long ident = Binder.clearCallingIdentity();
371 try {
372 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700373 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500374 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 } finally {
376 Binder.restoreCallingIdentity(ident);
377 }
378 }
379 }
380
381 public void release() {
382 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500383 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500384 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386 if (mCount < 0) {
387 throw new RuntimeException("WakeLock under-locked " + mTag);
388 }
389 }
390
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500391 public boolean isHeld()
392 {
393 return mHeld;
394 }
395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 public String toString() {
397 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500398 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 }
400 }
401
402 private final class BatteryReceiver extends BroadcastReceiver {
403 @Override
404 public void onReceive(Context context, Intent intent) {
405 synchronized (mLocks) {
406 boolean wasPowered = mIsPowered;
407 mIsPowered = mBatteryService.isPowered();
408
409 if (mIsPowered != wasPowered) {
410 // update mStayOnWhilePluggedIn wake lock
411 updateWakeLockLocked();
412
413 // treat plugging and unplugging the devices as a user activity.
414 // users find it disconcerting when they unplug the device
415 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500416 // to avoid turning on the screen when unplugging, we only trigger
417 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 // temporarily set mUserActivityAllowed to true so this will work
419 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700420 // However, you can also set config_unplugTurnsOnScreen to have it
421 // turn on. Some devices want this because they don't have a
422 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700424 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
425 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500426 forceUserActivityLocked();
427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
429 }
430 }
431 }
432 }
433
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500434 private final class BootCompletedReceiver extends BroadcastReceiver {
435 @Override
436 public void onReceive(Context context, Intent intent) {
437 bootCompleted();
438 }
439 }
440
Mike Lockwoodb2865412010-02-02 22:40:33 -0500441 private final class DockReceiver extends BroadcastReceiver {
442 @Override
443 public void onReceive(Context context, Intent intent) {
444 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
445 Intent.EXTRA_DOCK_STATE_UNDOCKED);
446 dockStateChanged(state);
447 }
448 }
449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 /**
451 * Set the setting that determines whether the device stays on when plugged in.
452 * The argument is a bit string, with each bit specifying a power source that,
453 * when the device is connected to that source, causes the device to stay on.
454 * See {@link android.os.BatteryManager} for the list of power sources that
455 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
456 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
457 * @param val an {@code int} containing the bits that specify which power sources
458 * should cause the device to stay on.
459 */
460 public void setStayOnSetting(int val) {
461 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
462 Settings.System.putInt(mContext.getContentResolver(),
463 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
464 }
465
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800466 public void setMaximumScreenOffTimeount(int timeMs) {
467 mContext.enforceCallingOrSelfPermission(
468 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
469 synchronized (mLocks) {
470 mMaximumScreenOffTimeout = timeMs;
471 // recalculate everything
472 setScreenOffTimeoutsLocked();
473 }
474 }
475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700477 private int getInt(String name, int defValue) {
478 ContentValues values = mSettings.getValues(name);
479 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
480 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 }
482
Joe Onorato609695d2010-10-14 14:57:49 -0700483 private float getFloat(String name, float defValue) {
484 ContentValues values = mSettings.getValues(name);
485 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
486 return fVal != null ? fVal : defValue;
487 }
488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 public void update(Observable o, Object arg) {
490 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700491 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
492 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
493 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 updateWakeLockLocked();
495
Amith Yamasani8b619832010-09-22 16:11:59 -0700496 // SCREEN_OFF_TIMEOUT, default to 15 seconds
497 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498
Joe Onorato609695d2010-10-14 14:57:49 -0700499 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 //mDimScreen = getInt(DIM_SCREEN) != 0;
501
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800502 mScreenBrightnessSetting = getInt(SCREEN_BRIGHTNESS, DEFAULT_SCREEN_BRIGHTNESS);
Dianne Hackborn518a3d82012-05-09 16:30:49 -0700503 mLightSensorAdjustSetting = 0; //getFloat(SCREEN_AUTO_BRIGHTNESS_ADJ, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800504
Amith Yamasani8b619832010-09-22 16:11:59 -0700505 // SCREEN_BRIGHTNESS_MODE, default to manual
506 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
507 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 // recalculate everything
510 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700511
Jim Miller92e66dd2012-02-21 18:57:12 -0800512 mWindowScaleAnimation = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
Joe Onorato609695d2010-10-14 14:57:49 -0700513 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
514 mAnimationSetting = 0;
Jim Miller92e66dd2012-02-21 18:57:12 -0800515 if (mWindowScaleAnimation > 0.5f) {
Joe Onorato609695d2010-10-14 14:57:49 -0700516 mAnimationSetting |= ANIM_SETTING_OFF;
517 }
518 if (transitionScale > 0.5f) {
519 // Uncomment this if you want the screen-on animation.
520 // mAnimationSetting |= ANIM_SETTING_ON;
521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523 }
524 }
525
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700526 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 // Hack to get our uid... should have a func for this.
528 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700529 MY_UID = Process.myUid();
530 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 Binder.restoreCallingIdentity(token);
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 // assume nothing is on yet
534 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 // Add ourself to the Watchdog monitors.
537 Watchdog.getInstance().addMonitor(this);
Jeff Brown7304c342012-05-11 18:42:42 -0700538
539 nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541
542 private ContentQueryMap mSettings;
543
Mike Lockwood3a322132009-11-24 00:30:52 -0500544 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700545 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500546 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 mContext = context;
548 mActivityService = activity;
549 mBatteryStats = BatteryStatsService.getService();
550 mBatteryService = battery;
551
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500552 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
553 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
554 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
555 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700556 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500557
Joe Onoratob08a1af2010-10-11 19:28:58 -0700558 mInitComplete = false;
Jim Miller92e66dd2012-02-21 18:57:12 -0800559 mScreenBrightnessAnimator = new ScreenBrightnessAnimator("mScreenBrightnessUpdaterThread",
560 Process.THREAD_PRIORITY_DISPLAY);
561 mScreenBrightnessAnimator.start();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700562
Jim Miller92e66dd2012-02-21 18:57:12 -0800563 synchronized (mScreenBrightnessAnimator) {
Joe Onoratob08a1af2010-10-11 19:28:58 -0700564 while (!mInitComplete) {
565 try {
Jim Miller92e66dd2012-02-21 18:57:12 -0800566 mScreenBrightnessAnimator.wait();
Joe Onoratob08a1af2010-10-11 19:28:58 -0700567 } catch (InterruptedException e) {
568 // Ignore
569 }
570 }
571 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800572
Joe Onoratob08a1af2010-10-11 19:28:58 -0700573 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 mHandlerThread = new HandlerThread("PowerManagerService") {
575 @Override
576 protected void onLooperPrepared() {
577 super.onLooperPrepared();
578 initInThread();
579 }
580 };
581 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 synchronized (mHandlerThread) {
584 while (!mInitComplete) {
585 try {
586 mHandlerThread.wait();
587 } catch (InterruptedException e) {
588 // Ignore
589 }
590 }
591 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800592
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700593 synchronized (mLocks) {
594 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700595 // We make sure to start out with the screen on due to user activity.
596 // (They did just boot their device, after all.)
597 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700598 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 void initInThread() {
603 mHandler = new Handler();
604
605 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700606 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
608 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
609 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
610 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
611 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
612 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500613 mProximityPartialLock = new UnsynchronizedWakeLock(
614 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615
616 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
617 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
618 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
619 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
620
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700621 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400622
Joe Onoratob08a1af2010-10-11 19:28:58 -0700623 mAnimateScreenLights = resources.getBoolean(
624 com.android.internal.R.bool.config_animateScreenLights);
625
Joe Onorato6d747652010-10-11 15:15:31 -0700626 mUnplugTurnsOnScreen = resources.getBoolean(
627 com.android.internal.R.bool.config_unplugTurnsOnScreen);
628
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400629 mScreenBrightnessDim = resources.getInteger(
630 com.android.internal.R.integer.config_screenBrightnessDim);
631
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400632 // read settings for auto-brightness
633 mUseSoftwareAutoBrightness = resources.getBoolean(
634 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400635 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700636 mAutoBrightnessLevels = resources.getIntArray(
637 com.android.internal.R.array.config_autoBrightnessLevels);
638 mLcdBacklightValues = resources.getIntArray(
639 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
640 mButtonBacklightValues = resources.getIntArray(
641 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
642 mKeyboardBacklightValues = resources.getIntArray(
643 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500644 mLightSensorWarmupTime = resources.getInteger(
645 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700646 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700647
648 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
650 "(" + Settings.System.NAME + "=?) or ("
651 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700652 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700653 + Settings.System.NAME + "=?) or ("
654 + Settings.System.NAME + "=?) or ("
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800655 + Settings.System.NAME + "=?) or ("
656 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 + Settings.System.NAME + "=?)",
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800658 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN, SCREEN_BRIGHTNESS,
Dianne Hackborn518a3d82012-05-09 16:30:49 -0700659 SCREEN_BRIGHTNESS_MODE, /*SCREEN_AUTO_BRIGHTNESS_ADJ,*/
Dianne Hackbornd9ea4682012-01-20 18:36:40 -0800660 WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 null);
662 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
663 SettingsObserver settingsObserver = new SettingsObserver();
664 mSettings.addObserver(settingsObserver);
665
666 // pretend that the settings changed so we will get their initial state
667 settingsObserver.update(mSettings, null);
668
669 // register for the battery changed notifications
670 IntentFilter filter = new IntentFilter();
671 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
672 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500673 filter = new IntentFilter();
674 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
675 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500676 filter = new IntentFilter();
677 filter.addAction(Intent.ACTION_DOCK_EVENT);
678 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
Doug Zongker43866e02010-01-07 12:09:54 -0800680 // Listen for secure settings changes
681 mContext.getContentResolver().registerContentObserver(
682 Settings.Secure.CONTENT_URI, true,
683 new ContentObserver(new Handler()) {
684 public void onChange(boolean selfChange) {
685 updateSettingsValues();
686 }
687 });
688 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 synchronized (mHandlerThread) {
691 mInitComplete = true;
692 mHandlerThread.notifyAll();
693 }
694 }
695
Jeff Brown7304c342012-05-11 18:42:42 -0700696 /**
697 * Low-level function turn the device off immediately, without trying
698 * to be clean. Most people should use
699 * {@link com.android.server.pm.internal.app.ShutdownThread} for a clean shutdown.
700 */
701 public static void lowLevelShutdown() {
702 nativeShutdown();
703 }
704
705 /**
706 * Low-level function to reboot the device.
707 *
708 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
709 * @throws IOException if reboot fails for some reason (eg, lack of
710 * permission)
711 */
712 public static void lowLevelReboot(String reason) throws IOException {
713 nativeReboot(reason);
714 }
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 private class WakeLock implements IBinder.DeathRecipient
717 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700718 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 super();
720 flags = f;
721 binder = b;
722 tag = t;
723 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700724 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (u != MY_UID || (
726 !"KEEP_SCREEN_ON_FLAG".equals(tag)
727 && !"KeyInputQueue".equals(tag))) {
728 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
729 ? BatteryStats.WAKE_TYPE_PARTIAL
730 : BatteryStats.WAKE_TYPE_FULL;
731 } else {
732 monitorType = -1;
733 }
734 try {
735 b.linkToDeath(this, 0);
736 } catch (RemoteException e) {
737 binderDied();
738 }
739 }
740 public void binderDied() {
741 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500742 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744 }
745 final int flags;
746 final IBinder binder;
747 final String tag;
748 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400749 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700751 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 boolean activated = true;
753 int minState;
754 }
755
756 private void updateWakeLockLocked() {
757 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
758 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
759 mStayOnWhilePluggedInScreenDimLock.acquire();
760 mStayOnWhilePluggedInPartialLock.acquire();
761 } else {
762 mStayOnWhilePluggedInScreenDimLock.release();
763 mStayOnWhilePluggedInPartialLock.release();
764 }
765 }
766
767 private boolean isScreenLock(int flags)
768 {
769 int n = flags & LOCK_MASK;
770 return n == PowerManager.FULL_WAKE_LOCK
771 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400772 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
773 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 }
775
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700776 void enforceWakeSourcePermission(int uid, int pid) {
777 if (uid == Process.myUid()) {
778 return;
779 }
780 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
781 pid, uid, null);
782 }
783
784 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700786 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700787 if (uid != Process.myUid()) {
788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
789 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 if (ws != null) {
791 enforceWakeSourcePermission(uid, pid);
792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 long ident = Binder.clearCallingIdentity();
794 try {
795 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700796 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 }
798 } finally {
799 Binder.restoreCallingIdentity(ident);
800 }
801 }
802
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700803 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700804 if (wl.monitorType >= 0) {
805 long origId = Binder.clearCallingIdentity();
806 try {
807 if (ws != null) {
808 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
809 wl.monitorType);
810 } else {
811 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
812 }
813 } catch (RemoteException e) {
814 // Ignore
815 } finally {
816 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700817 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700818 }
819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700821 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700822 if (wl.monitorType >= 0) {
823 long origId = Binder.clearCallingIdentity();
824 try {
825 if (ws != null) {
826 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
827 wl.monitorType);
828 } else {
829 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
830 }
831 } catch (RemoteException e) {
832 // Ignore
833 } finally {
834 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700835 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700836 }
837 }
838
839 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
840 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800842 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700845 if (ws != null && ws.size() == 0) {
846 ws = null;
847 }
848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 int index = mLocks.getIndex(lock);
850 WakeLock wl;
851 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700852 boolean diffsource;
853 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700855 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 switch (wl.flags & LOCK_MASK)
857 {
858 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500859 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400860 wl.minState = SCREEN_BRIGHT;
861 } else {
862 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 break;
865 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
866 wl.minState = SCREEN_BRIGHT;
867 break;
868 case PowerManager.SCREEN_DIM_WAKE_LOCK:
869 wl.minState = SCREEN_DIM;
870 break;
871 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700872 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 break;
874 default:
875 // just log and bail. we're in the server, so don't
876 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 + " flags=" + flags);
879 return;
880 }
881 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700882 if (ws != null) {
883 wl.ws = new WorkSource(ws);
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700886 diffsource = false;
887 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } else {
889 wl = mLocks.get(index);
890 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700891 oldsource = wl.ws;
892 if (oldsource != null) {
893 if (ws == null) {
894 wl.ws = null;
895 diffsource = true;
896 } else {
897 diffsource = oldsource.diff(ws);
898 }
899 } else if (ws != null) {
900 diffsource = true;
901 } else {
902 diffsource = false;
903 }
904 if (diffsource) {
905 wl.ws = new WorkSource(ws);
906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908 if (isScreenLock(flags)) {
909 // if this causes a wakeup, we reactivate all of the locks and
910 // set it to whatever they want. otherwise, we modulate that
911 // by the current state so we never turn it more on than
912 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400913 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
914 mProximityWakeLockCount++;
915 if (mProximityWakeLockCount == 1) {
916 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400919 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
920 int oldWakeLockState = mWakeLockState;
921 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400922
923 // Disable proximity sensor if if user presses power key while we are in the
924 // "waiting for proximity sensor to go negative" state.
925 if ((mWakeLockState & SCREEN_ON_BIT) != 0
926 && mProximitySensorActive && mProximityWakeLockCount == 0) {
927 mProximitySensorActive = false;
928 }
929
Joe Onorato8274a0e2010-10-05 17:38:09 -0400930 if (mSpew) {
931 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
932 + " mWakeLockState=0x"
933 + Integer.toHexString(mWakeLockState)
934 + " previous wakeLockState=0x"
935 + Integer.toHexString(oldWakeLockState));
936 }
937 } else {
938 if (mSpew) {
939 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
940 + " mLocks.gatherState()=0x"
941 + Integer.toHexString(mLocks.gatherState())
942 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
943 }
944 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400946 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
950 if (newlock) {
951 mPartialCount++;
952 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800953 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955 }
Jeff Brown7304c342012-05-11 18:42:42 -0700956 nativeAcquireWakeLock(PARTIAL_WAKE_LOCK_ID, PARTIAL_NAME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700959 if (diffsource) {
960 // If the lock sources have changed, need to first release the
961 // old ones.
962 noteStopWakeLocked(wl, oldsource);
963 }
964 if (newlock || diffsource) {
965 noteStartWakeLocked(wl, ws);
966 }
967 }
968
969 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
970 int uid = Binder.getCallingUid();
971 int pid = Binder.getCallingPid();
972 if (ws != null && ws.size() == 0) {
973 ws = null;
974 }
975 if (ws != null) {
976 enforceWakeSourcePermission(uid, pid);
977 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700978 synchronized (mLocks) {
979 int index = mLocks.getIndex(lock);
980 if (index < 0) {
981 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700983 WakeLock wl = mLocks.get(index);
984 WorkSource oldsource = wl.ws;
985 wl.ws = ws != null ? new WorkSource(ws) : null;
986 noteStopWakeLocked(wl, oldsource);
987 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
989 }
990
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500991 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700992 int uid = Binder.getCallingUid();
993 if (uid != Process.myUid()) {
994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
997 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500998 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000 }
1001
Mike Lockwood0e39ea82009-11-18 15:37:10 -05001002 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 WakeLock wl = mLocks.removeLock(lock);
1004 if (wl == null) {
1005 return;
1006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001009 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
1011 }
1012
1013 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04001014 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
1015 mProximityWakeLockCount--;
1016 if (mProximityWakeLockCount == 0) {
1017 if (mProximitySensorActive &&
1018 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
1019 // wait for proximity sensor to go negative before disabling sensor
1020 if (mDebugProximitySensor) {
1021 Slog.d(TAG, "waiting for proximity sensor to go negative");
1022 }
1023 } else {
1024 disableProximityLockLocked();
1025 }
1026 }
1027 } else {
1028 mWakeLockState = mLocks.gatherState();
1029 // goes in the middle to reduce flicker
1030 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
1031 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
1032 }
1033 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
1036 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
1037 mPartialCount--;
1038 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001039 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
Jeff Brown7304c342012-05-11 18:42:42 -07001040 nativeReleaseWakeLock(PARTIAL_NAME);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042 }
1043 // Unlink the lock from the binder.
1044 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045
Dianne Hackborn70be1672010-09-14 11:13:03 -07001046 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 private class PokeLock implements IBinder.DeathRecipient
1050 {
1051 PokeLock(int p, IBinder b, String t) {
1052 super();
1053 this.pokey = p;
1054 this.binder = b;
1055 this.tag = t;
1056 try {
1057 b.linkToDeath(this, 0);
1058 } catch (RemoteException e) {
1059 binderDied();
1060 }
1061 }
1062 public void binderDied() {
1063 setPokeLock(0, this.binder, this.tag);
1064 }
1065 int pokey;
1066 IBinder binder;
1067 String tag;
1068 boolean awakeOnSet;
1069 }
1070
1071 public void setPokeLock(int pokey, IBinder token, String tag) {
1072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1073 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001074 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 return;
1076 }
1077
1078 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1079 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1080 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1081 }
1082
1083 synchronized (mLocks) {
1084 if (pokey != 0) {
1085 PokeLock p = mPokeLocks.get(token);
1086 int oldPokey = 0;
1087 if (p != null) {
1088 oldPokey = p.pokey;
1089 p.pokey = pokey;
1090 } else {
1091 p = new PokeLock(pokey, token, tag);
1092 mPokeLocks.put(token, p);
1093 }
1094 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1095 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1096 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1097 p.awakeOnSet = true;
1098 }
1099 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001100 PokeLock rLock = mPokeLocks.remove(token);
1101 if (rLock != null) {
1102 token.unlinkToDeath(rLock, 0);
1103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105
1106 int oldPokey = mPokey;
1107 int cumulative = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 boolean awakeOnSet = false;
1109 for (PokeLock p: mPokeLocks.values()) {
1110 cumulative |= p.pokey;
1111 if (p.awakeOnSet) {
1112 awakeOnSet = true;
1113 }
1114 }
1115 mPokey = cumulative;
1116 mPokeAwakeOnSet = awakeOnSet;
1117
1118 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1119 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (oldCumulativeTimeout != newCumulativeTimeout) {
1122 setScreenOffTimeoutsLocked();
1123 // reset the countdown timer, but use the existing nextState so it doesn't
1124 // change anything
1125 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1126 }
1127 }
1128 }
1129
1130 private static String lockType(int type)
1131 {
1132 switch (type)
1133 {
1134 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001135 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001137 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001139 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001141 return "PARTIAL_WAKE_LOCK ";
1142 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1143 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 default:
David Brown251faa62009-08-02 22:04:36 -07001145 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 }
1148
1149 private static String dumpPowerState(int state) {
1150 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1151 ? "KEYBOARD_BRIGHT_BIT " : "")
1152 + (((state & SCREEN_BRIGHT_BIT) != 0)
1153 ? "SCREEN_BRIGHT_BIT " : "")
1154 + (((state & SCREEN_ON_BIT) != 0)
1155 ? "SCREEN_ON_BIT " : "")
1156 + (((state & BATTERY_LOW_BIT) != 0)
1157 ? "BATTERY_LOW_BIT " : "");
1158 }
1159
1160 @Override
1161 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1162 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1163 != PackageManager.PERMISSION_GRANTED) {
1164 pw.println("Permission Denial: can't dump PowerManager from from pid="
1165 + Binder.getCallingPid()
1166 + ", uid=" + Binder.getCallingUid());
1167 return;
1168 }
1169
1170 long now = SystemClock.uptimeMillis();
1171
Mike Lockwoodca44df82010-02-25 13:48:49 -05001172 synchronized (mLocks) {
1173 pw.println("Power Manager State:");
1174 pw.println(" mIsPowered=" + mIsPowered
1175 + " mPowerState=" + mPowerState
1176 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1177 + " ms");
1178 pw.println(" mPartialCount=" + mPartialCount);
1179 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1180 pw.println(" mUserState=" + dumpPowerState(mUserState));
1181 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1182 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1183 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1184 + " " + ((mNextTimeout-now)/1000) + "s from now");
1185 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001186 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001187 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1188 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001189 pw.println(" mScreenOffReason=" + mScreenOffReason
1190 + " mUserState=" + mUserState);
1191 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1192 + ',' + mBroadcastQueue[2] + "}");
1193 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1194 + ',' + mBroadcastWhy[2] + "}");
1195 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1196 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1197 + " mUserActivityAllowed=" + mUserActivityAllowed);
1198 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1199 + " mScreenOffDelay=" + mScreenOffDelay);
1200 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1201 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1202 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1203 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1204 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1205 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1206 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1207 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1208 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1209 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1210 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1211 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1212 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1213 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1214 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1215 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08001216 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled
1217 + " mLightSensorAdjustSetting=" + mLightSensorAdjustSetting);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001218 pw.println(" mLightSensorValue=" + mLightSensorValue
1219 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001220 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1221 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001222 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1223 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1224 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1225 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1226 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
Jim Miller92e66dd2012-02-21 18:57:12 -08001227 mScreenBrightnessAnimator.dump(pw, " mScreenBrightnessAnimator: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001228
Mike Lockwoodca44df82010-02-25 13:48:49 -05001229 int N = mLocks.size();
1230 pw.println();
1231 pw.println("mLocks.size=" + N + ":");
1232 for (int i=0; i<N; i++) {
1233 WakeLock wl = mLocks.get(i);
1234 String type = lockType(wl.flags & LOCK_MASK);
1235 String acquireCausesWakeup = "";
1236 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1237 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1238 }
1239 String activated = "";
1240 if (wl.activated) {
1241 activated = " activated";
1242 }
1243 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001244 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1245 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001247
1248 pw.println();
1249 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1250 for (PokeLock p: mPokeLocks.values()) {
1251 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001252 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1253 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001254 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1255 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1256 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1257 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001259
Mike Lockwoodca44df82010-02-25 13:48:49 -05001260 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
1263
Joe Onorato7999bff2010-07-24 11:50:05 -04001264 private void setTimeoutLocked(long now, int nextState) {
1265 setTimeoutLocked(now, -1, nextState);
1266 }
1267
1268 // If they gave a timeoutOverride it is the number of seconds
1269 // to screen-off. Figure out where in the countdown cycle we
1270 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001271 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1272 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001273 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001274 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001275 long when = 0;
1276 if (timeoutOverride <= 0) {
1277 switch (nextState)
1278 {
1279 case SCREEN_BRIGHT:
1280 when = now + mKeylightDelay;
1281 break;
1282 case SCREEN_DIM:
1283 if (mDimDelay >= 0) {
1284 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001285 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001286 } else {
1287 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1288 }
1289 case SCREEN_OFF:
1290 synchronized (mLocks) {
1291 when = now + mScreenOffDelay;
1292 }
1293 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001294 default:
1295 when = now;
1296 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001298 } else {
1299 override: {
1300 if (timeoutOverride <= mScreenOffDelay) {
1301 when = now + timeoutOverride;
1302 nextState = SCREEN_OFF;
1303 break override;
1304 }
1305 timeoutOverride -= mScreenOffDelay;
1306
1307 if (mDimDelay >= 0) {
1308 if (timeoutOverride <= mDimDelay) {
1309 when = now + timeoutOverride;
1310 nextState = SCREEN_DIM;
1311 break override;
1312 }
1313 timeoutOverride -= mDimDelay;
1314 }
1315
1316 when = now + timeoutOverride;
1317 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001319 }
1320 if (mSpew) {
1321 Slog.d(TAG, "setTimeoutLocked now=" + now
1322 + " timeoutOverride=" + timeoutOverride
1323 + " nextState=" + nextState + " when=" + when);
1324 }
Joe Onorato797e6882010-08-26 14:46:01 -04001325
1326 mHandler.removeCallbacks(mTimeoutTask);
1327 mTimeoutTask.nextState = nextState;
1328 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1329 ? (originalTimeoutOverride - timeoutOverride)
1330 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001331 mHandler.postAtTime(mTimeoutTask, when);
1332 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335 }
1336
1337 private void cancelTimerLocked()
1338 {
1339 mHandler.removeCallbacks(mTimeoutTask);
1340 mTimeoutTask.nextState = -1;
1341 }
1342
1343 private class TimeoutTask implements Runnable
1344 {
1345 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001346 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 public void run()
1348 {
1349 synchronized (mLocks) {
1350 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001351 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
1353
1354 if (nextState == -1) {
1355 return;
1356 }
1357
1358 mUserState = this.nextState;
1359 setPowerState(this.nextState | mWakeLockState);
1360
1361 long now = SystemClock.uptimeMillis();
1362
1363 switch (this.nextState)
1364 {
1365 case SCREEN_BRIGHT:
1366 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001367 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 break;
1369 }
1370 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001371 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 break;
1373 }
1374 }
1375 }
1376 }
1377
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001378 private void sendNotificationLocked(boolean on, int why) {
1379 if (!mInitialized) {
1380 // No notifications sent until first initialization is done.
1381 // This is so that when we are moving from our initial state
1382 // which looks like the screen was off to it being on, we do not
1383 // go through the process of waiting for the higher-level user
1384 // space to be ready before turning up the display brightness.
1385 // (And also do not send needless broadcasts about the screen.)
1386 return;
1387 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001388
1389 if (DEBUG_SCREEN_ON) {
1390 RuntimeException here = new RuntimeException("here");
1391 here.fillInStackTrace();
1392 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1393 }
1394
Joe Onorato64c62ba2009-03-24 20:13:57 -07001395 if (!on) {
1396 mStillNeedSleepNotification = false;
1397 }
1398
Joe Onorato128e7292009-03-24 18:41:31 -07001399 // Add to the queue.
1400 int index = 0;
1401 while (mBroadcastQueue[index] != -1) {
1402 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
Joe Onorato128e7292009-03-24 18:41:31 -07001404 mBroadcastQueue[index] = on ? 1 : 0;
1405 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406
Joe Onorato128e7292009-03-24 18:41:31 -07001407 // If we added it position 2, then there is a pair that can be stripped.
1408 // If we added it position 1 and we're turning the screen off, we can strip
1409 // the pair and do nothing, because the screen is already off, and therefore
1410 // keyguard has already been enabled.
1411 // However, if we added it at position 1 and we're turning it on, then position
1412 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1413 // on, so have to run the queue then.
1414 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001415 // While we're collapsing them, if it's going off, and the new reason
1416 // is more significant than the first, then use the new one.
1417 if (!on && mBroadcastWhy[0] > why) {
1418 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001419 }
1420 mBroadcastQueue[0] = on ? 1 : 0;
1421 mBroadcastQueue[1] = -1;
1422 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001423 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001424 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001425 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001426 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001427 index = 0;
1428 }
1429 if (index == 1 && !on) {
1430 mBroadcastQueue[0] = -1;
1431 mBroadcastQueue[1] = -1;
1432 index = -1;
1433 // The wake lock was being held, but we're not actually going to do any
1434 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001435 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001437 }
1438
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001439 // The broadcast queue has changed; make sure the screen is on if it
1440 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001441 if (mSkippedScreenOn) {
1442 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1443 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001444
Joe Onorato128e7292009-03-24 18:41:31 -07001445 // Now send the message.
1446 if (index >= 0) {
1447 // Acquire the broadcast wake lock before changing the power
1448 // state. It will be release after the broadcast is sent.
1449 // We always increment the ref count for each notification in the queue
1450 // and always decrement when that notification is handled.
1451 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001453 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 }
1455 }
1456
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001457 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1458 new WindowManagerPolicy.ScreenOnListener() {
Jim Miller92e66dd2012-02-21 18:57:12 -08001459 public void onScreenOn() {
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001460 synchronized (mLocks) {
1461 if (mPreparingForScreenOn) {
1462 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001463 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001464 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1465 4, mBroadcastWakeLock.mCount);
1466 mBroadcastWakeLock.release();
1467 }
1468 }
1469 }
1470 };
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private Runnable mNotificationTask = new Runnable()
1473 {
1474 public void run()
1475 {
Joe Onorato128e7292009-03-24 18:41:31 -07001476 while (true) {
1477 int value;
1478 int why;
1479 WindowManagerPolicy policy;
1480 synchronized (mLocks) {
1481 value = mBroadcastQueue[0];
1482 why = mBroadcastWhy[0];
1483 for (int i=0; i<2; i++) {
1484 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1485 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1486 }
1487 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001488 if (value == 1 && !mPreparingForScreenOn) {
1489 mPreparingForScreenOn = true;
1490 mBroadcastWakeLock.acquire();
1491 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1492 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
Joe Onorato128e7292009-03-24 18:41:31 -07001495 if (value == 1) {
1496 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001497
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001498 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001499 try {
1500 ActivityManagerNative.getDefault().wakingUp();
1501 } catch (RemoteException e) {
1502 // ignore it
1503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
Joe Onorato128e7292009-03-24 18:41:31 -07001505 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001506 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001507 }
1508 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1509 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1510 mScreenOnBroadcastDone, mHandler, 0, null, null);
1511 } else {
1512 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001513 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001514 mBroadcastWakeLock.mCount);
1515 mBroadcastWakeLock.release();
1516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518 }
Joe Onorato128e7292009-03-24 18:41:31 -07001519 else if (value == 0) {
1520 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001521
Joe Onorato128e7292009-03-24 18:41:31 -07001522 policy.screenTurnedOff(why);
1523 try {
1524 ActivityManagerNative.getDefault().goingToSleep();
1525 } catch (RemoteException e) {
1526 // ignore it.
1527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528
Joe Onorato128e7292009-03-24 18:41:31 -07001529 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1530 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1531 mScreenOffBroadcastDone, mHandler, 0, null, null);
1532 } else {
1533 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001534 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001535 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001536 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001537 mBroadcastWakeLock.release();
1538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
Joe Onorato128e7292009-03-24 18:41:31 -07001541 else {
1542 // If we're in this case, then this handler is running for a previous
1543 // paired transaction. mBroadcastWakeLock will already have been released.
1544 break;
1545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548 };
1549
1550 long mScreenOnStart;
1551 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1552 public void onReceive(Context context, Intent intent) {
1553 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001554 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1556 mBroadcastWakeLock.release();
1557 }
1558 }
1559 };
1560
1561 long mScreenOffStart;
1562 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1563 public void onReceive(Context context, Intent intent) {
1564 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001565 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1567 mBroadcastWakeLock.release();
1568 }
1569 }
1570 };
1571
1572 void logPointerUpEvent() {
1573 if (LOG_TOUCH_DOWNS) {
1574 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1575 mLastTouchDown = 0;
1576 }
1577 }
1578
1579 void logPointerDownEvent() {
1580 if (LOG_TOUCH_DOWNS) {
1581 // If we are not already timing a down/up sequence
1582 if (mLastTouchDown == 0) {
1583 mLastTouchDown = SystemClock.elapsedRealtime();
1584 mTouchCycles++;
1585 }
1586 }
1587 }
1588
1589 /**
1590 * Prevents the screen from turning on even if it *should* turn on due
1591 * to a subsequent full wake lock being acquired.
1592 * <p>
1593 * This is a temporary hack that allows an activity to "cover up" any
1594 * display glitches that happen during the activity's startup
1595 * sequence. (Specifically, this API was added to work around a
1596 * cosmetic bug in the "incoming call" sequence, where the lock screen
1597 * would flicker briefly before the incoming call UI became visible.)
1598 * TODO: There ought to be a more elegant way of doing this,
1599 * probably by having the PowerManager and ActivityManager
1600 * work together to let apps specify that the screen on/off
1601 * state should be synchronized with the Activity lifecycle.
1602 * <p>
1603 * Note that calling preventScreenOn(true) will NOT turn the screen
1604 * off if it's currently on. (This API only affects *future*
1605 * acquisitions of full wake locks.)
1606 * But calling preventScreenOn(false) WILL turn the screen on if
1607 * it's currently off because of a prior preventScreenOn(true) call.
1608 * <p>
1609 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1610 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1611 * call doesn't occur within 5 seconds, we'll turn the screen back on
1612 * ourselves (and log a warning about it); this prevents a buggy app
1613 * from disabling the screen forever.)
1614 * <p>
1615 * TODO: this feature should really be controlled by a new type of poke
1616 * lock (rather than an IPowerManager call).
1617 */
1618 public void preventScreenOn(boolean prevent) {
1619 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1620
1621 synchronized (mLocks) {
1622 if (prevent) {
1623 // First of all, grab a partial wake lock to
1624 // make sure the CPU stays on during the entire
1625 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1626 mPreventScreenOnPartialLock.acquire();
1627
1628 // Post a forceReenableScreen() call (for 5 seconds in the
1629 // future) to make sure the matching preventScreenOn(false) call
1630 // has happened by then.
1631 mHandler.removeCallbacks(mForceReenableScreenTask);
1632 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1633
1634 // Finally, set the flag that prevents the screen from turning on.
1635 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001636 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 mPreventScreenOn = true;
1638 } else {
1639 // (Re)enable the screen.
1640 mPreventScreenOn = false;
1641
1642 // We're "undoing" a the prior preventScreenOn(true) call, so we
1643 // no longer need the 5-second safeguard.
1644 mHandler.removeCallbacks(mForceReenableScreenTask);
1645
1646 // Forcibly turn on the screen if it's supposed to be on. (This
1647 // handles the case where the screen is currently off because of
1648 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001649 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001651 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1653 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001654 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001656 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658 }
1659
1660 // Release the partial wake lock that we held during the
1661 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1662 mPreventScreenOnPartialLock.release();
1663 }
1664 }
1665 }
1666
1667 public void setScreenBrightnessOverride(int brightness) {
1668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1669
Mike Lockwoodf527c712010-06-10 14:12:33 -04001670 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 synchronized (mLocks) {
1672 if (mScreenBrightnessOverride != brightness) {
1673 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001674 if (isScreenOn()) {
1675 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 }
1679 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001680
1681 public void setButtonBrightnessOverride(int brightness) {
1682 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1683
Mike Lockwoodf527c712010-06-10 14:12:33 -04001684 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001685 synchronized (mLocks) {
1686 if (mButtonBrightnessOverride != brightness) {
1687 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001688 if (isScreenOn()) {
1689 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1690 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001691 }
1692 }
1693 }
1694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 /**
1696 * Sanity-check that gets called 5 seconds after any call to
1697 * preventScreenOn(true). This ensures that the original call
1698 * is followed promptly by a call to preventScreenOn(false).
1699 */
1700 private void forceReenableScreen() {
1701 // We shouldn't get here at all if mPreventScreenOn is false, since
1702 // we should have already removed any existing
1703 // mForceReenableScreenTask messages...
1704 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001705 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 return;
1707 }
1708
1709 // Uh oh. It's been 5 seconds since a call to
1710 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1711 // This means the app that called preventScreenOn(true) is either
1712 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1713 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1714 // crashed before doing so.)
1715
1716 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001717 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 + "Forcing the screen back on...");
1719 preventScreenOn(false);
1720 }
1721
1722 private Runnable mForceReenableScreenTask = new Runnable() {
1723 public void run() {
1724 forceReenableScreen();
1725 }
1726 };
1727
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001728 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001729 if (DEBUG_SCREEN_ON) {
1730 RuntimeException e = new RuntimeException("here");
1731 e.fillInStackTrace();
1732 Slog.i(TAG, "Set screen state: " + on, e);
1733 }
Dianne Hackborn474fd742011-10-10 18:40:22 -07001734 if (on) {
1735 if ((mPowerState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1736 // If we are turning the screen state on, but the screen
1737 // light is currently off, then make sure that we set the
1738 // light at this point to 0. This is the case where we are
1739 // turning on the screen and waiting for the UI to be drawn
1740 // before showing it to the user. We want the light off
1741 // until it is ready to be shown to the user, not it using
1742 // whatever the last value it had.
Dianne Hackborn81de8b92011-11-28 16:54:31 -08001743 if (DEBUG_SCREEN_ON) {
1744 Slog.i(TAG, "Forcing brightness 0: mPowerState=0x"
1745 + Integer.toHexString(mPowerState)
1746 + " mSkippedScreenOn=" + mSkippedScreenOn);
1747 }
Jim Miller46f31c32012-03-01 14:36:07 -08001748 mScreenBrightnessHandler.removeMessages(ScreenBrightnessAnimator.ANIMATE_LIGHTS);
Jeff Brown7304c342012-05-11 18:42:42 -07001749 mScreenBrightnessAnimator.animateTo(PowerManager.BRIGHTNESS_OFF, SCREEN_BRIGHT_BIT, 0);
Dianne Hackborn474fd742011-10-10 18:40:22 -07001750 }
1751 }
Jeff Brown7304c342012-05-11 18:42:42 -07001752 int err = nativeSetScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001753 if (err == 0) {
1754 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1755 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001756 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001757 if (!on) {
1758 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001759 mButtonLight.turnOff();
1760 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001761 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001762 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001763 }
1764 return err;
1765 }
1766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 private void setPowerState(int state)
1768 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001769 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771
Mike Lockwood435eb642009-12-03 08:40:18 -05001772 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 {
1774 synchronized (mLocks) {
1775 int err;
1776
1777 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001778 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001780 + " noChangeLights=" + noChangeLights
1781 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
Daniel Sandler7d276c32012-01-30 14:33:52 -05001783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 if (noChangeLights) {
1785 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1786 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001787 if (mProximitySensorActive) {
1788 // don't turn on the screen when the proximity sensor lock is held
1789 newState = (newState & ~SCREEN_BRIGHT);
1790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791
1792 if (batteryIsLow()) {
1793 newState |= BATTERY_LOW_BIT;
1794 } else {
1795 newState &= ~BATTERY_LOW_BIT;
1796 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001797 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 return;
1799 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001800
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001801 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 newState |= ALL_BRIGHT;
1803 }
1804
1805 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1806 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1807
Mike Lockwood51b844962009-11-16 21:51:18 -05001808 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001811 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001813 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001815 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001817 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001819 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1821 }
1822
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001823 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824
Daniel Sandler7d276c32012-01-30 14:33:52 -05001825 if (stateChanged && reason == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT) {
Daniel Sandler0af48952012-04-10 15:14:35 -04001826 if (mPolicy != null && mPolicy.isScreenSaverEnabled()) {
Daniel Sandler7d276c32012-01-30 14:33:52 -05001827 if (mSpew) {
1828 Slog.d(TAG, "setPowerState: running screen saver instead of turning off screen");
1829 }
1830 if (mPolicy.startScreenSaver()) {
1831 // was successful
1832 return;
1833 }
1834 }
1835 }
1836
1837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 if (oldScreenOn != newScreenOn) {
1839 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001840 // When the user presses the power button, we need to always send out the
1841 // notification that it's going to sleep so the keyguard goes on. But
1842 // we can't do that until the screen fades out, so we don't show the keyguard
1843 // too early.
1844 if (mStillNeedSleepNotification) {
1845 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1846 }
1847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 // Turn on the screen UNLESS there was a prior
1849 // preventScreenOn(true) request. (Note that the lifetime
1850 // of a single preventScreenOn() request is limited to 5
1851 // seconds to prevent a buggy app from disabling the
1852 // screen forever; see forceReenableScreen().)
1853 boolean reallyTurnScreenOn = true;
1854 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001855 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 + mPreventScreenOn);
1857 }
1858
1859 if (mPreventScreenOn) {
1860 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001861 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
1863 reallyTurnScreenOn = false;
1864 }
1865 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001866 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 long identity = Binder.clearCallingIdentity();
1868 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001869 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 mBatteryStats.noteScreenOn();
1871 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001872 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 } finally {
1874 Binder.restoreCallingIdentity(identity);
1875 }
1876 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001877 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 // But continue as if we really did turn the screen on...
1879 err = 0;
1880 }
1881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 mLastTouchDown = 0;
1883 mTotalTouchDownTime = 0;
1884 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001885 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 mTotalTouchDownTime, mTouchCycles);
1887 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001889 // Update the lights *after* taking care of turning the
1890 // screen on, so we do this after our notifications are
1891 // enqueued and thus will delay turning on the screen light
1892 // until the windows are correctly displayed.
1893 if (stateChanged) {
1894 updateLightsLocked(newState, 0);
1895 }
1896 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001900 // Update the lights *before* taking care of turning the
1901 // screen off, so we can initiate any animations that are desired.
Craig Mautner44bf70f2012-03-13 11:38:38 -07001902 mScreenOffReason = reason;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001903 if (stateChanged) {
1904 updateLightsLocked(newState, 0);
1905 }
1906
Mike Lockwood497087e32009-11-08 18:33:03 -05001907 // cancel light sensor task
1908 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001909 mLightSensorPendingDecrease = false;
1910 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 mScreenOffTime = SystemClock.elapsedRealtime();
1912 long identity = Binder.clearCallingIdentity();
1913 try {
1914 mBatteryStats.noteScreenOff();
1915 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001916 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 } finally {
1918 Binder.restoreCallingIdentity(identity);
1919 }
1920 mPowerState &= ~SCREEN_ON_BIT;
Jim Miller92e66dd2012-02-21 18:57:12 -08001921 if (!mScreenBrightnessAnimator.isAnimating()) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001922 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 err = 0;
1925 mLastTouchDown = 0;
1926 }
1927 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001928 } else if (stateChanged) {
1929 // Screen on/off didn't change, but lights may have.
1930 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001932
1933 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1934
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001935 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001938
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001939 private void updateNativePowerStateLocked() {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001940 if (!mHeadless) {
1941 nativeSetPowerState(
1942 (mPowerState & SCREEN_ON_BIT) != 0,
1943 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1944 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001946
Mike Lockwood435eb642009-12-03 08:40:18 -05001947 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001951 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1952 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001954 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001956 mScreenOffReason = reason;
1957 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
1959 return err;
1960 }
1961
1962 private boolean batteryIsLow() {
1963 return (!mIsPowered &&
Jeff Brown7304c342012-05-11 18:42:42 -07001964 mBatteryService.getBatteryLevel() <= LOW_BATTERY_THRESHOLD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001967 private boolean shouldDeferScreenOnLocked() {
1968 if (mPreparingForScreenOn) {
1969 // Currently waiting for confirmation from the policy that it
1970 // is okay to turn on the screen. Don't allow the screen to go
1971 // on until that is done.
1972 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1973 "updateLights: delaying screen on due to mPreparingForScreenOn");
1974 return true;
1975 } else {
1976 // If there is a screen-on command in the notification queue, we
1977 // can't turn the screen on until it has been processed (and we
1978 // have set mPreparingForScreenOn) or it has been dropped.
1979 for (int i=0; i<mBroadcastQueue.length; i++) {
1980 if (mBroadcastQueue[i] == 1) {
1981 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1982 "updateLights: delaying screen on due to notification queue");
1983 return true;
1984 }
1985 }
1986 }
1987 return false;
1988 }
1989
The Android Open Source Project10592532009-03-18 17:39:46 -07001990 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001991 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001992
1993 // If the screen is not currently on, we will want to delay actually
1994 // turning the lights on if we are still getting the UI put up.
Jim Miller92e66dd2012-02-21 18:57:12 -08001995 if ((oldState & SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001996 // Don't turn screen on until we know we are really ready to.
1997 // This is to avoid letting the screen go on before things like the
1998 // lock screen have been displayed.
Jim Miller92e66dd2012-02-21 18:57:12 -08001999 if ((mSkippedScreenOn = shouldDeferScreenOnLocked())) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002000 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
2001 }
2002 }
2003
Joe Onorato60607a902010-10-23 14:49:30 -07002004 if ((newState & SCREEN_ON_BIT) != 0) {
2005 // Only turn on the buttons or keyboard if the screen is also on.
2006 // We should never see the buttons on but not the screen.
2007 newState = applyButtonState(newState);
2008 newState = applyKeyboardState(newState);
2009 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002010 final int realDifference = (newState ^ oldState);
2011 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002013 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 int offMask = 0;
2017 int dimMask = 0;
2018 int onMask = 0;
2019
2020 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002023 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
2024 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002026 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 }
2029
2030 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002031 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
2032 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002034 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
2036 }
2037
2038 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002039 int nominalCurrentValue = -1;
2040 // If there was an actual difference in the light state, then
2041 // figure out the "ideal" current value based on the previous
2042 // state. Otherwise, this is a change due to the brightness
2043 // override, so we want to animate from whatever the current
2044 // value is.
2045 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
2046 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
2047 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
2048 nominalCurrentValue = preferredBrightness;
2049 break;
2050 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002051 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002052 break;
2053 case 0:
Jeff Brown7304c342012-05-11 18:42:42 -07002054 nominalCurrentValue = PowerManager.BRIGHTNESS_OFF;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002055 break;
2056 case SCREEN_BRIGHT_BIT:
2057 default:
2058 // not possible
Jim Miller92e66dd2012-02-21 18:57:12 -08002059 nominalCurrentValue = (int)mScreenBrightnessAnimator.getCurrentBrightness();
Joe Onoratob08a1af2010-10-11 19:28:58 -07002060 break;
Joe Onorato128e7292009-03-24 18:41:31 -07002061 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002062 }
2063 int brightness = preferredBrightness;
2064 int steps = ANIM_STEPS;
2065 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
2066 // dim or turn off backlight, depending on if the screen is on
2067 // the scale is because the brightness ramp isn't linear and this biases
2068 // it so the later parts take longer.
2069 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002070 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002071 if (ratio > 1.0f) ratio = 1.0f;
2072 if ((newState & SCREEN_ON_BIT) == 0) {
2073 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
2074 // was bright
2075 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002077 // was dim
2078 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
Jeff Brown7304c342012-05-11 18:42:42 -07002080 brightness = PowerManager.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002082 if ((oldState & SCREEN_ON_BIT) != 0) {
2083 // was bright
2084 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2085 } else {
2086 // was dim
2087 steps = (int)(ANIM_STEPS*ratio);
2088 }
2089 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2090 // If the "stay on while plugged in" option is
2091 // turned on, then the screen will often not
2092 // automatically turn off while plugged in. To
2093 // still have a sense of when it is inactive, we
2094 // will then count going dim as turning off.
2095 mScreenOffTime = SystemClock.elapsedRealtime();
2096 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002097 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
2099 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002100 long identity = Binder.clearCallingIdentity();
2101 try {
2102 mBatteryStats.noteScreenBrightness(brightness);
2103 } catch (RemoteException e) {
2104 // Nothing interesting to do.
2105 } finally {
2106 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002108 if (!mSkippedScreenOn) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002109 int dt = steps * NOMINAL_FRAME_TIME_MS;
2110 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, dt);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002111 if (DEBUG_SCREEN_ON) {
2112 RuntimeException e = new RuntimeException("here");
2113 e.fillInStackTrace();
2114 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2115 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002118
Joe Onorato60607a902010-10-23 14:49:30 -07002119 if (mSpew) {
2120 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2121 + " dimMask=0x" + Integer.toHexString(dimMask)
2122 + " onMask=0x" + Integer.toHexString(onMask)
2123 + " difference=0x" + Integer.toHexString(difference)
2124 + " realDifference=0x" + Integer.toHexString(realDifference)
2125 + " forceState=0x" + Integer.toHexString(forceState)
2126 );
2127 }
2128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002130 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
Jeff Brown7304c342012-05-11 18:42:42 -07002131 setLightBrightness(offMask, PowerManager.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
2133 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002134 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 if ((newState & BATTERY_LOW_BIT) != 0 &&
Jeff Brown7304c342012-05-11 18:42:42 -07002136 brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) {
2137 brightness = PowerManager.BRIGHTNESS_LOW_BATTERY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002139 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002140 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 if (onMask != 0) {
2143 int brightness = getPreferredBrightness();
2144 if ((newState & BATTERY_LOW_BIT) != 0 &&
Jeff Brown7304c342012-05-11 18:42:42 -07002145 brightness > PowerManager.BRIGHTNESS_LOW_BATTERY) {
2146 brightness = PowerManager.BRIGHTNESS_LOW_BATTERY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002148 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002149 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152
Jim Miller92e66dd2012-02-21 18:57:12 -08002153 /**
2154 * Note: by design this class does not hold mLocks while calling native methods.
2155 * Nor should it. Ever.
2156 */
2157 class ScreenBrightnessAnimator extends HandlerThread {
2158 static final int ANIMATE_LIGHTS = 10;
Jim Miller46f31c32012-03-01 14:36:07 -08002159 static final int ANIMATE_POWER_OFF = 11;
Jim Miller92e66dd2012-02-21 18:57:12 -08002160 volatile int startValue;
2161 volatile int endValue;
2162 volatile int currentValue;
2163 private int currentMask;
2164 private int duration;
2165 private long startTimeMillis;
2166 private final String prefix;
2167
2168 public ScreenBrightnessAnimator(String name, int priority) {
2169 super(name, priority);
2170 prefix = name;
2171 }
2172
2173 @Override
2174 protected void onLooperPrepared() {
2175 mScreenBrightnessHandler = new Handler() {
2176 public void handleMessage(Message msg) {
2177 int brightnessMode = (mAutoBrightessEnabled && !mInitialAnimation
Mike Lockwood3a322132009-11-24 00:30:52 -05002178 ? LightsService.BRIGHTNESS_MODE_SENSOR
2179 : LightsService.BRIGHTNESS_MODE_USER);
Jim Miller92e66dd2012-02-21 18:57:12 -08002180 if (msg.what == ANIMATE_LIGHTS) {
2181 final int mask = msg.arg1;
2182 int value = msg.arg2;
2183 long tStart = SystemClock.uptimeMillis();
2184 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
2185 if (mDebugLightAnimation) Log.v(TAG, "Set brightness: " + value);
2186 mLcdLight.setBrightness(value, brightnessMode);
2187 }
2188 long elapsed = SystemClock.uptimeMillis() - tStart;
2189 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
2190 mButtonLight.setBrightness(value);
2191 }
2192 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
2193 mKeyboardLight.setBrightness(value);
2194 }
2195
2196 if (elapsed > 100) {
2197 Log.e(TAG, "Excessive delay setting brightness: " + elapsed
2198 + "ms, mask=" + mask);
2199 }
2200
2201 // Throttle brightness updates to frame refresh rate
2202 int delay = elapsed < NOMINAL_FRAME_TIME_MS ? NOMINAL_FRAME_TIME_MS : 0;
2203 synchronized(this) {
2204 currentValue = value;
2205 }
2206 animateInternal(mask, false, delay);
Jim Miller46f31c32012-03-01 14:36:07 -08002207 } else if (msg.what == ANIMATE_POWER_OFF) {
2208 int mode = msg.arg1;
2209 nativeStartSurfaceFlingerAnimation(mode);
Jim Miller92e66dd2012-02-21 18:57:12 -08002210 }
2211 }
2212 };
2213 synchronized (this) {
2214 mInitComplete = true;
2215 notifyAll();
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002216 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002217 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002218
2219 private void animateInternal(int mask, boolean turningOff, int delay) {
2220 synchronized (this) {
2221 if (currentValue != endValue) {
2222 final long now = SystemClock.elapsedRealtime();
2223 final int elapsed = (int) (now - startTimeMillis);
2224 int newValue;
2225 if (elapsed < duration) {
2226 int delta = endValue - startValue;
2227 newValue = startValue + delta * elapsed / duration;
Jeff Brown7304c342012-05-11 18:42:42 -07002228 newValue = Math.max(PowerManager.BRIGHTNESS_OFF, newValue);
2229 newValue = Math.min(PowerManager.BRIGHTNESS_ON, newValue);
Jim Miller92e66dd2012-02-21 18:57:12 -08002230 } else {
2231 newValue = endValue;
2232 mInitialAnimation = false;
2233 }
2234
2235 if (mDebugLightAnimation) {
2236 Log.v(TAG, "Animating light: " + "start:" + startValue
2237 + ", end:" + endValue + ", elapsed:" + elapsed
2238 + ", duration:" + duration + ", current:" + currentValue
2239 + ", delay:" + delay);
2240 }
2241
Jim Miller46f31c32012-03-01 14:36:07 -08002242 if (turningOff && !mHeadless && !mAnimateScreenLights) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002243 int mode = mScreenOffReason == OFF_BECAUSE_OF_PROX_SENSOR
2244 ? 0 : mAnimationSetting;
2245 if (mDebugLightAnimation) Log.v(TAG, "Doing power-off anim, mode=" + mode);
Jim Miller46f31c32012-03-01 14:36:07 -08002246 mScreenBrightnessHandler.obtainMessage(ANIMATE_POWER_OFF, mode, 0)
2247 .sendToTarget();
Jim Miller92e66dd2012-02-21 18:57:12 -08002248 }
2249 Message msg = mScreenBrightnessHandler
2250 .obtainMessage(ANIMATE_LIGHTS, mask, newValue);
2251 mScreenBrightnessHandler.sendMessageDelayed(msg, delay);
2252 }
2253 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002254 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002255
2256 public void dump(PrintWriter pw, String string) {
2257 pw.println(prefix + "animating: " + "start:" + startValue + ", end:" + endValue
2258 + ", duration:" + duration + ", current:" + currentValue);
2259 }
2260
2261 public void animateTo(int target, int mask, int animationDuration) {
2262 synchronized(this) {
2263 startValue = currentValue;
2264 endValue = target;
2265 currentMask = mask;
2266 duration = (int) (mWindowScaleAnimation * animationDuration);
2267 startTimeMillis = SystemClock.elapsedRealtime();
2268 mInitialAnimation = currentValue == 0 && target > 0;
2269
2270 if (mDebugLightAnimation) {
2271 Log.v(TAG, "animateTo(target=" + target + ", mask=" + mask
2272 + ", duration=" + animationDuration +")"
2273 + ", currentValue=" + currentValue
2274 + ", startTime=" + startTimeMillis);
2275 }
2276
2277 if (target != currentValue) {
Jim Miller18651802012-03-07 14:19:56 -08002278 final boolean doScreenAnim = (mask & (SCREEN_BRIGHT_BIT | SCREEN_ON_BIT)) != 0;
Jeff Brown7304c342012-05-11 18:42:42 -07002279 final boolean turningOff = endValue == PowerManager.BRIGHTNESS_OFF;
Jim Miller18651802012-03-07 14:19:56 -08002280 if (turningOff && doScreenAnim) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002281 // Cancel all pending animations since we're turning off
2282 mScreenBrightnessHandler.removeCallbacksAndMessages(null);
2283 screenOffFinishedAnimatingLocked(mScreenOffReason);
2284 duration = 200; // TODO: how long should this be?
2285 }
Jim Miller18651802012-03-07 14:19:56 -08002286 if (doScreenAnim) {
2287 animateInternal(mask, turningOff, 0);
2288 }
2289 // TODO: Handle keyboard light animation when we have devices that support it
Jim Miller92e66dd2012-02-21 18:57:12 -08002290 }
2291 }
2292 }
2293
2294 public int getCurrentBrightness() {
2295 synchronized (this) {
2296 return currentValue;
2297 }
2298 }
2299
2300 public boolean isAnimating() {
2301 synchronized (this) {
2302 return currentValue != endValue;
2303 }
2304 }
2305
2306 public void cancelAnimation() {
2307 animateTo(endValue, currentMask, 0);
The Android Open Source Project10592532009-03-18 17:39:46 -07002308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 }
2310
Jim Miller92e66dd2012-02-21 18:57:12 -08002311 private void setLightBrightness(int mask, int value) {
2312 mScreenBrightnessAnimator.animateTo(value, mask, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 private int getPreferredBrightness() {
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002316 if (mScreenBrightnessOverride >= 0) {
2317 return mScreenBrightnessOverride;
2318 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
2319 && mAutoBrightessEnabled) {
2320 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002322 final int brightness = mScreenBrightnessSetting;
2323 // Don't let applications turn the screen all the way off
2324 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 }
2326
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002327 private int applyButtonState(int state) {
2328 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002329 if ((state & BATTERY_LOW_BIT) != 0) {
2330 // do not override brightness if the battery is low
2331 return state;
2332 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002333 if (mButtonBrightnessOverride >= 0) {
2334 brightness = mButtonBrightnessOverride;
2335 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2336 brightness = mLightSensorButtonBrightness;
2337 }
2338 if (brightness > 0) {
2339 return state | BUTTON_BRIGHT_BIT;
2340 } else if (brightness == 0) {
2341 return state & ~BUTTON_BRIGHT_BIT;
2342 } else {
2343 return state;
2344 }
2345 }
2346
2347 private int applyKeyboardState(int state) {
2348 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002349 if ((state & BATTERY_LOW_BIT) != 0) {
2350 // do not override brightness if the battery is low
2351 return state;
2352 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002353 if (!mKeyboardVisible) {
2354 brightness = 0;
2355 } else if (mButtonBrightnessOverride >= 0) {
2356 brightness = mButtonBrightnessOverride;
2357 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2358 brightness = mLightSensorKeyboardBrightness;
2359 }
2360 if (brightness > 0) {
2361 return state | KEYBOARD_BRIGHT_BIT;
2362 } else if (brightness == 0) {
2363 return state & ~KEYBOARD_BRIGHT_BIT;
2364 } else {
2365 return state;
2366 }
2367 }
2368
Charles Mendis322591c2009-10-29 11:06:59 -07002369 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 synchronized (mLocks) {
2371 return (mPowerState & SCREEN_ON_BIT) != 0;
2372 }
2373 }
2374
Charles Mendis322591c2009-10-29 11:06:59 -07002375 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 synchronized (mLocks) {
2377 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2378 }
2379 }
2380
Mike Lockwood497087e32009-11-08 18:33:03 -05002381 private boolean isScreenTurningOffLocked() {
Jim Miller92e66dd2012-02-21 18:57:12 -08002382 return (mScreenBrightnessAnimator.isAnimating()
Jeff Brown7304c342012-05-11 18:42:42 -07002383 && mScreenBrightnessAnimator.endValue == PowerManager.BRIGHTNESS_OFF);
Mike Lockwood497087e32009-11-08 18:33:03 -05002384 }
2385
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002386 private boolean shouldLog(long time) {
2387 synchronized (mLocks) {
2388 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2389 mWarningSpewThrottleTime = time;
2390 mWarningSpewThrottleCount = 0;
2391 return true;
2392 } else if (mWarningSpewThrottleCount < 30) {
2393 mWarningSpewThrottleCount++;
2394 return true;
2395 } else {
2396 return false;
2397 }
2398 }
2399 }
2400
Mike Lockwood200b30b2009-09-20 00:23:59 -04002401 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002402 if (isScreenTurningOffLocked()) {
2403 // cancel animation so userActivity will succeed
Jim Miller92e66dd2012-02-21 18:57:12 -08002404 mScreenBrightnessAnimator.cancelAnimation();
Mike Lockwoode090281422009-11-14 21:02:56 -05002405 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002406 boolean savedActivityAllowed = mUserActivityAllowed;
2407 mUserActivityAllowed = true;
2408 userActivity(SystemClock.uptimeMillis(), false);
2409 mUserActivityAllowed = savedActivityAllowed;
2410 }
2411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002414 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 }
2416
2417 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002418 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2419 != PackageManager.PERMISSION_GRANTED) {
2420 if (shouldLog(time)) {
2421 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2422 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2423 }
2424 return;
2425 }
2426
Joe Onorato7999bff2010-07-24 11:50:05 -04002427 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
2429
2430 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002431 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433
2434 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002435 userActivity(time, -1, noChangeLights, eventType, force);
2436 }
2437
2438 /*
2439 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2440 * on with user activity. Don't use this function.
2441 */
2442 public void clearUserActivityTimeout(long now, long timeout) {
2443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2444 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2445 userActivity(now, timeout, false, OTHER_EVENT, false);
2446 }
2447
2448 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2449 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450
Joe Onorato1a542c72010-11-08 09:48:20 -08002451 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002452 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002453 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002454 }
2455 return;
2456 }
2457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 synchronized (mLocks) {
2459 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002460 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 + " mUserActivityAllowed=" + mUserActivityAllowed
2462 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002463 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2464 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002465 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002466 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
Mike Lockwood05067122009-10-27 23:07:25 -04002468 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002469 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002470 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002471 return;
2472 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002473 // Disable proximity sensor if if user presses power key while we are in the
2474 // "waiting for proximity sensor to go negative" state.
2475 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2476 mProximitySensorActive = false;
2477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 if (mLastEventTime <= time || force) {
2479 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002480 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002481 // Only turn on button backlights if a button was pressed
2482 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002483 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2485 } else {
2486 // don't clear button/keyboard backlights when the screen is touched.
2487 mUserState |= SCREEN_BRIGHT;
2488 }
2489
Dianne Hackborn617f8772009-03-31 15:04:46 -07002490 int uid = Binder.getCallingUid();
2491 long ident = Binder.clearCallingIdentity();
2492 try {
2493 mBatteryStats.noteUserActivity(uid, eventType);
2494 } catch (RemoteException e) {
2495 // Ignore
2496 } finally {
2497 Binder.restoreCallingIdentity(ident);
2498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002499
Michael Chane96440f2009-05-06 10:27:36 -07002500 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002501 setPowerState(mUserState | mWakeLockState, noChangeLights,
2502 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002503 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
2505 }
2506 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002507
2508 if (mPolicy != null) {
2509 mPolicy.userActivity();
2510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
2512
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002513 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2514 try {
2515 int i;
2516 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2517 if (sensorValue < mAutoBrightnessLevels[i]) {
2518 break;
2519 }
2520 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002521 // This is the range of brightness values that we can use.
2522 final int minval = values[0];
2523 final int maxval = values[mAutoBrightnessLevels.length];
2524 // This is the range we will be scaling. We put some padding
2525 // at the low and high end to give the adjustment a little better
2526 // impact on the actual observed value.
2527 final int range = (maxval-minval) + LIGHT_SENSOR_RANGE_EXPANSION;
2528 // This is the desired brightness value from 0.0 to 1.0.
2529 float valf = ((values[i]-minval+(LIGHT_SENSOR_RANGE_EXPANSION/2))/(float)range);
2530 // Apply a scaling to the value based on the adjustment.
2531 if (mLightSensorAdjustSetting > 0 && mLightSensorAdjustSetting <= 1) {
2532 float adj = (float)Math.sqrt(1.0f-mLightSensorAdjustSetting);
2533 if (adj <= .00001) {
2534 valf = 1;
2535 } else {
2536 valf /= adj;
2537 }
2538 } else if (mLightSensorAdjustSetting < 0 && mLightSensorAdjustSetting >= -1) {
2539 float adj = (float)Math.sqrt(1.0f+mLightSensorAdjustSetting);
2540 valf *= adj;
2541 }
2542 // Apply an additional offset to the value based on the adjustment.
2543 valf += mLightSensorAdjustSetting/LIGHT_SENSOR_OFFSET_SCALE;
2544 // Convert the 0.0-1.0 value back to a brightness integer.
2545 int val = (int)((valf*range)+minval) - (LIGHT_SENSOR_RANGE_EXPANSION/2);
2546 if (val < minval) val = minval;
2547 else if (val > maxval) val = maxval;
2548 return val;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002549 } catch (Exception e) {
2550 // guard against null pointer or index out of bounds errors
Jeff Browndaa37532012-05-01 15:54:03 -07002551 Slog.e(TAG, "Values array must be non-empty and must be one element longer than "
2552 + "the auto-brightness levels array. Check config.xml.", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002553 return 255;
2554 }
2555 }
2556
Mike Lockwood20f87d72009-11-05 16:08:51 -05002557 private Runnable mProximityTask = new Runnable() {
2558 public void run() {
2559 synchronized (mLocks) {
2560 if (mProximityPendingValue != -1) {
2561 proximityChangedLocked(mProximityPendingValue == 1);
2562 mProximityPendingValue = -1;
2563 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002564 if (mProximityPartialLock.isHeld()) {
2565 mProximityPartialLock.release();
2566 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002567 }
2568 }
2569 };
2570
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002571 private Runnable mAutoBrightnessTask = new Runnable() {
2572 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002573 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002574 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2575 int value = (int)mLightSensorPendingValue;
2576 mLightSensorPendingDecrease = false;
2577 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002578 lightSensorChangedLocked(value, false);
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002579 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002580 }
2581 }
2582 };
2583
Jim Miller92e66dd2012-02-21 18:57:12 -08002584 private boolean mInitialAnimation; // used to prevent lightsensor changes while turning on
2585
Mike Lockwoodb2865412010-02-02 22:40:33 -05002586 private void dockStateChanged(int state) {
2587 synchronized (mLocks) {
2588 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2589 if (mIsDocked) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04002590 // allow brightness to decrease when docked
Mike Lockwoodb2865412010-02-02 22:40:33 -05002591 mHighestLightSensorValue = -1;
2592 }
2593 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2594 // force lights recalculation
2595 int value = (int)mLightSensorValue;
2596 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002597 lightSensorChangedLocked(value, false);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002598 }
2599 }
2600 }
2601
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002602 private void lightSensorChangedLocked(int value, boolean immediate) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002603 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002604 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002605 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002606
Joe Onorato06eb33a2010-10-25 14:09:21 -07002607 // Don't do anything if the screen is off.
2608 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2609 if (mDebugLightSensor) {
2610 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2611 }
2612 return;
2613 }
2614
Mike Lockwoodb2865412010-02-02 22:40:33 -05002615 // do not allow light sensor value to decrease
2616 if (mHighestLightSensorValue < value) {
2617 mHighestLightSensorValue = value;
2618 }
2619
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002620 if (mLightSensorValue != value) {
2621 mLightSensorValue = value;
2622 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002623 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2624 // we only do this if we are undocked, since lighting should be stable when
2625 // stationary in a dock.
2626 int lcdValue = getAutoBrightnessValue(
2627 (mIsDocked ? value : mHighestLightSensorValue),
2628 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002629 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002630 int keyboardValue;
2631 if (mKeyboardVisible) {
2632 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2633 } else {
2634 keyboardValue = 0;
2635 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002636 mLightSensorScreenBrightness = lcdValue;
2637 mLightSensorButtonBrightness = buttonValue;
2638 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002639
2640 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002641 Slog.d(TAG, "lcdValue " + lcdValue);
2642 Slog.d(TAG, "buttonValue " + buttonValue);
2643 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002644 }
2645
Mike Lockwood4984e732009-11-01 08:16:33 -05002646 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Jim Miller92e66dd2012-02-21 18:57:12 -08002647 if (!mSkippedScreenOn && !mInitialAnimation) {
2648 int steps = immediate ? IMMEDIATE_ANIM_STEPS : AUTOBRIGHTNESS_ANIM_STEPS;
2649 mScreenBrightnessAnimator.cancelAnimation();
2650 mScreenBrightnessAnimator.animateTo(lcdValue,
2651 SCREEN_BRIGHT_BIT, steps * NOMINAL_FRAME_TIME_MS);
Dianne Hackborn81de8b92011-11-28 16:54:31 -08002652 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002653 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002654 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002655 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002656 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002657 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002658 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002659 }
2660 }
2661 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002662 }
2663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 /**
2665 * The user requested that we go to sleep (probably with the power button).
2666 * This overrides all wake locks that are held.
2667 */
2668 public void goToSleep(long time)
2669 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002670 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2671 }
2672
2673 /**
2674 * The user requested that we go to sleep (probably with the power button).
2675 * This overrides all wake locks that are held.
2676 */
2677 public void goToSleepWithReason(long time, int reason)
2678 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2680 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002681 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002686 * Reboot the device immediately, passing 'reason' (may be null)
2687 * to the underlying __reboot system call. Should not return.
2688 */
2689 public void reboot(String reason)
2690 {
2691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002692
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002693 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2694 throw new IllegalStateException("Too early to call reboot()");
2695 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002696
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002697 final String finalReason = reason;
2698 Runnable runnable = new Runnable() {
2699 public void run() {
2700 synchronized (this) {
2701 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002702 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002703
San Mehat1e512792010-01-07 10:40:29 -08002704 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002705 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002706 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002707 mHandler.post(runnable);
2708
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002709 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002710 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002711 while (true) {
2712 try {
2713 runnable.wait();
2714 } catch (InterruptedException e) {
2715 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002716 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002717 }
2718 }
2719
Dan Egnor60d87622009-12-16 16:32:58 -08002720 /**
2721 * Crash the runtime (causing a complete restart of the Android framework).
2722 * Requires REBOOT permission. Mostly for testing. Should not return.
2723 */
2724 public void crash(final String message)
2725 {
2726 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2727 Thread t = new Thread("PowerManagerService.crash()") {
2728 public void run() { throw new RuntimeException(message); }
2729 };
2730 try {
2731 t.start();
2732 t.join();
2733 } catch (InterruptedException e) {
2734 Log.wtf(TAG, e);
2735 }
2736 }
2737
Mike Lockwood435eb642009-12-03 08:40:18 -05002738 private void goToSleepLocked(long time, int reason) {
Jeff Browna75fe052012-05-01 18:41:26 -07002739 if (mSpew) {
2740 Exception ex = new Exception();
2741 ex.fillInStackTrace();
2742 Slog.d(TAG, "goToSleep mLastEventTime=" + mLastEventTime + " time=" + time
2743 + " reason=" + reason, ex);
2744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745
2746 if (mLastEventTime <= time) {
2747 mLastEventTime = time;
2748 // cancel all of the wake locks
2749 mWakeLockState = SCREEN_OFF;
2750 int N = mLocks.size();
2751 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002752 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 for (int i=0; i<N; i++) {
2754 WakeLock wl = mLocks.get(i);
2755 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002756 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2757 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2758 proxLock = true;
2759 } else {
2760 mLocks.get(i).activated = false;
2761 numCleared++;
2762 }
2763 }
2764 }
2765 if (!proxLock) {
2766 mProxIgnoredBecauseScreenTurnedOff = true;
2767 if (mDebugProximitySensor) {
2768 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002771 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002772 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002774 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 cancelTimerLocked();
2776 }
2777 }
2778
2779 public long timeSinceScreenOn() {
2780 synchronized (mLocks) {
2781 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2782 return 0;
2783 }
2784 return SystemClock.elapsedRealtime() - mScreenOffTime;
2785 }
2786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002789 synchronized (mLocks) {
2790 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002791 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002792 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002793 if (mKeyboardVisible != visible) {
2794 mKeyboardVisible = visible;
2795 // don't signal user activity if the screen is off; other code
2796 // will take care of turning on due to a true change to the lid
2797 // switch and synchronized with the lock screen.
2798 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002799 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002800 // force recompute of backlight values
2801 if (mLightSensorValue >= 0) {
2802 int value = (int)mLightSensorValue;
2803 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08002804 lightSensorChangedLocked(value, false);
Mike Lockwooddf024922009-10-29 21:29:15 -04002805 }
2806 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002807 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2808 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002809 }
2810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 }
2812
2813 /**
2814 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002815 * When disabling user activity we also reset user power state so the keyguard can reset its
2816 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 */
2818 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002819 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002820 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 synchronized (mLocks) {
2823 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002824 if (!enabled) {
2825 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2826 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 }
2829 }
2830
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002831 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002832 synchronized (mLocks) {
2833 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2834 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2835 mAutoBrightessEnabled = enabled;
2836 // This will get us a new value
2837 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002838 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002839 }
2840 }
2841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 /** Sets the screen off timeouts:
2843 * mKeylightDelay
2844 * mDimDelay
2845 * mScreenOffDelay
2846 * */
2847 private void setScreenOffTimeoutsLocked() {
2848 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002849 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 mDimDelay = -1;
2851 mScreenOffDelay = 0;
2852 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2853 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2854 mDimDelay = -1;
2855 mScreenOffDelay = 0;
2856 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002857 int totalDelay = mScreenOffTimeoutSetting;
2858 if (totalDelay > mMaximumScreenOffTimeout) {
2859 totalDelay = mMaximumScreenOffTimeout;
2860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2862 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002863 // negative number means stay on as long as possible.
2864 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 } else if (mKeylightDelay < totalDelay) {
2866 // subtract the time that the keylight delay. This will give us the
2867 // remainder of the time that we need to sleep to get the accurate
2868 // screen off timeout.
2869 mScreenOffDelay = totalDelay - mKeylightDelay;
2870 } else {
2871 mScreenOffDelay = 0;
2872 }
2873 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2874 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2875 mScreenOffDelay = LONG_DIM_TIME;
2876 } else {
2877 mDimDelay = -1;
2878 }
2879 }
2880 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002881 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2883 + " mDimScreen=" + mDimScreen);
2884 }
2885 }
2886
2887 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002888 * Refreshes cached secure settings. Called once on startup, and
2889 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 */
Doug Zongker43866e02010-01-07 12:09:54 -08002891 private void updateSettingsValues() {
2892 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002894 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002896 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898
2899 private class LockList extends ArrayList<WakeLock>
2900 {
2901 void addLock(WakeLock wl)
2902 {
2903 int index = getIndex(wl.binder);
2904 if (index < 0) {
2905 this.add(wl);
2906 }
2907 }
2908
2909 WakeLock removeLock(IBinder binder)
2910 {
2911 int index = getIndex(binder);
2912 if (index >= 0) {
2913 return this.remove(index);
2914 } else {
2915 return null;
2916 }
2917 }
2918
2919 int getIndex(IBinder binder)
2920 {
2921 int N = this.size();
2922 for (int i=0; i<N; i++) {
2923 if (this.get(i).binder == binder) {
2924 return i;
2925 }
2926 }
2927 return -1;
2928 }
2929
2930 int gatherState()
2931 {
2932 int result = 0;
2933 int N = this.size();
2934 for (int i=0; i<N; i++) {
2935 WakeLock wl = this.get(i);
2936 if (wl.activated) {
2937 if (isScreenLock(wl.flags)) {
2938 result |= wl.minState;
2939 }
2940 }
2941 }
2942 return result;
2943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002944
Michael Chane96440f2009-05-06 10:27:36 -07002945 int reactivateScreenLocksLocked()
2946 {
2947 int result = 0;
2948 int N = this.size();
2949 for (int i=0; i<N; i++) {
2950 WakeLock wl = this.get(i);
2951 if (isScreenLock(wl.flags)) {
2952 wl.activated = true;
2953 result |= wl.minState;
2954 }
2955 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002956 if (mDebugProximitySensor) {
2957 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2958 + mProxIgnoredBecauseScreenTurnedOff);
2959 }
2960 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002961 return result;
2962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 }
2964
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002965 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 synchronized (mLocks) {
2967 mPolicy = p;
2968 mLocks.notifyAll();
2969 }
2970 }
2971
2972 WindowManagerPolicy getPolicyLocked() {
2973 while (mPolicy == null || !mDoneBooting) {
2974 try {
2975 mLocks.wait();
2976 } catch (InterruptedException e) {
2977 // Ignore
2978 }
2979 }
2980 return mPolicy;
2981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 void systemReady() {
Jeff Brown25157e42012-04-16 12:13:05 -07002984 mSensorManager = new SystemSensorManager(mHandlerThread.getLooper());
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002985 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2986 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002987 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002988 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002989 }
2990
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002991 // wait until sensors are enabled before turning on screen.
2992 // some devices will not activate the light sensor properly on boot
2993 // unless we do this.
2994 if (mUseSoftwareAutoBrightness) {
2995 // turn the screen on
2996 setPowerState(SCREEN_BRIGHT);
2997 } else {
2998 // turn everything on
2999 setPowerState(ALL_BRIGHT);
3000 }
3001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003003 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05003005
Joe Onoratod28f7532010-11-06 12:56:53 -07003006 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
3007
Dianne Hackborn617f8772009-03-31 15:04:46 -07003008 long identity = Binder.clearCallingIdentity();
3009 try {
3010 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
3011 mBatteryStats.noteScreenOn();
3012 } catch (RemoteException e) {
3013 // Nothing interesting to do.
3014 } finally {
3015 Binder.restoreCallingIdentity(identity);
3016 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05003017 }
3018 }
3019
3020 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003021 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05003022 synchronized (mLocks) {
3023 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
3025 updateWakeLockLocked();
3026 mLocks.notifyAll();
3027 }
3028 }
3029
Joe Onoratob08a1af2010-10-11 19:28:58 -07003030 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 public void monitor() {
3032 synchronized (mLocks) { }
3033 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003034
3035 public int getSupportedWakeLockFlags() {
3036 int result = PowerManager.PARTIAL_WAKE_LOCK
3037 | PowerManager.FULL_WAKE_LOCK
3038 | PowerManager.SCREEN_DIM_WAKE_LOCK;
3039
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003040 if (mProximitySensor != null) {
3041 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
3042 }
3043
3044 return result;
3045 }
3046
Mike Lockwood237a2992009-09-15 14:42:16 -04003047 public void setBacklightBrightness(int brightness) {
3048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3049 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07003050 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04003051 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07003052 mLcdLight.setBrightness(brightness);
3053 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
3054 mButtonLight.setBrightness(brightness);
3055 long identity = Binder.clearCallingIdentity();
3056 try {
3057 mBatteryStats.noteScreenBrightness(brightness);
3058 } catch (RemoteException e) {
3059 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
3060 } finally {
3061 Binder.restoreCallingIdentity(identity);
3062 }
Jim Miller92e66dd2012-02-21 18:57:12 -08003063 mScreenBrightnessAnimator.animateTo(brightness, SCREEN_BRIGHT_BIT, 0);
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003064 }
3065 }
3066
3067 public void setAutoBrightnessAdjustment(float adj) {
3068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
3069 synchronized (mLocks) {
3070 mLightSensorAdjustSetting = adj;
3071 if (mSensorManager != null && mLightSensorEnabled) {
3072 // clear calling identity so sensor manager battery stats are accurate
3073 long identity = Binder.clearCallingIdentity();
3074 try {
3075 // force recompute of backlight values
3076 if (mLightSensorValue >= 0) {
3077 int value = (int)mLightSensorValue;
3078 mLightSensorValue = -1;
3079 handleLightSensorValue(value, true);
3080 }
3081 } finally {
3082 Binder.restoreCallingIdentity(identity);
3083 }
Joe Onorato3d3db602010-10-18 16:08:16 -04003084 }
Mike Lockwood237a2992009-09-15 14:42:16 -04003085 }
3086 }
3087
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003088 public void setAttentionLight(boolean on, int color) {
3089 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05003090 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05003091 }
3092
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003093 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003094 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003095 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003096 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003097 if (!mProximitySensorEnabled) {
3098 // clear calling identity so sensor manager battery stats are accurate
3099 long identity = Binder.clearCallingIdentity();
3100 try {
3101 mSensorManager.registerListener(mProximityListener, mProximitySensor,
3102 SensorManager.SENSOR_DELAY_NORMAL);
3103 mProximitySensorEnabled = true;
3104 } finally {
3105 Binder.restoreCallingIdentity(identity);
3106 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003107 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003108 }
3109
3110 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003111 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003112 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07003113 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003114 if (mProximitySensorEnabled) {
3115 // clear calling identity so sensor manager battery stats are accurate
3116 long identity = Binder.clearCallingIdentity();
3117 try {
3118 mSensorManager.unregisterListener(mProximityListener);
3119 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003120 if (mProximityPartialLock.isHeld()) {
3121 mProximityPartialLock.release();
3122 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003123 mProximitySensorEnabled = false;
3124 } finally {
3125 Binder.restoreCallingIdentity(identity);
3126 }
3127 if (mProximitySensorActive) {
3128 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003129 if (mDebugProximitySensor) {
3130 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
3131 + mProxIgnoredBecauseScreenTurnedOff);
3132 }
3133 if (!mProxIgnoredBecauseScreenTurnedOff) {
3134 forceUserActivityLocked();
3135 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003136 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04003137 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003138 }
3139
Mike Lockwood20f87d72009-11-05 16:08:51 -05003140 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003141 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003142 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05003143 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003144 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003145 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05003146 return;
3147 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003148 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04003149 if (mDebugProximitySensor) {
3150 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3151 + mProxIgnoredBecauseScreenTurnedOff);
3152 }
3153 if (!mProxIgnoredBecauseScreenTurnedOff) {
3154 goToSleepLocked(SystemClock.uptimeMillis(),
3155 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
3156 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003157 mProximitySensorActive = true;
3158 } else {
3159 // proximity sensor negative events trigger as user activity.
3160 // temporarily set mUserActivityAllowed to true so this will work
3161 // even when the keyguard is on.
3162 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003163 if (mDebugProximitySensor) {
3164 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3165 + mProxIgnoredBecauseScreenTurnedOff);
3166 }
3167 if (!mProxIgnoredBecauseScreenTurnedOff) {
3168 forceUserActivityLocked();
3169 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003170
3171 if (mProximityWakeLockCount == 0) {
3172 // disable sensor if we have no listeners left after proximity negative
3173 disableProximityLockLocked();
3174 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003175 }
3176 }
3177
Joe Onoratod28f7532010-11-06 12:56:53 -07003178 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003179 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003180 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3181 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3182 }
3183 if (!mAutoBrightessEnabled) {
3184 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003185 }
3186 if (mSensorManager != null && mLightSensorEnabled != enable) {
3187 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003188 // clear calling identity so sensor manager battery stats are accurate
3189 long identity = Binder.clearCallingIdentity();
3190 try {
3191 if (enable) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003192 // reset our highest value when reenabling
3193 mHighestLightSensorValue = -1;
3194 // force recompute of backlight values
3195 if (mLightSensorValue >= 0) {
3196 int value = (int)mLightSensorValue;
3197 mLightSensorValue = -1;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003198 handleLightSensorValue(value, true);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003199 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003200 mSensorManager.registerListener(mLightListener, mLightSensor,
Mathias Agopian47f1fe52011-11-08 17:18:41 -08003201 LIGHT_SENSOR_RATE);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003202 } else {
3203 mSensorManager.unregisterListener(mLightListener);
3204 mHandler.removeCallbacks(mAutoBrightnessTask);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003205 mLightSensorPendingDecrease = false;
3206 mLightSensorPendingIncrease = false;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003207 }
3208 } finally {
3209 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003210 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003211 }
3212 }
3213
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003214 SensorEventListener mProximityListener = new SensorEventListener() {
3215 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003216 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003217 synchronized (mLocks) {
3218 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003219 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3220 mLastProximityEventTime = milliseconds;
3221 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003222 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003223
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003224 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003225 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3226 distance < mProximitySensor.getMaximumRange());
3227
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003228 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003229 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003230 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003231 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3232 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3233 mProximityPendingValue = (active ? 1 : 0);
3234 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003235 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003236 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003237 // process the value immediately
3238 mProximityPendingValue = -1;
3239 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003240 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003241
3242 // update mProximityPartialLock state
3243 boolean held = mProximityPartialLock.isHeld();
3244 if (!held && proximityTaskQueued) {
3245 // hold wakelock until mProximityTask runs
3246 mProximityPartialLock.acquire();
3247 } else if (held && !proximityTaskQueued) {
3248 mProximityPartialLock.release();
3249 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003250 }
3251 }
3252
3253 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3254 // ignore
3255 }
3256 };
3257
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003258 private void handleLightSensorValue(int value, boolean immediate) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003259 long milliseconds = SystemClock.elapsedRealtime();
3260 if (mLightSensorValue == -1 ||
3261 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3262 // process the value immediately if screen has just turned on
3263 mHandler.removeCallbacks(mAutoBrightnessTask);
3264 mLightSensorPendingDecrease = false;
3265 mLightSensorPendingIncrease = false;
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003266 lightSensorChangedLocked(value, immediate);
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003267 } else {
3268 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3269 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3270 (value == mLightSensorValue) ||
3271 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3272 // delay processing to debounce the sensor
3273 mHandler.removeCallbacks(mAutoBrightnessTask);
3274 mLightSensorPendingDecrease = (value < mLightSensorValue);
3275 mLightSensorPendingIncrease = (value > mLightSensorValue);
3276 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3277 mLightSensorPendingValue = value;
3278 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3279 }
3280 } else {
3281 mLightSensorPendingValue = value;
3282 }
3283 }
3284 }
3285
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003286 SensorEventListener mLightListener = new SensorEventListener() {
3287 public void onSensorChanged(SensorEvent event) {
Mike Lockwood5dca30a2011-10-13 16:29:29 -04003288 if (mDebugLightSensor) {
3289 Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
3290 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003291 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003292 // ignore light sensor while screen is turning off
3293 if (isScreenTurningOffLocked()) {
3294 return;
3295 }
Dianne Hackbornd9ea4682012-01-20 18:36:40 -08003296 handleLightSensorValue((int)event.values[0], false);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003297 }
3298 }
3299
3300 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3301 // ignore
3302 }
3303 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304}