blob: 78dbbd6eb55535c55e9cf4816f6142212b808e7b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080020import com.android.internal.app.ShutdownThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import com.android.server.am.BatteryStatsService;
22
23import android.app.ActivityManagerNative;
24import android.app.IActivityManager;
25import android.content.BroadcastReceiver;
26import android.content.ContentQueryMap;
27import android.content.ContentResolver;
Amith Yamasani8b619832010-09-22 16:11:59 -070028import android.content.ContentValues;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070033import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.Cursor;
Mike Lockwoodbc706a02009-07-27 13:50:57 -070036import android.hardware.Sensor;
37import android.hardware.SensorEvent;
38import android.hardware.SensorEventListener;
39import android.hardware.SensorManager;
Amith Yamasani8b619832010-09-22 16:11:59 -070040import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.BatteryStats;
42import android.os.Binder;
43import android.os.Handler;
44import android.os.HandlerThread;
45import android.os.IBinder;
46import android.os.IPowerManager;
47import android.os.LocalPowerManager;
48import android.os.Power;
49import android.os.PowerManager;
50import android.os.Process;
51import android.os.RemoteException;
52import android.os.SystemClock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070053import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings.SettingNotFoundException;
55import android.provider.Settings;
56import android.util.EventLog;
57import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.view.WindowManagerPolicy;
60import static android.provider.Settings.System.DIM_SCREEN;
61import static android.provider.Settings.System.SCREEN_BRIGHTNESS;
Dan Murphy951764b2009-08-27 14:59:03 -050062import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE;
Mike Lockwooddc3494e2009-10-14 21:17:09 -070063import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
65import static android.provider.Settings.System.STAY_ON_WHILE_PLUGGED_IN;
Joe Onorato609695d2010-10-14 14:57:49 -070066import static android.provider.Settings.System.WINDOW_ANIMATION_SCALE;
67import static android.provider.Settings.System.TRANSITION_ANIMATION_SCALE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69import java.io.FileDescriptor;
70import java.io.PrintWriter;
71import java.util.ArrayList;
72import java.util.HashMap;
73import java.util.Observable;
74import java.util.Observer;
75
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080076public class PowerManagerService extends IPowerManager.Stub
Mike Lockwood8738e0c2009-10-04 08:44:47 -040077 implements LocalPowerManager, Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
79 private static final String TAG = "PowerManagerService";
80 static final String PARTIAL_NAME = "PowerManagerService";
81
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -070082 static final boolean DEBUG_SCREEN_ON = false;
83
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final boolean LOG_PARTIAL_WL = false;
85
86 // Indicates whether touch-down cycles should be logged as part of the
87 // LOG_POWER_SCREEN_STATE log events
88 private static final boolean LOG_TOUCH_DOWNS = true;
89
90 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
91 | PowerManager.SCREEN_DIM_WAKE_LOCK
92 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070093 | PowerManager.FULL_WAKE_LOCK
94 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
96 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080097 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
99 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
100 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
101 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
102
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700103 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500104 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700105
Mike Lockwood20f87d72009-11-05 16:08:51 -0500106 // For debouncing the proximity sensor.
107 private static final int PROXIMITY_SENSOR_DELAY = 1000;
108
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400109 // trigger proximity if distance is less than 5 cm
110 private static final float PROXIMITY_THRESHOLD = 5.0f;
111
Doug Zongker43866e02010-01-07 12:09:54 -0800112 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
114
Amith Yamasani8b619832010-09-22 16:11:59 -0700115 // Default timeout for screen off, if not found in settings database = 15 seconds.
116 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 // flags for setPowerState
119 private static final int SCREEN_ON_BIT = 0x00000001;
120 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
121 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
122 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
123 private static final int BATTERY_LOW_BIT = 0x00000010;
124
125 // values for setPowerState
126
127 // SCREEN_OFF == everything off
128 private static final int SCREEN_OFF = 0x00000000;
129
130 // SCREEN_DIM == screen on, screen backlight dim
131 private static final int SCREEN_DIM = SCREEN_ON_BIT;
132
133 // SCREEN_BRIGHT == screen on, screen backlight bright
134 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
135
136 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
137 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
138
139 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
140 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
141
142 // used for noChangeLights in setPowerState()
143 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
144
Joe Onoratob08a1af2010-10-11 19:28:58 -0700145 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400148 // Slower animation for autobrightness changes
149 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151 // These magic numbers are the initial state of the LEDs at boot. Ideally
152 // we should read them from the driver, but our current hardware returns 0
153 // for the initial value. Oops!
154 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
155 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
156 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700159 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500162 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500164 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
165 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn38e29a62011-09-18 14:43:08 -0700166 private boolean mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700167 private boolean mSkippedScreenOn = false;
168 private boolean mInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 private int mPartialCount = 0;
170 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500171 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
172 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
173 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 private int mUserState;
175 private boolean mKeyboardVisible = false;
176 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500177 private int mProximityWakeLockCount = 0;
178 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700179 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500180 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
181 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800182 private int mScreenOffTimeoutSetting;
183 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 private int mKeylightDelay;
185 private int mDimDelay;
186 private int mScreenOffDelay;
187 private int mWakeLockState;
188 private long mLastEventTime = 0;
189 private long mScreenOffTime;
190 private volatile WindowManagerPolicy mPolicy;
191 private final LockList mLocks = new LockList();
192 private Intent mScreenOffIntent;
193 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500194 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500196 private LightsService.Light mLcdLight;
197 private LightsService.Light mButtonLight;
198 private LightsService.Light mKeyboardLight;
199 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 private UnsynchronizedWakeLock mBroadcastWakeLock;
201 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
202 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
203 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500204 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700206 private HandlerThread mScreenOffThread;
207 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500209 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700211 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700212 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 private boolean mIsPowered = false;
214 private IActivityManager mActivityService;
215 private IBatteryStats mBatteryStats;
216 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700217 private SensorManager mSensorManager;
218 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400219 private Sensor mLightSensor;
220 private boolean mLightSensorEnabled;
221 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400222 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500223 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500224 private boolean mLightSensorPendingDecrease = false;
225 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700226 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500227 private int mLightSensorScreenBrightness = -1;
228 private int mLightSensorButtonBrightness = -1;
229 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500231 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 private long mNextTimeout;
233 private volatile int mPokey = 0;
234 private volatile boolean mPokeAwakeOnSet = false;
235 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500236 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500237 // mLastScreenOnTime is the time the screen was last turned on
238 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 private boolean mPreventScreenOn;
240 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500241 private int mButtonBrightnessOverride = -1;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400242 private int mScreenBrightnessDim;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400243 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700244 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700245 private int[] mAutoBrightnessLevels;
246 private int[] mLcdBacklightValues;
247 private int[] mButtonBacklightValues;
248 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500249 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700250 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700251 private int mWarningSpewThrottleCount;
252 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700253 private int mAnimationSetting = ANIM_SETTING_OFF;
254
255 // Must match with the ISurfaceComposer constants in C++.
256 private static final int ANIM_SETTING_ON = 0x01;
257 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
259 // Used when logging number and duration of touch-down cycles
260 private long mTotalTouchDownTime;
261 private long mLastTouchDown;
262 private int mTouchCycles;
263
264 // could be either static or controllable at runtime
265 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400266 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400267 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700268
269 private native void nativeInit();
270 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700271 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272
273 /*
274 static PrintStream mLog;
275 static {
276 try {
277 mLog = new PrintStream("/data/power.log");
278 }
279 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800280 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 }
282 }
283 static class Log {
284 static void d(String tag, String s) {
285 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800286 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 }
288 static void i(String tag, String s) {
289 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800290 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292 static void w(String tag, String s) {
293 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800294 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 }
296 static void e(String tag, String s) {
297 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800298 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300 }
301 */
302
303 /**
304 * This class works around a deadlock between the lock in PowerManager.WakeLock
305 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
306 * mToken object so it can be accessed from any thread, but it calls into here
307 * with its lock held. This class is essentially a reimplementation of
308 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
309 * only call it with our own locks held.
310 */
311 private class UnsynchronizedWakeLock {
312 int mFlags;
313 String mTag;
314 IBinder mToken;
315 int mCount = 0;
316 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500317 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318
319 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
320 mFlags = flags;
321 mTag = tag;
322 mToken = new Binder();
323 mRefCounted = refCounted;
324 }
325
326 public void acquire() {
327 if (!mRefCounted || mCount++ == 0) {
328 long ident = Binder.clearCallingIdentity();
329 try {
330 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700331 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500332 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 } finally {
334 Binder.restoreCallingIdentity(ident);
335 }
336 }
337 }
338
339 public void release() {
340 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500341 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500342 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344 if (mCount < 0) {
345 throw new RuntimeException("WakeLock under-locked " + mTag);
346 }
347 }
348
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500349 public boolean isHeld()
350 {
351 return mHeld;
352 }
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 public String toString() {
355 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500356 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 }
358 }
359
360 private final class BatteryReceiver extends BroadcastReceiver {
361 @Override
362 public void onReceive(Context context, Intent intent) {
363 synchronized (mLocks) {
364 boolean wasPowered = mIsPowered;
365 mIsPowered = mBatteryService.isPowered();
366
367 if (mIsPowered != wasPowered) {
368 // update mStayOnWhilePluggedIn wake lock
369 updateWakeLockLocked();
370
371 // treat plugging and unplugging the devices as a user activity.
372 // users find it disconcerting when they unplug the device
373 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500374 // to avoid turning on the screen when unplugging, we only trigger
375 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 // temporarily set mUserActivityAllowed to true so this will work
377 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700378 // However, you can also set config_unplugTurnsOnScreen to have it
379 // turn on. Some devices want this because they don't have a
380 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700382 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
383 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500384 forceUserActivityLocked();
385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 }
387 }
388 }
389 }
390 }
391
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500392 private final class BootCompletedReceiver extends BroadcastReceiver {
393 @Override
394 public void onReceive(Context context, Intent intent) {
395 bootCompleted();
396 }
397 }
398
Mike Lockwoodb2865412010-02-02 22:40:33 -0500399 private final class DockReceiver extends BroadcastReceiver {
400 @Override
401 public void onReceive(Context context, Intent intent) {
402 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
403 Intent.EXTRA_DOCK_STATE_UNDOCKED);
404 dockStateChanged(state);
405 }
406 }
407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 /**
409 * Set the setting that determines whether the device stays on when plugged in.
410 * The argument is a bit string, with each bit specifying a power source that,
411 * when the device is connected to that source, causes the device to stay on.
412 * See {@link android.os.BatteryManager} for the list of power sources that
413 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
414 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
415 * @param val an {@code int} containing the bits that specify which power sources
416 * should cause the device to stay on.
417 */
418 public void setStayOnSetting(int val) {
419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
420 Settings.System.putInt(mContext.getContentResolver(),
421 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
422 }
423
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800424 public void setMaximumScreenOffTimeount(int timeMs) {
425 mContext.enforceCallingOrSelfPermission(
426 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
427 synchronized (mLocks) {
428 mMaximumScreenOffTimeout = timeMs;
429 // recalculate everything
430 setScreenOffTimeoutsLocked();
431 }
432 }
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700435 private int getInt(String name, int defValue) {
436 ContentValues values = mSettings.getValues(name);
437 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
438 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 }
440
Joe Onorato609695d2010-10-14 14:57:49 -0700441 private float getFloat(String name, float defValue) {
442 ContentValues values = mSettings.getValues(name);
443 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
444 return fVal != null ? fVal : defValue;
445 }
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 public void update(Observable o, Object arg) {
448 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700449 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
450 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
451 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 updateWakeLockLocked();
453
Amith Yamasani8b619832010-09-22 16:11:59 -0700454 // SCREEN_OFF_TIMEOUT, default to 15 seconds
455 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456
Joe Onorato609695d2010-10-14 14:57:49 -0700457 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 //mDimScreen = getInt(DIM_SCREEN) != 0;
459
Amith Yamasani8b619832010-09-22 16:11:59 -0700460 // SCREEN_BRIGHTNESS_MODE, default to manual
461 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
462 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 // recalculate everything
465 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700466
467 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
468 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
469 mAnimationSetting = 0;
470 if (windowScale > 0.5f) {
471 mAnimationSetting |= ANIM_SETTING_OFF;
472 }
473 if (transitionScale > 0.5f) {
474 // Uncomment this if you want the screen-on animation.
475 // mAnimationSetting |= ANIM_SETTING_ON;
476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478 }
479 }
480
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700481 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 // Hack to get our uid... should have a func for this.
483 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700484 MY_UID = Process.myUid();
485 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 Binder.restoreCallingIdentity(token);
487
488 // XXX remove this when the kernel doesn't timeout wake locks
489 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
490
491 // assume nothing is on yet
492 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 // Add ourself to the Watchdog monitors.
495 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
497
498 private ContentQueryMap mSettings;
499
Mike Lockwood3a322132009-11-24 00:30:52 -0500500 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700501 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500502 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 mContext = context;
504 mActivityService = activity;
505 mBatteryStats = BatteryStatsService.getService();
506 mBatteryService = battery;
507
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500508 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
509 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
510 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
511 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
512
Joe Onoratob08a1af2010-10-11 19:28:58 -0700513 nativeInit();
514 synchronized (mLocks) {
515 updateNativePowerStateLocked();
516 }
517
518 mInitComplete = false;
519 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
520 @Override
521 protected void onLooperPrepared() {
522 mScreenOffHandler = new Handler();
523 synchronized (mScreenOffThread) {
524 mInitComplete = true;
525 mScreenOffThread.notifyAll();
526 }
527 }
528 };
529 mScreenOffThread.start();
530
531 synchronized (mScreenOffThread) {
532 while (!mInitComplete) {
533 try {
534 mScreenOffThread.wait();
535 } catch (InterruptedException e) {
536 // Ignore
537 }
538 }
539 }
540
541 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 mHandlerThread = new HandlerThread("PowerManagerService") {
543 @Override
544 protected void onLooperPrepared() {
545 super.onLooperPrepared();
546 initInThread();
547 }
548 };
549 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 synchronized (mHandlerThread) {
552 while (!mInitComplete) {
553 try {
554 mHandlerThread.wait();
555 } catch (InterruptedException e) {
556 // Ignore
557 }
558 }
559 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700560
561 nativeInit();
562 synchronized (mLocks) {
563 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -0700564 // We make sure to start out with the screen on due to user activity.
565 // (They did just boot their device, after all.)
566 forceUserActivityLocked();
Dianne Hackborn40011092011-09-22 13:37:48 -0700567 mInitialized = true;
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 void initInThread() {
572 mHandler = new Handler();
573
574 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700575 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
577 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
578 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
579 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
580 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
581 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500582 mProximityPartialLock = new UnsynchronizedWakeLock(
583 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
586 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
587 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
588 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
589
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700590 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400591
Joe Onoratob08a1af2010-10-11 19:28:58 -0700592 mAnimateScreenLights = resources.getBoolean(
593 com.android.internal.R.bool.config_animateScreenLights);
594
Joe Onorato6d747652010-10-11 15:15:31 -0700595 mUnplugTurnsOnScreen = resources.getBoolean(
596 com.android.internal.R.bool.config_unplugTurnsOnScreen);
597
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400598 mScreenBrightnessDim = resources.getInteger(
599 com.android.internal.R.integer.config_screenBrightnessDim);
600
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400601 // read settings for auto-brightness
602 mUseSoftwareAutoBrightness = resources.getBoolean(
603 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400604 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700605 mAutoBrightnessLevels = resources.getIntArray(
606 com.android.internal.R.array.config_autoBrightnessLevels);
607 mLcdBacklightValues = resources.getIntArray(
608 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
609 mButtonBacklightValues = resources.getIntArray(
610 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
611 mKeyboardBacklightValues = resources.getIntArray(
612 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500613 mLightSensorWarmupTime = resources.getInteger(
614 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700615 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700616
617 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
619 "(" + Settings.System.NAME + "=?) or ("
620 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700621 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700622 + Settings.System.NAME + "=?) or ("
623 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700625 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700626 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 null);
628 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
629 SettingsObserver settingsObserver = new SettingsObserver();
630 mSettings.addObserver(settingsObserver);
631
632 // pretend that the settings changed so we will get their initial state
633 settingsObserver.update(mSettings, null);
634
635 // register for the battery changed notifications
636 IntentFilter filter = new IntentFilter();
637 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
638 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500639 filter = new IntentFilter();
640 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
641 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500642 filter = new IntentFilter();
643 filter.addAction(Intent.ACTION_DOCK_EVENT);
644 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645
Doug Zongker43866e02010-01-07 12:09:54 -0800646 // Listen for secure settings changes
647 mContext.getContentResolver().registerContentObserver(
648 Settings.Secure.CONTENT_URI, true,
649 new ContentObserver(new Handler()) {
650 public void onChange(boolean selfChange) {
651 updateSettingsValues();
652 }
653 });
654 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 synchronized (mHandlerThread) {
657 mInitComplete = true;
658 mHandlerThread.notifyAll();
659 }
660 }
661
662 private class WakeLock implements IBinder.DeathRecipient
663 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700664 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 super();
666 flags = f;
667 binder = b;
668 tag = t;
669 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700670 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 if (u != MY_UID || (
672 !"KEEP_SCREEN_ON_FLAG".equals(tag)
673 && !"KeyInputQueue".equals(tag))) {
674 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
675 ? BatteryStats.WAKE_TYPE_PARTIAL
676 : BatteryStats.WAKE_TYPE_FULL;
677 } else {
678 monitorType = -1;
679 }
680 try {
681 b.linkToDeath(this, 0);
682 } catch (RemoteException e) {
683 binderDied();
684 }
685 }
686 public void binderDied() {
687 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500688 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 }
690 }
691 final int flags;
692 final IBinder binder;
693 final String tag;
694 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400695 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700697 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 boolean activated = true;
699 int minState;
700 }
701
702 private void updateWakeLockLocked() {
703 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
704 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
705 mStayOnWhilePluggedInScreenDimLock.acquire();
706 mStayOnWhilePluggedInPartialLock.acquire();
707 } else {
708 mStayOnWhilePluggedInScreenDimLock.release();
709 mStayOnWhilePluggedInPartialLock.release();
710 }
711 }
712
713 private boolean isScreenLock(int flags)
714 {
715 int n = flags & LOCK_MASK;
716 return n == PowerManager.FULL_WAKE_LOCK
717 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400718 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
719 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700722 void enforceWakeSourcePermission(int uid, int pid) {
723 if (uid == Process.myUid()) {
724 return;
725 }
726 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
727 pid, uid, null);
728 }
729
730 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700732 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700733 if (uid != Process.myUid()) {
734 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
735 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700736 if (ws != null) {
737 enforceWakeSourcePermission(uid, pid);
738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 long ident = Binder.clearCallingIdentity();
740 try {
741 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700742 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744 } finally {
745 Binder.restoreCallingIdentity(ident);
746 }
747 }
748
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700749 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700750 if (wl.monitorType >= 0) {
751 long origId = Binder.clearCallingIdentity();
752 try {
753 if (ws != null) {
754 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
755 wl.monitorType);
756 } else {
757 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
758 }
759 } catch (RemoteException e) {
760 // Ignore
761 } finally {
762 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700763 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700764 }
765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700767 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700768 if (wl.monitorType >= 0) {
769 long origId = Binder.clearCallingIdentity();
770 try {
771 if (ws != null) {
772 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
773 wl.monitorType);
774 } else {
775 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
776 }
777 } catch (RemoteException e) {
778 // Ignore
779 } finally {
780 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700781 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700782 }
783 }
784
785 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
786 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800788 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 }
790
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700791 if (ws != null && ws.size() == 0) {
792 ws = null;
793 }
794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 int index = mLocks.getIndex(lock);
796 WakeLock wl;
797 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700798 boolean diffsource;
799 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700801 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 switch (wl.flags & LOCK_MASK)
803 {
804 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500805 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400806 wl.minState = SCREEN_BRIGHT;
807 } else {
808 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 break;
811 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
812 wl.minState = SCREEN_BRIGHT;
813 break;
814 case PowerManager.SCREEN_DIM_WAKE_LOCK:
815 wl.minState = SCREEN_DIM;
816 break;
817 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700818 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 break;
820 default:
821 // just log and bail. we're in the server, so don't
822 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 + " flags=" + flags);
825 return;
826 }
827 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700828 if (ws != null) {
829 wl.ws = new WorkSource(ws);
830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700832 diffsource = false;
833 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 } else {
835 wl = mLocks.get(index);
836 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700837 oldsource = wl.ws;
838 if (oldsource != null) {
839 if (ws == null) {
840 wl.ws = null;
841 diffsource = true;
842 } else {
843 diffsource = oldsource.diff(ws);
844 }
845 } else if (ws != null) {
846 diffsource = true;
847 } else {
848 diffsource = false;
849 }
850 if (diffsource) {
851 wl.ws = new WorkSource(ws);
852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 if (isScreenLock(flags)) {
855 // if this causes a wakeup, we reactivate all of the locks and
856 // set it to whatever they want. otherwise, we modulate that
857 // by the current state so we never turn it more on than
858 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400859 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
860 mProximityWakeLockCount++;
861 if (mProximityWakeLockCount == 1) {
862 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400865 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
866 int oldWakeLockState = mWakeLockState;
867 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400868
869 // Disable proximity sensor if if user presses power key while we are in the
870 // "waiting for proximity sensor to go negative" state.
871 if ((mWakeLockState & SCREEN_ON_BIT) != 0
872 && mProximitySensorActive && mProximityWakeLockCount == 0) {
873 mProximitySensorActive = false;
874 }
875
Joe Onorato8274a0e2010-10-05 17:38:09 -0400876 if (mSpew) {
877 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
878 + " mWakeLockState=0x"
879 + Integer.toHexString(mWakeLockState)
880 + " previous wakeLockState=0x"
881 + Integer.toHexString(oldWakeLockState));
882 }
883 } else {
884 if (mSpew) {
885 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
886 + " mLocks.gatherState()=0x"
887 + Integer.toHexString(mLocks.gatherState())
888 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
889 }
890 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400892 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
896 if (newlock) {
897 mPartialCount++;
898 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800899 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 }
901 }
902 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700905 if (diffsource) {
906 // If the lock sources have changed, need to first release the
907 // old ones.
908 noteStopWakeLocked(wl, oldsource);
909 }
910 if (newlock || diffsource) {
911 noteStartWakeLocked(wl, ws);
912 }
913 }
914
915 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
916 int uid = Binder.getCallingUid();
917 int pid = Binder.getCallingPid();
918 if (ws != null && ws.size() == 0) {
919 ws = null;
920 }
921 if (ws != null) {
922 enforceWakeSourcePermission(uid, pid);
923 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700924 synchronized (mLocks) {
925 int index = mLocks.getIndex(lock);
926 if (index < 0) {
927 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700929 WakeLock wl = mLocks.get(index);
930 WorkSource oldsource = wl.ws;
931 wl.ws = ws != null ? new WorkSource(ws) : null;
932 noteStopWakeLocked(wl, oldsource);
933 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935 }
936
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500937 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700938 int uid = Binder.getCallingUid();
939 if (uid != Process.myUid()) {
940 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942
943 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500944 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
946 }
947
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500948 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 WakeLock wl = mLocks.removeLock(lock);
950 if (wl == null) {
951 return;
952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800955 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
957 }
958
959 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400960 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
961 mProximityWakeLockCount--;
962 if (mProximityWakeLockCount == 0) {
963 if (mProximitySensorActive &&
964 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
965 // wait for proximity sensor to go negative before disabling sensor
966 if (mDebugProximitySensor) {
967 Slog.d(TAG, "waiting for proximity sensor to go negative");
968 }
969 } else {
970 disableProximityLockLocked();
971 }
972 }
973 } else {
974 mWakeLockState = mLocks.gatherState();
975 // goes in the middle to reduce flicker
976 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
977 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
978 }
979 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
982 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
983 mPartialCount--;
984 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 Power.releaseWakeLock(PARTIAL_NAME);
987 }
988 }
989 // Unlink the lock from the binder.
990 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991
Dianne Hackborn70be1672010-09-14 11:13:03 -0700992 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 private class PokeLock implements IBinder.DeathRecipient
996 {
997 PokeLock(int p, IBinder b, String t) {
998 super();
999 this.pokey = p;
1000 this.binder = b;
1001 this.tag = t;
1002 try {
1003 b.linkToDeath(this, 0);
1004 } catch (RemoteException e) {
1005 binderDied();
1006 }
1007 }
1008 public void binderDied() {
1009 setPokeLock(0, this.binder, this.tag);
1010 }
1011 int pokey;
1012 IBinder binder;
1013 String tag;
1014 boolean awakeOnSet;
1015 }
1016
1017 public void setPokeLock(int pokey, IBinder token, String tag) {
1018 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1019 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001020 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 return;
1022 }
1023
1024 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1025 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1026 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1027 }
1028
1029 synchronized (mLocks) {
1030 if (pokey != 0) {
1031 PokeLock p = mPokeLocks.get(token);
1032 int oldPokey = 0;
1033 if (p != null) {
1034 oldPokey = p.pokey;
1035 p.pokey = pokey;
1036 } else {
1037 p = new PokeLock(pokey, token, tag);
1038 mPokeLocks.put(token, p);
1039 }
1040 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1041 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1042 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1043 p.awakeOnSet = true;
1044 }
1045 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001046 PokeLock rLock = mPokeLocks.remove(token);
1047 if (rLock != null) {
1048 token.unlinkToDeath(rLock, 0);
1049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051
1052 int oldPokey = mPokey;
1053 int cumulative = 0;
1054 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1055 boolean awakeOnSet = false;
1056 for (PokeLock p: mPokeLocks.values()) {
1057 cumulative |= p.pokey;
1058 if (p.awakeOnSet) {
1059 awakeOnSet = true;
1060 }
1061 }
1062 mPokey = cumulative;
1063 mPokeAwakeOnSet = awakeOnSet;
1064
1065 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1066 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if (oldCumulativeTimeout != newCumulativeTimeout) {
1069 setScreenOffTimeoutsLocked();
1070 // reset the countdown timer, but use the existing nextState so it doesn't
1071 // change anything
1072 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1073 }
1074 }
1075 }
1076
1077 private static String lockType(int type)
1078 {
1079 switch (type)
1080 {
1081 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001082 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001084 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001086 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001088 return "PARTIAL_WAKE_LOCK ";
1089 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1090 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 default:
David Brown251faa62009-08-02 22:04:36 -07001092 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094 }
1095
1096 private static String dumpPowerState(int state) {
1097 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1098 ? "KEYBOARD_BRIGHT_BIT " : "")
1099 + (((state & SCREEN_BRIGHT_BIT) != 0)
1100 ? "SCREEN_BRIGHT_BIT " : "")
1101 + (((state & SCREEN_ON_BIT) != 0)
1102 ? "SCREEN_ON_BIT " : "")
1103 + (((state & BATTERY_LOW_BIT) != 0)
1104 ? "BATTERY_LOW_BIT " : "");
1105 }
1106
1107 @Override
1108 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1109 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1110 != PackageManager.PERMISSION_GRANTED) {
1111 pw.println("Permission Denial: can't dump PowerManager from from pid="
1112 + Binder.getCallingPid()
1113 + ", uid=" + Binder.getCallingUid());
1114 return;
1115 }
1116
1117 long now = SystemClock.uptimeMillis();
1118
Mike Lockwoodca44df82010-02-25 13:48:49 -05001119 synchronized (mLocks) {
1120 pw.println("Power Manager State:");
1121 pw.println(" mIsPowered=" + mIsPowered
1122 + " mPowerState=" + mPowerState
1123 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1124 + " ms");
1125 pw.println(" mPartialCount=" + mPartialCount);
1126 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1127 pw.println(" mUserState=" + dumpPowerState(mUserState));
1128 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1129 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1130 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1131 + " " + ((mNextTimeout-now)/1000) + "s from now");
1132 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001133 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001134 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1135 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001136 pw.println(" mScreenOffReason=" + mScreenOffReason
1137 + " mUserState=" + mUserState);
1138 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1139 + ',' + mBroadcastQueue[2] + "}");
1140 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1141 + ',' + mBroadcastWhy[2] + "}");
1142 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1143 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1144 + " mUserActivityAllowed=" + mUserActivityAllowed);
1145 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1146 + " mScreenOffDelay=" + mScreenOffDelay);
1147 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1148 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1149 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1150 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1151 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1152 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1153 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1154 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1155 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1156 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1157 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1158 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1159 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1160 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1161 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1162 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1163 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1164 pw.println(" mLightSensorValue=" + mLightSensorValue
1165 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001166 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1167 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001168 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1169 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1170 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1171 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1172 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1173 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001174
Mike Lockwoodca44df82010-02-25 13:48:49 -05001175 int N = mLocks.size();
1176 pw.println();
1177 pw.println("mLocks.size=" + N + ":");
1178 for (int i=0; i<N; i++) {
1179 WakeLock wl = mLocks.get(i);
1180 String type = lockType(wl.flags & LOCK_MASK);
1181 String acquireCausesWakeup = "";
1182 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1183 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1184 }
1185 String activated = "";
1186 if (wl.activated) {
1187 activated = " activated";
1188 }
1189 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001190 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1191 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001193
1194 pw.println();
1195 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1196 for (PokeLock p: mPokeLocks.values()) {
1197 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001198 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1199 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001200 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1201 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1202 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1203 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001205
Mike Lockwoodca44df82010-02-25 13:48:49 -05001206 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Joe Onorato7999bff2010-07-24 11:50:05 -04001210 private void setTimeoutLocked(long now, int nextState) {
1211 setTimeoutLocked(now, -1, nextState);
1212 }
1213
1214 // If they gave a timeoutOverride it is the number of seconds
1215 // to screen-off. Figure out where in the countdown cycle we
1216 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001217 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1218 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001219 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001220 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001221 long when = 0;
1222 if (timeoutOverride <= 0) {
1223 switch (nextState)
1224 {
1225 case SCREEN_BRIGHT:
1226 when = now + mKeylightDelay;
1227 break;
1228 case SCREEN_DIM:
1229 if (mDimDelay >= 0) {
1230 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001231 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001232 } else {
1233 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1234 }
1235 case SCREEN_OFF:
1236 synchronized (mLocks) {
1237 when = now + mScreenOffDelay;
1238 }
1239 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001240 default:
1241 when = now;
1242 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001244 } else {
1245 override: {
1246 if (timeoutOverride <= mScreenOffDelay) {
1247 when = now + timeoutOverride;
1248 nextState = SCREEN_OFF;
1249 break override;
1250 }
1251 timeoutOverride -= mScreenOffDelay;
1252
1253 if (mDimDelay >= 0) {
1254 if (timeoutOverride <= mDimDelay) {
1255 when = now + timeoutOverride;
1256 nextState = SCREEN_DIM;
1257 break override;
1258 }
1259 timeoutOverride -= mDimDelay;
1260 }
1261
1262 when = now + timeoutOverride;
1263 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001265 }
1266 if (mSpew) {
1267 Slog.d(TAG, "setTimeoutLocked now=" + now
1268 + " timeoutOverride=" + timeoutOverride
1269 + " nextState=" + nextState + " when=" + when);
1270 }
Joe Onorato797e6882010-08-26 14:46:01 -04001271
1272 mHandler.removeCallbacks(mTimeoutTask);
1273 mTimeoutTask.nextState = nextState;
1274 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1275 ? (originalTimeoutOverride - timeoutOverride)
1276 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001277 mHandler.postAtTime(mTimeoutTask, when);
1278 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 }
1282
1283 private void cancelTimerLocked()
1284 {
1285 mHandler.removeCallbacks(mTimeoutTask);
1286 mTimeoutTask.nextState = -1;
1287 }
1288
1289 private class TimeoutTask implements Runnable
1290 {
1291 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001292 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 public void run()
1294 {
1295 synchronized (mLocks) {
1296 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001297 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
1299
1300 if (nextState == -1) {
1301 return;
1302 }
1303
1304 mUserState = this.nextState;
1305 setPowerState(this.nextState | mWakeLockState);
1306
1307 long now = SystemClock.uptimeMillis();
1308
1309 switch (this.nextState)
1310 {
1311 case SCREEN_BRIGHT:
1312 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001313 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 break;
1315 }
1316 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001317 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 break;
1319 }
1320 }
1321 }
1322 }
1323
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001324 private void sendNotificationLocked(boolean on, int why) {
1325 if (!mInitialized) {
1326 // No notifications sent until first initialization is done.
1327 // This is so that when we are moving from our initial state
1328 // which looks like the screen was off to it being on, we do not
1329 // go through the process of waiting for the higher-level user
1330 // space to be ready before turning up the display brightness.
1331 // (And also do not send needless broadcasts about the screen.)
1332 return;
1333 }
Dianne Hackborn40011092011-09-22 13:37:48 -07001334
1335 if (DEBUG_SCREEN_ON) {
1336 RuntimeException here = new RuntimeException("here");
1337 here.fillInStackTrace();
1338 Slog.i(TAG, "sendNotificationLocked: " + on, here);
1339 }
1340
Joe Onorato64c62ba2009-03-24 20:13:57 -07001341 if (!on) {
1342 mStillNeedSleepNotification = false;
1343 }
1344
Joe Onorato128e7292009-03-24 18:41:31 -07001345 // Add to the queue.
1346 int index = 0;
1347 while (mBroadcastQueue[index] != -1) {
1348 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
Joe Onorato128e7292009-03-24 18:41:31 -07001350 mBroadcastQueue[index] = on ? 1 : 0;
1351 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352
Joe Onorato128e7292009-03-24 18:41:31 -07001353 // If we added it position 2, then there is a pair that can be stripped.
1354 // If we added it position 1 and we're turning the screen off, we can strip
1355 // the pair and do nothing, because the screen is already off, and therefore
1356 // keyguard has already been enabled.
1357 // However, if we added it at position 1 and we're turning it on, then position
1358 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1359 // on, so have to run the queue then.
1360 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001361 // While we're collapsing them, if it's going off, and the new reason
1362 // is more significant than the first, then use the new one.
1363 if (!on && mBroadcastWhy[0] > why) {
1364 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001365 }
1366 mBroadcastQueue[0] = on ? 1 : 0;
1367 mBroadcastQueue[1] = -1;
1368 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001369 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001370 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001371 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001372 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001373 index = 0;
1374 }
1375 if (index == 1 && !on) {
1376 mBroadcastQueue[0] = -1;
1377 mBroadcastQueue[1] = -1;
1378 index = -1;
1379 // The wake lock was being held, but we're not actually going to do any
1380 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001381 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001383 }
1384
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001385 // The broadcast queue has changed; make sure the screen is on if it
1386 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001387 if (mSkippedScreenOn) {
1388 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1389 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001390
Joe Onorato128e7292009-03-24 18:41:31 -07001391 // Now send the message.
1392 if (index >= 0) {
1393 // Acquire the broadcast wake lock before changing the power
1394 // state. It will be release after the broadcast is sent.
1395 // We always increment the ref count for each notification in the queue
1396 // and always decrement when that notification is handled.
1397 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001398 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001399 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 }
1402
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001403 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1404 new WindowManagerPolicy.ScreenOnListener() {
1405 @Override public void onScreenOn() {
1406 synchronized (mLocks) {
1407 if (mPreparingForScreenOn) {
1408 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001409 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001410 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1411 4, mBroadcastWakeLock.mCount);
1412 mBroadcastWakeLock.release();
1413 }
1414 }
1415 }
1416 };
1417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 private Runnable mNotificationTask = new Runnable()
1419 {
1420 public void run()
1421 {
Joe Onorato128e7292009-03-24 18:41:31 -07001422 while (true) {
1423 int value;
1424 int why;
1425 WindowManagerPolicy policy;
1426 synchronized (mLocks) {
1427 value = mBroadcastQueue[0];
1428 why = mBroadcastWhy[0];
1429 for (int i=0; i<2; i++) {
1430 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1431 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1432 }
1433 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001434 if (value == 1 && !mPreparingForScreenOn) {
1435 mPreparingForScreenOn = true;
1436 mBroadcastWakeLock.acquire();
1437 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1438 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
Joe Onorato128e7292009-03-24 18:41:31 -07001441 if (value == 1) {
1442 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001444 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001445 try {
1446 ActivityManagerNative.getDefault().wakingUp();
1447 } catch (RemoteException e) {
1448 // ignore it
1449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450
Joe Onorato128e7292009-03-24 18:41:31 -07001451 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001452 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001453 }
1454 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1455 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1456 mScreenOnBroadcastDone, mHandler, 0, null, null);
1457 } else {
1458 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001459 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001460 mBroadcastWakeLock.mCount);
1461 mBroadcastWakeLock.release();
1462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464 }
Joe Onorato128e7292009-03-24 18:41:31 -07001465 else if (value == 0) {
1466 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001467
Joe Onorato128e7292009-03-24 18:41:31 -07001468 policy.screenTurnedOff(why);
1469 try {
1470 ActivityManagerNative.getDefault().goingToSleep();
1471 } catch (RemoteException e) {
1472 // ignore it.
1473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
Joe Onorato128e7292009-03-24 18:41:31 -07001475 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1476 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1477 mScreenOffBroadcastDone, mHandler, 0, null, null);
1478 } else {
1479 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001481 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001482 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001483 mBroadcastWakeLock.release();
1484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
1486 }
Joe Onorato128e7292009-03-24 18:41:31 -07001487 else {
1488 // If we're in this case, then this handler is running for a previous
1489 // paired transaction. mBroadcastWakeLock will already have been released.
1490 break;
1491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 }
1494 };
1495
1496 long mScreenOnStart;
1497 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1498 public void onReceive(Context context, Intent intent) {
1499 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001500 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1502 mBroadcastWakeLock.release();
1503 }
1504 }
1505 };
1506
1507 long mScreenOffStart;
1508 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1509 public void onReceive(Context context, Intent intent) {
1510 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001511 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1513 mBroadcastWakeLock.release();
1514 }
1515 }
1516 };
1517
1518 void logPointerUpEvent() {
1519 if (LOG_TOUCH_DOWNS) {
1520 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1521 mLastTouchDown = 0;
1522 }
1523 }
1524
1525 void logPointerDownEvent() {
1526 if (LOG_TOUCH_DOWNS) {
1527 // If we are not already timing a down/up sequence
1528 if (mLastTouchDown == 0) {
1529 mLastTouchDown = SystemClock.elapsedRealtime();
1530 mTouchCycles++;
1531 }
1532 }
1533 }
1534
1535 /**
1536 * Prevents the screen from turning on even if it *should* turn on due
1537 * to a subsequent full wake lock being acquired.
1538 * <p>
1539 * This is a temporary hack that allows an activity to "cover up" any
1540 * display glitches that happen during the activity's startup
1541 * sequence. (Specifically, this API was added to work around a
1542 * cosmetic bug in the "incoming call" sequence, where the lock screen
1543 * would flicker briefly before the incoming call UI became visible.)
1544 * TODO: There ought to be a more elegant way of doing this,
1545 * probably by having the PowerManager and ActivityManager
1546 * work together to let apps specify that the screen on/off
1547 * state should be synchronized with the Activity lifecycle.
1548 * <p>
1549 * Note that calling preventScreenOn(true) will NOT turn the screen
1550 * off if it's currently on. (This API only affects *future*
1551 * acquisitions of full wake locks.)
1552 * But calling preventScreenOn(false) WILL turn the screen on if
1553 * it's currently off because of a prior preventScreenOn(true) call.
1554 * <p>
1555 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1556 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1557 * call doesn't occur within 5 seconds, we'll turn the screen back on
1558 * ourselves (and log a warning about it); this prevents a buggy app
1559 * from disabling the screen forever.)
1560 * <p>
1561 * TODO: this feature should really be controlled by a new type of poke
1562 * lock (rather than an IPowerManager call).
1563 */
1564 public void preventScreenOn(boolean prevent) {
1565 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1566
1567 synchronized (mLocks) {
1568 if (prevent) {
1569 // First of all, grab a partial wake lock to
1570 // make sure the CPU stays on during the entire
1571 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1572 mPreventScreenOnPartialLock.acquire();
1573
1574 // Post a forceReenableScreen() call (for 5 seconds in the
1575 // future) to make sure the matching preventScreenOn(false) call
1576 // has happened by then.
1577 mHandler.removeCallbacks(mForceReenableScreenTask);
1578 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1579
1580 // Finally, set the flag that prevents the screen from turning on.
1581 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001582 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 mPreventScreenOn = true;
1584 } else {
1585 // (Re)enable the screen.
1586 mPreventScreenOn = false;
1587
1588 // We're "undoing" a the prior preventScreenOn(true) call, so we
1589 // no longer need the 5-second safeguard.
1590 mHandler.removeCallbacks(mForceReenableScreenTask);
1591
1592 // Forcibly turn on the screen if it's supposed to be on. (This
1593 // handles the case where the screen is currently off because of
1594 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001595 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001597 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1599 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001600 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001602 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604 }
1605
1606 // Release the partial wake lock that we held during the
1607 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1608 mPreventScreenOnPartialLock.release();
1609 }
1610 }
1611 }
1612
1613 public void setScreenBrightnessOverride(int brightness) {
1614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1615
Mike Lockwoodf527c712010-06-10 14:12:33 -04001616 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 synchronized (mLocks) {
1618 if (mScreenBrightnessOverride != brightness) {
1619 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001620 if (isScreenOn()) {
1621 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 }
1625 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001626
1627 public void setButtonBrightnessOverride(int brightness) {
1628 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1629
Mike Lockwoodf527c712010-06-10 14:12:33 -04001630 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001631 synchronized (mLocks) {
1632 if (mButtonBrightnessOverride != brightness) {
1633 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001634 if (isScreenOn()) {
1635 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1636 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001637 }
1638 }
1639 }
1640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 /**
1642 * Sanity-check that gets called 5 seconds after any call to
1643 * preventScreenOn(true). This ensures that the original call
1644 * is followed promptly by a call to preventScreenOn(false).
1645 */
1646 private void forceReenableScreen() {
1647 // We shouldn't get here at all if mPreventScreenOn is false, since
1648 // we should have already removed any existing
1649 // mForceReenableScreenTask messages...
1650 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001651 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 return;
1653 }
1654
1655 // Uh oh. It's been 5 seconds since a call to
1656 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1657 // This means the app that called preventScreenOn(true) is either
1658 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1659 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1660 // crashed before doing so.)
1661
1662 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001663 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 + "Forcing the screen back on...");
1665 preventScreenOn(false);
1666 }
1667
1668 private Runnable mForceReenableScreenTask = new Runnable() {
1669 public void run() {
1670 forceReenableScreen();
1671 }
1672 };
1673
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001674 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001675 if (DEBUG_SCREEN_ON) {
1676 RuntimeException e = new RuntimeException("here");
1677 e.fillInStackTrace();
1678 Slog.i(TAG, "Set screen state: " + on, e);
1679 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001680 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001681 if (err == 0) {
1682 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1683 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001684 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001685 if (!on) {
1686 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001687 mButtonLight.turnOff();
1688 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001689 // clear current value so we will update based on the new conditions
1690 // when the sensor is reenabled.
1691 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001692 // reset our highest light sensor value when the screen turns off
1693 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001694 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001695 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001696 }
1697 return err;
1698 }
1699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 private void setPowerState(int state)
1701 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001702 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704
Mike Lockwood435eb642009-12-03 08:40:18 -05001705 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 {
1707 synchronized (mLocks) {
1708 int err;
1709
1710 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001711 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001713 + " noChangeLights=" + noChangeLights
1714 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716
1717 if (noChangeLights) {
1718 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1719 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001720 if (mProximitySensorActive) {
1721 // don't turn on the screen when the proximity sensor lock is held
1722 newState = (newState & ~SCREEN_BRIGHT);
1723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724
1725 if (batteryIsLow()) {
1726 newState |= BATTERY_LOW_BIT;
1727 } else {
1728 newState &= ~BATTERY_LOW_BIT;
1729 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001730 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 return;
1732 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001733
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001734 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 newState |= ALL_BRIGHT;
1736 }
1737
1738 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1739 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1740
Mike Lockwood51b84492009-11-16 21:51:18 -05001741 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001742 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001744 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001748 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001750 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001752 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1754 }
1755
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001756 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757
1758 if (oldScreenOn != newScreenOn) {
1759 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001760 // When the user presses the power button, we need to always send out the
1761 // notification that it's going to sleep so the keyguard goes on. But
1762 // we can't do that until the screen fades out, so we don't show the keyguard
1763 // too early.
1764 if (mStillNeedSleepNotification) {
1765 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1766 }
1767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 // Turn on the screen UNLESS there was a prior
1769 // preventScreenOn(true) request. (Note that the lifetime
1770 // of a single preventScreenOn() request is limited to 5
1771 // seconds to prevent a buggy app from disabling the
1772 // screen forever; see forceReenableScreen().)
1773 boolean reallyTurnScreenOn = true;
1774 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001775 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 + mPreventScreenOn);
1777 }
1778
1779 if (mPreventScreenOn) {
1780 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001781 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
1783 reallyTurnScreenOn = false;
1784 }
1785 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001786 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 long identity = Binder.clearCallingIdentity();
1788 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001789 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 mBatteryStats.noteScreenOn();
1791 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001792 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 } finally {
1794 Binder.restoreCallingIdentity(identity);
1795 }
1796 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001797 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 // But continue as if we really did turn the screen on...
1799 err = 0;
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 mLastTouchDown = 0;
1803 mTotalTouchDownTime = 0;
1804 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001805 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 mTotalTouchDownTime, mTouchCycles);
1807 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001809 // Update the lights *after* taking care of turning the
1810 // screen on, so we do this after our notifications are
1811 // enqueued and thus will delay turning on the screen light
1812 // until the windows are correctly displayed.
1813 if (stateChanged) {
1814 updateLightsLocked(newState, 0);
1815 }
1816 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001820 // Update the lights *before* taking care of turning the
1821 // screen off, so we can initiate any animations that are desired.
1822 if (stateChanged) {
1823 updateLightsLocked(newState, 0);
1824 }
1825
Mike Lockwood497087e32009-11-08 18:33:03 -05001826 // cancel light sensor task
1827 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001828 mLightSensorPendingDecrease = false;
1829 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 mScreenOffTime = SystemClock.elapsedRealtime();
1831 long identity = Binder.clearCallingIdentity();
1832 try {
1833 mBatteryStats.noteScreenOff();
1834 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001835 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 } finally {
1837 Binder.restoreCallingIdentity(identity);
1838 }
1839 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001840 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001842 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 err = 0;
1845 mLastTouchDown = 0;
1846 }
1847 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001848 } else if (stateChanged) {
1849 // Screen on/off didn't change, but lights may have.
1850 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001852
1853 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1854
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001855 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001858
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001859 private void updateNativePowerStateLocked() {
1860 nativeSetPowerState(
1861 (mPowerState & SCREEN_ON_BIT) != 0,
1862 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001864
Mike Lockwood435eb642009-12-03 08:40:18 -05001865 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001867 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001869 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1870 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001872 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001874 mScreenOffReason = reason;
1875 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877 return err;
1878 }
1879
1880 private boolean batteryIsLow() {
1881 return (!mIsPowered &&
1882 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1883 }
1884
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001885 private boolean shouldDeferScreenOnLocked() {
1886 if (mPreparingForScreenOn) {
1887 // Currently waiting for confirmation from the policy that it
1888 // is okay to turn on the screen. Don't allow the screen to go
1889 // on until that is done.
1890 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1891 "updateLights: delaying screen on due to mPreparingForScreenOn");
1892 return true;
1893 } else {
1894 // If there is a screen-on command in the notification queue, we
1895 // can't turn the screen on until it has been processed (and we
1896 // have set mPreparingForScreenOn) or it has been dropped.
1897 for (int i=0; i<mBroadcastQueue.length; i++) {
1898 if (mBroadcastQueue[i] == 1) {
1899 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1900 "updateLights: delaying screen on due to notification queue");
1901 return true;
1902 }
1903 }
1904 }
1905 return false;
1906 }
1907
The Android Open Source Project10592532009-03-18 17:39:46 -07001908 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001909 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001910
1911 // If the screen is not currently on, we will want to delay actually
1912 // turning the lights on if we are still getting the UI put up.
1913 if ((oldState&SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1914 // Don't turn screen on until we know we are really ready to.
1915 // This is to avoid letting the screen go on before things like the
1916 // lock screen have been displayed.
1917 if ((mSkippedScreenOn=shouldDeferScreenOnLocked())) {
1918 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1919 }
1920 }
1921
Joe Onorato60607a92010-10-23 14:49:30 -07001922 if ((newState & SCREEN_ON_BIT) != 0) {
1923 // Only turn on the buttons or keyboard if the screen is also on.
1924 // We should never see the buttons on but not the screen.
1925 newState = applyButtonState(newState);
1926 newState = applyKeyboardState(newState);
1927 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001928 final int realDifference = (newState ^ oldState);
1929 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001931 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 int offMask = 0;
1935 int dimMask = 0;
1936 int onMask = 0;
1937
1938 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001941 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1942 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001944 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
1946 }
1947
1948 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001949 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1950 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001952 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
1954 }
1955
1956 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001957 int nominalCurrentValue = -1;
1958 // If there was an actual difference in the light state, then
1959 // figure out the "ideal" current value based on the previous
1960 // state. Otherwise, this is a change due to the brightness
1961 // override, so we want to animate from whatever the current
1962 // value is.
1963 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1964 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1965 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1966 nominalCurrentValue = preferredBrightness;
1967 break;
1968 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001969 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001970 break;
1971 case 0:
1972 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1973 break;
1974 case SCREEN_BRIGHT_BIT:
1975 default:
1976 // not possible
1977 nominalCurrentValue = (int)mScreenBrightness.curValue;
1978 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001979 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001980 }
1981 int brightness = preferredBrightness;
1982 int steps = ANIM_STEPS;
1983 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1984 // dim or turn off backlight, depending on if the screen is on
1985 // the scale is because the brightness ramp isn't linear and this biases
1986 // it so the later parts take longer.
1987 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001988 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07001989 if (ratio > 1.0f) ratio = 1.0f;
1990 if ((newState & SCREEN_ON_BIT) == 0) {
1991 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1992 // was bright
1993 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001995 // was dim
1996 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001998 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002000 if ((oldState & SCREEN_ON_BIT) != 0) {
2001 // was bright
2002 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
2003 } else {
2004 // was dim
2005 steps = (int)(ANIM_STEPS*ratio);
2006 }
2007 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2008 // If the "stay on while plugged in" option is
2009 // turned on, then the screen will often not
2010 // automatically turn off while plugged in. To
2011 // still have a sense of when it is inactive, we
2012 // will then count going dim as turning off.
2013 mScreenOffTime = SystemClock.elapsedRealtime();
2014 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002015 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002018 long identity = Binder.clearCallingIdentity();
2019 try {
2020 mBatteryStats.noteScreenBrightness(brightness);
2021 } catch (RemoteException e) {
2022 // Nothing interesting to do.
2023 } finally {
2024 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002026 mScreenBrightness.setTargetLocked(brightness, steps,
2027 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002028 if (DEBUG_SCREEN_ON) {
2029 RuntimeException e = new RuntimeException("here");
2030 e.fillInStackTrace();
2031 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2032 mScreenBrightness.setTargetLocked(brightness, steps,
2033 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
2034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002036
Joe Onorato60607a92010-10-23 14:49:30 -07002037 if (mSpew) {
2038 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2039 + " dimMask=0x" + Integer.toHexString(dimMask)
2040 + " onMask=0x" + Integer.toHexString(onMask)
2041 + " difference=0x" + Integer.toHexString(difference)
2042 + " realDifference=0x" + Integer.toHexString(realDifference)
2043 + " forceState=0x" + Integer.toHexString(forceState)
2044 );
2045 }
2046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002048 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002049 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002052 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 if ((newState & BATTERY_LOW_BIT) != 0 &&
2054 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2055 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2056 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002057 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002058 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 if (onMask != 0) {
2061 int brightness = getPreferredBrightness();
2062 if ((newState & BATTERY_LOW_BIT) != 0 &&
2063 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2064 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2065 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002066 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002067 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070
The Android Open Source Project10592532009-03-18 17:39:46 -07002071 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002072 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002073 ? LightsService.BRIGHTNESS_MODE_SENSOR
2074 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07002075 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002076 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07002077 }
2078 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002079 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002080 }
2081 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002082 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085
Joe Onoratob08a1af2010-10-11 19:28:58 -07002086 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 boolean initialized;
2090 int targetValue;
2091 float curValue;
2092 float delta;
2093 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 BrightnessState(int m) {
2096 mask = m;
2097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 public void dump(PrintWriter pw, String prefix) {
2100 pw.println(prefix + "animating=" + animating
2101 + " targetValue=" + targetValue
2102 + " curValue=" + curValue
2103 + " delta=" + delta);
2104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002105
Joe Onoratob08a1af2010-10-11 19:28:58 -07002106 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002107 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 if (!initialized) {
2109 initialized = true;
2110 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002111 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002112 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002115 delta = (targetValue -
2116 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2117 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07002119 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002120 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2121 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002122 + " nominalCurrentValue=" + nominalCurrentValue
2123 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002126
2127 if (mSpew) {
2128 Slog.i(TAG, "scheduling light animator");
2129 }
2130 mScreenOffHandler.removeCallbacks(this);
2131 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 boolean stepLocked() {
2135 if (!animating) return false;
2136 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002137 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 + " target=" + targetValue + " delta=" + delta);
2139 }
2140 curValue += delta;
2141 int curIntValue = (int)curValue;
2142 boolean more = true;
2143 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002144 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 more = false;
2146 } else if (delta > 0) {
2147 if (curIntValue >= targetValue) {
2148 curValue = curIntValue = targetValue;
2149 more = false;
2150 }
2151 } else {
2152 if (curIntValue <= targetValue) {
2153 curValue = curIntValue = targetValue;
2154 more = false;
2155 }
2156 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002157 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002158 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002159 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002160 return more;
2161 }
2162
Joe Onorato3d3db602010-10-18 16:08:16 -04002163 void jumpToTargetLocked() {
2164 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002165 setLightBrightness(mask, targetValue);
2166 final int tv = targetValue;
2167 curValue = tv;
2168 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002169 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002170 }
2171
Joe Onorato3d3db602010-10-18 16:08:16 -04002172 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 animating = more;
2174 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002175 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002176 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
2178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002182 if (mAnimateScreenLights) {
2183 synchronized (mLocks) {
2184 long now = SystemClock.uptimeMillis();
2185 boolean more = mScreenBrightness.stepLocked();
2186 if (more) {
2187 mScreenOffHandler.postAtTime(this, now+(1000/60));
2188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002190 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002191 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002192 // we're turning off
2193 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2194 if (animate) {
2195 // It's pretty scary to hold mLocks for this long, and we should
2196 // redesign this, but it works for now.
2197 nativeStartSurfaceFlingerAnimation(
2198 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2199 ? 0 : mAnimationSetting);
2200 }
2201 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 }
2204 }
2205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 private int getPreferredBrightness() {
2208 try {
2209 if (mScreenBrightnessOverride >= 0) {
2210 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002211 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002212 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002213 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2216 SCREEN_BRIGHTNESS);
2217 // Don't let applications turn the screen all the way off
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002218 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 } catch (SettingNotFoundException snfe) {
2220 return Power.BRIGHTNESS_ON;
2221 }
2222 }
2223
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002224 private int applyButtonState(int state) {
2225 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002226 if ((state & BATTERY_LOW_BIT) != 0) {
2227 // do not override brightness if the battery is low
2228 return state;
2229 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002230 if (mButtonBrightnessOverride >= 0) {
2231 brightness = mButtonBrightnessOverride;
2232 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2233 brightness = mLightSensorButtonBrightness;
2234 }
2235 if (brightness > 0) {
2236 return state | BUTTON_BRIGHT_BIT;
2237 } else if (brightness == 0) {
2238 return state & ~BUTTON_BRIGHT_BIT;
2239 } else {
2240 return state;
2241 }
2242 }
2243
2244 private int applyKeyboardState(int state) {
2245 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002246 if ((state & BATTERY_LOW_BIT) != 0) {
2247 // do not override brightness if the battery is low
2248 return state;
2249 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002250 if (!mKeyboardVisible) {
2251 brightness = 0;
2252 } else if (mButtonBrightnessOverride >= 0) {
2253 brightness = mButtonBrightnessOverride;
2254 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2255 brightness = mLightSensorKeyboardBrightness;
2256 }
2257 if (brightness > 0) {
2258 return state | KEYBOARD_BRIGHT_BIT;
2259 } else if (brightness == 0) {
2260 return state & ~KEYBOARD_BRIGHT_BIT;
2261 } else {
2262 return state;
2263 }
2264 }
2265
Charles Mendis322591c2009-10-29 11:06:59 -07002266 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 synchronized (mLocks) {
2268 return (mPowerState & SCREEN_ON_BIT) != 0;
2269 }
2270 }
2271
Charles Mendis322591c2009-10-29 11:06:59 -07002272 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 synchronized (mLocks) {
2274 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2275 }
2276 }
2277
Mike Lockwood497087e32009-11-08 18:33:03 -05002278 private boolean isScreenTurningOffLocked() {
2279 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2280 }
2281
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002282 private boolean shouldLog(long time) {
2283 synchronized (mLocks) {
2284 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2285 mWarningSpewThrottleTime = time;
2286 mWarningSpewThrottleCount = 0;
2287 return true;
2288 } else if (mWarningSpewThrottleCount < 30) {
2289 mWarningSpewThrottleCount++;
2290 return true;
2291 } else {
2292 return false;
2293 }
2294 }
2295 }
2296
Mike Lockwood200b30b2009-09-20 00:23:59 -04002297 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002298 if (isScreenTurningOffLocked()) {
2299 // cancel animation so userActivity will succeed
2300 mScreenBrightness.animating = false;
2301 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002302 boolean savedActivityAllowed = mUserActivityAllowed;
2303 mUserActivityAllowed = true;
2304 userActivity(SystemClock.uptimeMillis(), false);
2305 mUserActivityAllowed = savedActivityAllowed;
2306 }
2307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2309 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002310 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312
2313 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002314 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2315 != PackageManager.PERMISSION_GRANTED) {
2316 if (shouldLog(time)) {
2317 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2318 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2319 }
2320 return;
2321 }
2322
Joe Onorato7999bff2010-07-24 11:50:05 -04002323 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325
2326 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002327 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 }
2329
2330 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002331 userActivity(time, -1, noChangeLights, eventType, force);
2332 }
2333
2334 /*
2335 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2336 * on with user activity. Don't use this function.
2337 */
2338 public void clearUserActivityTimeout(long now, long timeout) {
2339 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2340 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2341 userActivity(now, timeout, false, OTHER_EVENT, false);
2342 }
2343
2344 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2345 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346
Joe Onorato1a542c72010-11-08 09:48:20 -08002347 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002348 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002349 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002350 }
2351 return;
2352 }
2353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 synchronized (mLocks) {
2355 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002356 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 + " mUserActivityAllowed=" + mUserActivityAllowed
2358 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002359 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2360 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002361 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002362 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
Mike Lockwood05067122009-10-27 23:07:25 -04002364 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002365 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002366 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002367 return;
2368 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002369 // Disable proximity sensor if if user presses power key while we are in the
2370 // "waiting for proximity sensor to go negative" state.
2371 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2372 mProximitySensorActive = false;
2373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 if (mLastEventTime <= time || force) {
2375 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002376 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002377 // Only turn on button backlights if a button was pressed
2378 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002379 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2381 } else {
2382 // don't clear button/keyboard backlights when the screen is touched.
2383 mUserState |= SCREEN_BRIGHT;
2384 }
2385
Dianne Hackborn617f8772009-03-31 15:04:46 -07002386 int uid = Binder.getCallingUid();
2387 long ident = Binder.clearCallingIdentity();
2388 try {
2389 mBatteryStats.noteUserActivity(uid, eventType);
2390 } catch (RemoteException e) {
2391 // Ignore
2392 } finally {
2393 Binder.restoreCallingIdentity(ident);
2394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002395
Michael Chane96440f2009-05-06 10:27:36 -07002396 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002397 setPowerState(mUserState | mWakeLockState, noChangeLights,
2398 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002399 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
2401 }
2402 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002403
2404 if (mPolicy != null) {
2405 mPolicy.userActivity();
2406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 }
2408
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002409 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2410 try {
2411 int i;
2412 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2413 if (sensorValue < mAutoBrightnessLevels[i]) {
2414 break;
2415 }
2416 }
2417 return values[i];
2418 } catch (Exception e) {
2419 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002420 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002421 return 255;
2422 }
2423 }
2424
Mike Lockwood20f87d72009-11-05 16:08:51 -05002425 private Runnable mProximityTask = new Runnable() {
2426 public void run() {
2427 synchronized (mLocks) {
2428 if (mProximityPendingValue != -1) {
2429 proximityChangedLocked(mProximityPendingValue == 1);
2430 mProximityPendingValue = -1;
2431 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002432 if (mProximityPartialLock.isHeld()) {
2433 mProximityPartialLock.release();
2434 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002435 }
2436 }
2437 };
2438
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002439 private Runnable mAutoBrightnessTask = new Runnable() {
2440 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002441 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002442 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2443 int value = (int)mLightSensorPendingValue;
2444 mLightSensorPendingDecrease = false;
2445 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002446 lightSensorChangedLocked(value);
2447 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002448 }
2449 }
2450 };
2451
Mike Lockwoodb2865412010-02-02 22:40:33 -05002452 private void dockStateChanged(int state) {
2453 synchronized (mLocks) {
2454 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2455 if (mIsDocked) {
2456 mHighestLightSensorValue = -1;
2457 }
2458 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2459 // force lights recalculation
2460 int value = (int)mLightSensorValue;
2461 mLightSensorValue = -1;
2462 lightSensorChangedLocked(value);
2463 }
2464 }
2465 }
2466
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002467 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002468 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002470 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002471
Joe Onorato06eb33a2010-10-25 14:09:21 -07002472 // Don't do anything if the screen is off.
2473 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2474 if (mDebugLightSensor) {
2475 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2476 }
2477 return;
2478 }
2479
Mike Lockwoodb2865412010-02-02 22:40:33 -05002480 // do not allow light sensor value to decrease
2481 if (mHighestLightSensorValue < value) {
2482 mHighestLightSensorValue = value;
2483 }
2484
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002485 if (mLightSensorValue != value) {
2486 mLightSensorValue = value;
2487 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002488 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2489 // we only do this if we are undocked, since lighting should be stable when
2490 // stationary in a dock.
2491 int lcdValue = getAutoBrightnessValue(
2492 (mIsDocked ? value : mHighestLightSensorValue),
2493 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002494 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002495 int keyboardValue;
2496 if (mKeyboardVisible) {
2497 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2498 } else {
2499 keyboardValue = 0;
2500 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002501 mLightSensorScreenBrightness = lcdValue;
2502 mLightSensorButtonBrightness = buttonValue;
2503 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002504
2505 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002506 Slog.d(TAG, "lcdValue " + lcdValue);
2507 Slog.d(TAG, "buttonValue " + buttonValue);
2508 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002509 }
2510
Mike Lockwood4984e732009-11-01 08:16:33 -05002511 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002512 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2513 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002514 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002515 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002516 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002517 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002518 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002519 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002520 }
2521 }
2522 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 /**
2526 * The user requested that we go to sleep (probably with the power button).
2527 * This overrides all wake locks that are held.
2528 */
2529 public void goToSleep(long time)
2530 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002531 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2532 }
2533
2534 /**
2535 * The user requested that we go to sleep (probably with the power button).
2536 * This overrides all wake locks that are held.
2537 */
2538 public void goToSleepWithReason(long time, int reason)
2539 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2541 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002542 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
2544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002547 * Reboot the device immediately, passing 'reason' (may be null)
2548 * to the underlying __reboot system call. Should not return.
2549 */
2550 public void reboot(String reason)
2551 {
2552 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002553
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002554 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2555 throw new IllegalStateException("Too early to call reboot()");
2556 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002557
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002558 final String finalReason = reason;
2559 Runnable runnable = new Runnable() {
2560 public void run() {
2561 synchronized (this) {
2562 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002563 }
2564
San Mehat1e512792010-01-07 10:40:29 -08002565 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002566 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002567 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002568 mHandler.post(runnable);
2569
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002570 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002571 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002572 while (true) {
2573 try {
2574 runnable.wait();
2575 } catch (InterruptedException e) {
2576 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002577 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002578 }
2579 }
2580
Dan Egnor60d87622009-12-16 16:32:58 -08002581 /**
2582 * Crash the runtime (causing a complete restart of the Android framework).
2583 * Requires REBOOT permission. Mostly for testing. Should not return.
2584 */
2585 public void crash(final String message)
2586 {
2587 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2588 Thread t = new Thread("PowerManagerService.crash()") {
2589 public void run() { throw new RuntimeException(message); }
2590 };
2591 try {
2592 t.start();
2593 t.join();
2594 } catch (InterruptedException e) {
2595 Log.wtf(TAG, e);
2596 }
2597 }
2598
Mike Lockwood435eb642009-12-03 08:40:18 -05002599 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600
2601 if (mLastEventTime <= time) {
2602 mLastEventTime = time;
2603 // cancel all of the wake locks
2604 mWakeLockState = SCREEN_OFF;
2605 int N = mLocks.size();
2606 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002607 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 for (int i=0; i<N; i++) {
2609 WakeLock wl = mLocks.get(i);
2610 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002611 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2612 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2613 proxLock = true;
2614 } else {
2615 mLocks.get(i).activated = false;
2616 numCleared++;
2617 }
2618 }
2619 }
2620 if (!proxLock) {
2621 mProxIgnoredBecauseScreenTurnedOff = true;
2622 if (mDebugProximitySensor) {
2623 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002626 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002627 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002629 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 cancelTimerLocked();
2631 }
2632 }
2633
2634 public long timeSinceScreenOn() {
2635 synchronized (mLocks) {
2636 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2637 return 0;
2638 }
2639 return SystemClock.elapsedRealtime() - mScreenOffTime;
2640 }
2641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002644 synchronized (mLocks) {
2645 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002646 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002647 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002648 if (mKeyboardVisible != visible) {
2649 mKeyboardVisible = visible;
2650 // don't signal user activity if the screen is off; other code
2651 // will take care of turning on due to a true change to the lid
2652 // switch and synchronized with the lock screen.
2653 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002654 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002655 // force recompute of backlight values
2656 if (mLightSensorValue >= 0) {
2657 int value = (int)mLightSensorValue;
2658 mLightSensorValue = -1;
2659 lightSensorChangedLocked(value);
2660 }
2661 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002662 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2663 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002664 }
2665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
2667
2668 /**
2669 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002670 * When disabling user activity we also reset user power state so the keyguard can reset its
2671 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 */
2673 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002674 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002675 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 synchronized (mLocks) {
2678 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002679 if (!enabled) {
2680 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2681 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 }
2684 }
2685
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002686 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002687 synchronized (mLocks) {
2688 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2689 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2690 mAutoBrightessEnabled = enabled;
2691 // This will get us a new value
2692 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002693 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002694 }
2695 }
2696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 /** Sets the screen off timeouts:
2698 * mKeylightDelay
2699 * mDimDelay
2700 * mScreenOffDelay
2701 * */
2702 private void setScreenOffTimeoutsLocked() {
2703 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002704 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 mDimDelay = -1;
2706 mScreenOffDelay = 0;
2707 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2708 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2709 mDimDelay = -1;
2710 mScreenOffDelay = 0;
2711 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002712 int totalDelay = mScreenOffTimeoutSetting;
2713 if (totalDelay > mMaximumScreenOffTimeout) {
2714 totalDelay = mMaximumScreenOffTimeout;
2715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2717 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002718 // negative number means stay on as long as possible.
2719 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 } else if (mKeylightDelay < totalDelay) {
2721 // subtract the time that the keylight delay. This will give us the
2722 // remainder of the time that we need to sleep to get the accurate
2723 // screen off timeout.
2724 mScreenOffDelay = totalDelay - mKeylightDelay;
2725 } else {
2726 mScreenOffDelay = 0;
2727 }
2728 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2729 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2730 mScreenOffDelay = LONG_DIM_TIME;
2731 } else {
2732 mDimDelay = -1;
2733 }
2734 }
2735 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002736 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2738 + " mDimScreen=" + mDimScreen);
2739 }
2740 }
2741
2742 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002743 * Refreshes cached secure settings. Called once on startup, and
2744 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 */
Doug Zongker43866e02010-01-07 12:09:54 -08002746 private void updateSettingsValues() {
2747 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002749 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002751 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 }
2753
2754 private class LockList extends ArrayList<WakeLock>
2755 {
2756 void addLock(WakeLock wl)
2757 {
2758 int index = getIndex(wl.binder);
2759 if (index < 0) {
2760 this.add(wl);
2761 }
2762 }
2763
2764 WakeLock removeLock(IBinder binder)
2765 {
2766 int index = getIndex(binder);
2767 if (index >= 0) {
2768 return this.remove(index);
2769 } else {
2770 return null;
2771 }
2772 }
2773
2774 int getIndex(IBinder binder)
2775 {
2776 int N = this.size();
2777 for (int i=0; i<N; i++) {
2778 if (this.get(i).binder == binder) {
2779 return i;
2780 }
2781 }
2782 return -1;
2783 }
2784
2785 int gatherState()
2786 {
2787 int result = 0;
2788 int N = this.size();
2789 for (int i=0; i<N; i++) {
2790 WakeLock wl = this.get(i);
2791 if (wl.activated) {
2792 if (isScreenLock(wl.flags)) {
2793 result |= wl.minState;
2794 }
2795 }
2796 }
2797 return result;
2798 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002799
Michael Chane96440f2009-05-06 10:27:36 -07002800 int reactivateScreenLocksLocked()
2801 {
2802 int result = 0;
2803 int N = this.size();
2804 for (int i=0; i<N; i++) {
2805 WakeLock wl = this.get(i);
2806 if (isScreenLock(wl.flags)) {
2807 wl.activated = true;
2808 result |= wl.minState;
2809 }
2810 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002811 if (mDebugProximitySensor) {
2812 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2813 + mProxIgnoredBecauseScreenTurnedOff);
2814 }
2815 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002816 return result;
2817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002820 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 synchronized (mLocks) {
2822 mPolicy = p;
2823 mLocks.notifyAll();
2824 }
2825 }
2826
2827 WindowManagerPolicy getPolicyLocked() {
2828 while (mPolicy == null || !mDoneBooting) {
2829 try {
2830 mLocks.wait();
2831 } catch (InterruptedException e) {
2832 // Ignore
2833 }
2834 }
2835 return mPolicy;
2836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002839 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2840 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2841 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002842 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002843 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002844 }
2845
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002846 // wait until sensors are enabled before turning on screen.
2847 // some devices will not activate the light sensor properly on boot
2848 // unless we do this.
2849 if (mUseSoftwareAutoBrightness) {
2850 // turn the screen on
2851 setPowerState(SCREEN_BRIGHT);
2852 } else {
2853 // turn everything on
2854 setPowerState(ALL_BRIGHT);
2855 }
2856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002858 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002860
Joe Onoratod28f7532010-11-06 12:56:53 -07002861 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2862
Dianne Hackborn617f8772009-03-31 15:04:46 -07002863 long identity = Binder.clearCallingIdentity();
2864 try {
2865 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2866 mBatteryStats.noteScreenOn();
2867 } catch (RemoteException e) {
2868 // Nothing interesting to do.
2869 } finally {
2870 Binder.restoreCallingIdentity(identity);
2871 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002872 }
2873 }
2874
2875 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002876 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002877 synchronized (mLocks) {
2878 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2880 updateWakeLockLocked();
2881 mLocks.notifyAll();
2882 }
2883 }
2884
Joe Onoratob08a1af2010-10-11 19:28:58 -07002885 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 public void monitor() {
2887 synchronized (mLocks) { }
2888 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002889
2890 public int getSupportedWakeLockFlags() {
2891 int result = PowerManager.PARTIAL_WAKE_LOCK
2892 | PowerManager.FULL_WAKE_LOCK
2893 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2894
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002895 if (mProximitySensor != null) {
2896 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2897 }
2898
2899 return result;
2900 }
2901
Mike Lockwood237a2992009-09-15 14:42:16 -04002902 public void setBacklightBrightness(int brightness) {
2903 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2904 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002905 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002906 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002907 mLcdLight.setBrightness(brightness);
2908 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2909 mButtonLight.setBrightness(brightness);
2910 long identity = Binder.clearCallingIdentity();
2911 try {
2912 mBatteryStats.noteScreenBrightness(brightness);
2913 } catch (RemoteException e) {
2914 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2915 } finally {
2916 Binder.restoreCallingIdentity(identity);
2917 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002918
Joe Onoratob08a1af2010-10-11 19:28:58 -07002919 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002920 synchronized (mLocks) {
2921 mScreenBrightness.targetValue = brightness;
2922 mScreenBrightness.jumpToTargetLocked();
2923 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002924 }
2925 }
2926
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002927 public void setAttentionLight(boolean on, int color) {
2928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002929 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002930 }
2931
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002932 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002933 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002934 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002935 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002936 if (!mProximitySensorEnabled) {
2937 // clear calling identity so sensor manager battery stats are accurate
2938 long identity = Binder.clearCallingIdentity();
2939 try {
2940 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2941 SensorManager.SENSOR_DELAY_NORMAL);
2942 mProximitySensorEnabled = true;
2943 } finally {
2944 Binder.restoreCallingIdentity(identity);
2945 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002946 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002947 }
2948
2949 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002950 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002951 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002952 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002953 if (mProximitySensorEnabled) {
2954 // clear calling identity so sensor manager battery stats are accurate
2955 long identity = Binder.clearCallingIdentity();
2956 try {
2957 mSensorManager.unregisterListener(mProximityListener);
2958 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002959 if (mProximityPartialLock.isHeld()) {
2960 mProximityPartialLock.release();
2961 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002962 mProximitySensorEnabled = false;
2963 } finally {
2964 Binder.restoreCallingIdentity(identity);
2965 }
2966 if (mProximitySensorActive) {
2967 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002968 if (mDebugProximitySensor) {
2969 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2970 + mProxIgnoredBecauseScreenTurnedOff);
2971 }
2972 if (!mProxIgnoredBecauseScreenTurnedOff) {
2973 forceUserActivityLocked();
2974 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002975 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002976 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002977 }
2978
Mike Lockwood20f87d72009-11-05 16:08:51 -05002979 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002980 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002981 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002982 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002983 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002984 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002985 return;
2986 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002987 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002988 if (mDebugProximitySensor) {
2989 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2990 + mProxIgnoredBecauseScreenTurnedOff);
2991 }
2992 if (!mProxIgnoredBecauseScreenTurnedOff) {
2993 goToSleepLocked(SystemClock.uptimeMillis(),
2994 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2995 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002996 mProximitySensorActive = true;
2997 } else {
2998 // proximity sensor negative events trigger as user activity.
2999 // temporarily set mUserActivityAllowed to true so this will work
3000 // even when the keyguard is on.
3001 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04003002 if (mDebugProximitySensor) {
3003 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
3004 + mProxIgnoredBecauseScreenTurnedOff);
3005 }
3006 if (!mProxIgnoredBecauseScreenTurnedOff) {
3007 forceUserActivityLocked();
3008 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003009
3010 if (mProximityWakeLockCount == 0) {
3011 // disable sensor if we have no listeners left after proximity negative
3012 disableProximityLockLocked();
3013 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003014 }
3015 }
3016
Joe Onoratod28f7532010-11-06 12:56:53 -07003017 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003018 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003019 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3020 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3021 }
3022 if (!mAutoBrightessEnabled) {
3023 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003024 }
3025 if (mSensorManager != null && mLightSensorEnabled != enable) {
3026 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003027 // clear calling identity so sensor manager battery stats are accurate
3028 long identity = Binder.clearCallingIdentity();
3029 try {
3030 if (enable) {
3031 mSensorManager.registerListener(mLightListener, mLightSensor,
3032 SensorManager.SENSOR_DELAY_NORMAL);
3033 } else {
3034 mSensorManager.unregisterListener(mLightListener);
3035 mHandler.removeCallbacks(mAutoBrightnessTask);
3036 }
3037 } finally {
3038 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003039 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003040 }
3041 }
3042
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003043 SensorEventListener mProximityListener = new SensorEventListener() {
3044 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003045 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003046 synchronized (mLocks) {
3047 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003048 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3049 mLastProximityEventTime = milliseconds;
3050 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003051 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003052
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003053 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003054 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3055 distance < mProximitySensor.getMaximumRange());
3056
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003057 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003058 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003059 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003060 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3061 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3062 mProximityPendingValue = (active ? 1 : 0);
3063 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003064 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003065 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003066 // process the value immediately
3067 mProximityPendingValue = -1;
3068 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003069 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003070
3071 // update mProximityPartialLock state
3072 boolean held = mProximityPartialLock.isHeld();
3073 if (!held && proximityTaskQueued) {
3074 // hold wakelock until mProximityTask runs
3075 mProximityPartialLock.acquire();
3076 } else if (held && !proximityTaskQueued) {
3077 mProximityPartialLock.release();
3078 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003079 }
3080 }
3081
3082 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3083 // ignore
3084 }
3085 };
3086
3087 SensorEventListener mLightListener = new SensorEventListener() {
3088 public void onSensorChanged(SensorEvent event) {
3089 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003090 // ignore light sensor while screen is turning off
3091 if (isScreenTurningOffLocked()) {
3092 return;
3093 }
3094
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003095 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003096 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003097 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003098 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003099 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05003100 if (mLightSensorValue == -1 ||
3101 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3102 // process the value immediately if screen has just turned on
3103 mHandler.removeCallbacks(mAutoBrightnessTask);
3104 mLightSensorPendingDecrease = false;
3105 mLightSensorPendingIncrease = false;
3106 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003107 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003108 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3109 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3110 (value == mLightSensorValue) ||
3111 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3112 // delay processing to debounce the sensor
3113 mHandler.removeCallbacks(mAutoBrightnessTask);
3114 mLightSensorPendingDecrease = (value < mLightSensorValue);
3115 mLightSensorPendingIncrease = (value > mLightSensorValue);
3116 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3117 mLightSensorPendingValue = value;
3118 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3119 }
3120 } else {
3121 mLightSensorPendingValue = value;
3122 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003123 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003124 }
3125 }
3126
3127 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3128 // ignore
3129 }
3130 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131}