blob: 785db9829992a5f655ee08fc71029a5ebd6db177 [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();
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 void initInThread() {
571 mHandler = new Handler();
572
573 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700574 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
576 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
577 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
578 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
579 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
580 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500581 mProximityPartialLock = new UnsynchronizedWakeLock(
582 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583
584 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
585 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
586 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
587 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
588
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700589 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400590
Joe Onoratob08a1af2010-10-11 19:28:58 -0700591 mAnimateScreenLights = resources.getBoolean(
592 com.android.internal.R.bool.config_animateScreenLights);
593
Joe Onorato6d747652010-10-11 15:15:31 -0700594 mUnplugTurnsOnScreen = resources.getBoolean(
595 com.android.internal.R.bool.config_unplugTurnsOnScreen);
596
Mike Lockwoodeb6456b2011-09-13 15:24:02 -0400597 mScreenBrightnessDim = resources.getInteger(
598 com.android.internal.R.integer.config_screenBrightnessDim);
599
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400600 // read settings for auto-brightness
601 mUseSoftwareAutoBrightness = resources.getBoolean(
602 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400603 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700604 mAutoBrightnessLevels = resources.getIntArray(
605 com.android.internal.R.array.config_autoBrightnessLevels);
606 mLcdBacklightValues = resources.getIntArray(
607 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
608 mButtonBacklightValues = resources.getIntArray(
609 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
610 mKeyboardBacklightValues = resources.getIntArray(
611 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500612 mLightSensorWarmupTime = resources.getInteger(
613 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700614 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700615
616 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
618 "(" + Settings.System.NAME + "=?) or ("
619 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700620 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700621 + Settings.System.NAME + "=?) or ("
622 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700624 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700625 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 null);
627 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
628 SettingsObserver settingsObserver = new SettingsObserver();
629 mSettings.addObserver(settingsObserver);
630
631 // pretend that the settings changed so we will get their initial state
632 settingsObserver.update(mSettings, null);
633
634 // register for the battery changed notifications
635 IntentFilter filter = new IntentFilter();
636 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
637 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500638 filter = new IntentFilter();
639 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
640 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500641 filter = new IntentFilter();
642 filter.addAction(Intent.ACTION_DOCK_EVENT);
643 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644
Doug Zongker43866e02010-01-07 12:09:54 -0800645 // Listen for secure settings changes
646 mContext.getContentResolver().registerContentObserver(
647 Settings.Secure.CONTENT_URI, true,
648 new ContentObserver(new Handler()) {
649 public void onChange(boolean selfChange) {
650 updateSettingsValues();
651 }
652 });
653 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 synchronized (mHandlerThread) {
656 mInitComplete = true;
657 mHandlerThread.notifyAll();
658 }
659 }
660
661 private class WakeLock implements IBinder.DeathRecipient
662 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700663 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 super();
665 flags = f;
666 binder = b;
667 tag = t;
668 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700669 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 if (u != MY_UID || (
671 !"KEEP_SCREEN_ON_FLAG".equals(tag)
672 && !"KeyInputQueue".equals(tag))) {
673 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
674 ? BatteryStats.WAKE_TYPE_PARTIAL
675 : BatteryStats.WAKE_TYPE_FULL;
676 } else {
677 monitorType = -1;
678 }
679 try {
680 b.linkToDeath(this, 0);
681 } catch (RemoteException e) {
682 binderDied();
683 }
684 }
685 public void binderDied() {
686 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500687 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
689 }
690 final int flags;
691 final IBinder binder;
692 final String tag;
693 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400694 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700696 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 boolean activated = true;
698 int minState;
699 }
700
701 private void updateWakeLockLocked() {
702 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
703 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
704 mStayOnWhilePluggedInScreenDimLock.acquire();
705 mStayOnWhilePluggedInPartialLock.acquire();
706 } else {
707 mStayOnWhilePluggedInScreenDimLock.release();
708 mStayOnWhilePluggedInPartialLock.release();
709 }
710 }
711
712 private boolean isScreenLock(int flags)
713 {
714 int n = flags & LOCK_MASK;
715 return n == PowerManager.FULL_WAKE_LOCK
716 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400717 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
718 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700721 void enforceWakeSourcePermission(int uid, int pid) {
722 if (uid == Process.myUid()) {
723 return;
724 }
725 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
726 pid, uid, null);
727 }
728
729 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700731 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700732 if (uid != Process.myUid()) {
733 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
734 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700735 if (ws != null) {
736 enforceWakeSourcePermission(uid, pid);
737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 long ident = Binder.clearCallingIdentity();
739 try {
740 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700741 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
743 } finally {
744 Binder.restoreCallingIdentity(ident);
745 }
746 }
747
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700748 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700749 if (wl.monitorType >= 0) {
750 long origId = Binder.clearCallingIdentity();
751 try {
752 if (ws != null) {
753 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
754 wl.monitorType);
755 } else {
756 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
757 }
758 } catch (RemoteException e) {
759 // Ignore
760 } finally {
761 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700762 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700763 }
764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700766 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700767 if (wl.monitorType >= 0) {
768 long origId = Binder.clearCallingIdentity();
769 try {
770 if (ws != null) {
771 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
772 wl.monitorType);
773 } else {
774 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
775 }
776 } catch (RemoteException e) {
777 // Ignore
778 } finally {
779 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700780 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700781 }
782 }
783
784 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
785 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800787 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 }
789
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700790 if (ws != null && ws.size() == 0) {
791 ws = null;
792 }
793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 int index = mLocks.getIndex(lock);
795 WakeLock wl;
796 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700797 boolean diffsource;
798 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700800 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 switch (wl.flags & LOCK_MASK)
802 {
803 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500804 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400805 wl.minState = SCREEN_BRIGHT;
806 } else {
807 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 break;
810 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
811 wl.minState = SCREEN_BRIGHT;
812 break;
813 case PowerManager.SCREEN_DIM_WAKE_LOCK:
814 wl.minState = SCREEN_DIM;
815 break;
816 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700817 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 break;
819 default:
820 // just log and bail. we're in the server, so don't
821 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800822 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 + " flags=" + flags);
824 return;
825 }
826 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700827 if (ws != null) {
828 wl.ws = new WorkSource(ws);
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700831 diffsource = false;
832 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 } else {
834 wl = mLocks.get(index);
835 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700836 oldsource = wl.ws;
837 if (oldsource != null) {
838 if (ws == null) {
839 wl.ws = null;
840 diffsource = true;
841 } else {
842 diffsource = oldsource.diff(ws);
843 }
844 } else if (ws != null) {
845 diffsource = true;
846 } else {
847 diffsource = false;
848 }
849 if (diffsource) {
850 wl.ws = new WorkSource(ws);
851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853 if (isScreenLock(flags)) {
854 // if this causes a wakeup, we reactivate all of the locks and
855 // set it to whatever they want. otherwise, we modulate that
856 // by the current state so we never turn it more on than
857 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400858 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
859 mProximityWakeLockCount++;
860 if (mProximityWakeLockCount == 1) {
861 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400864 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
865 int oldWakeLockState = mWakeLockState;
866 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400867
868 // Disable proximity sensor if if user presses power key while we are in the
869 // "waiting for proximity sensor to go negative" state.
870 if ((mWakeLockState & SCREEN_ON_BIT) != 0
871 && mProximitySensorActive && mProximityWakeLockCount == 0) {
872 mProximitySensorActive = false;
873 }
874
Joe Onorato8274a0e2010-10-05 17:38:09 -0400875 if (mSpew) {
876 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
877 + " mWakeLockState=0x"
878 + Integer.toHexString(mWakeLockState)
879 + " previous wakeLockState=0x"
880 + Integer.toHexString(oldWakeLockState));
881 }
882 } else {
883 if (mSpew) {
884 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
885 + " mLocks.gatherState()=0x"
886 + Integer.toHexString(mLocks.gatherState())
887 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
888 }
889 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400891 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
895 if (newlock) {
896 mPartialCount++;
897 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900 }
901 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700904 if (diffsource) {
905 // If the lock sources have changed, need to first release the
906 // old ones.
907 noteStopWakeLocked(wl, oldsource);
908 }
909 if (newlock || diffsource) {
910 noteStartWakeLocked(wl, ws);
911 }
912 }
913
914 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
915 int uid = Binder.getCallingUid();
916 int pid = Binder.getCallingPid();
917 if (ws != null && ws.size() == 0) {
918 ws = null;
919 }
920 if (ws != null) {
921 enforceWakeSourcePermission(uid, pid);
922 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700923 synchronized (mLocks) {
924 int index = mLocks.getIndex(lock);
925 if (index < 0) {
926 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700928 WakeLock wl = mLocks.get(index);
929 WorkSource oldsource = wl.ws;
930 wl.ws = ws != null ? new WorkSource(ws) : null;
931 noteStopWakeLocked(wl, oldsource);
932 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934 }
935
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500936 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700937 int uid = Binder.getCallingUid();
938 if (uid != Process.myUid()) {
939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941
942 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500943 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 }
945 }
946
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500947 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 WakeLock wl = mLocks.removeLock(lock);
949 if (wl == null) {
950 return;
951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800954 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
956 }
957
958 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400959 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
960 mProximityWakeLockCount--;
961 if (mProximityWakeLockCount == 0) {
962 if (mProximitySensorActive &&
963 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
964 // wait for proximity sensor to go negative before disabling sensor
965 if (mDebugProximitySensor) {
966 Slog.d(TAG, "waiting for proximity sensor to go negative");
967 }
968 } else {
969 disableProximityLockLocked();
970 }
971 }
972 } else {
973 mWakeLockState = mLocks.gatherState();
974 // goes in the middle to reduce flicker
975 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
976 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
977 }
978 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
982 mPartialCount--;
983 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800984 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 Power.releaseWakeLock(PARTIAL_NAME);
986 }
987 }
988 // Unlink the lock from the binder.
989 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990
Dianne Hackborn70be1672010-09-14 11:13:03 -0700991 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 private class PokeLock implements IBinder.DeathRecipient
995 {
996 PokeLock(int p, IBinder b, String t) {
997 super();
998 this.pokey = p;
999 this.binder = b;
1000 this.tag = t;
1001 try {
1002 b.linkToDeath(this, 0);
1003 } catch (RemoteException e) {
1004 binderDied();
1005 }
1006 }
1007 public void binderDied() {
1008 setPokeLock(0, this.binder, this.tag);
1009 }
1010 int pokey;
1011 IBinder binder;
1012 String tag;
1013 boolean awakeOnSet;
1014 }
1015
1016 public void setPokeLock(int pokey, IBinder token, String tag) {
1017 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1018 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 return;
1021 }
1022
1023 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1024 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1025 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1026 }
1027
1028 synchronized (mLocks) {
1029 if (pokey != 0) {
1030 PokeLock p = mPokeLocks.get(token);
1031 int oldPokey = 0;
1032 if (p != null) {
1033 oldPokey = p.pokey;
1034 p.pokey = pokey;
1035 } else {
1036 p = new PokeLock(pokey, token, tag);
1037 mPokeLocks.put(token, p);
1038 }
1039 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1040 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1041 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1042 p.awakeOnSet = true;
1043 }
1044 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001045 PokeLock rLock = mPokeLocks.remove(token);
1046 if (rLock != null) {
1047 token.unlinkToDeath(rLock, 0);
1048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
1051 int oldPokey = mPokey;
1052 int cumulative = 0;
1053 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1054 boolean awakeOnSet = false;
1055 for (PokeLock p: mPokeLocks.values()) {
1056 cumulative |= p.pokey;
1057 if (p.awakeOnSet) {
1058 awakeOnSet = true;
1059 }
1060 }
1061 mPokey = cumulative;
1062 mPokeAwakeOnSet = awakeOnSet;
1063
1064 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1065 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 if (oldCumulativeTimeout != newCumulativeTimeout) {
1068 setScreenOffTimeoutsLocked();
1069 // reset the countdown timer, but use the existing nextState so it doesn't
1070 // change anything
1071 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1072 }
1073 }
1074 }
1075
1076 private static String lockType(int type)
1077 {
1078 switch (type)
1079 {
1080 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001081 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001083 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001085 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001087 return "PARTIAL_WAKE_LOCK ";
1088 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1089 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 default:
David Brown251faa62009-08-02 22:04:36 -07001091 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 }
1094
1095 private static String dumpPowerState(int state) {
1096 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1097 ? "KEYBOARD_BRIGHT_BIT " : "")
1098 + (((state & SCREEN_BRIGHT_BIT) != 0)
1099 ? "SCREEN_BRIGHT_BIT " : "")
1100 + (((state & SCREEN_ON_BIT) != 0)
1101 ? "SCREEN_ON_BIT " : "")
1102 + (((state & BATTERY_LOW_BIT) != 0)
1103 ? "BATTERY_LOW_BIT " : "");
1104 }
1105
1106 @Override
1107 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1108 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1109 != PackageManager.PERMISSION_GRANTED) {
1110 pw.println("Permission Denial: can't dump PowerManager from from pid="
1111 + Binder.getCallingPid()
1112 + ", uid=" + Binder.getCallingUid());
1113 return;
1114 }
1115
1116 long now = SystemClock.uptimeMillis();
1117
Mike Lockwoodca44df82010-02-25 13:48:49 -05001118 synchronized (mLocks) {
1119 pw.println("Power Manager State:");
1120 pw.println(" mIsPowered=" + mIsPowered
1121 + " mPowerState=" + mPowerState
1122 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1123 + " ms");
1124 pw.println(" mPartialCount=" + mPartialCount);
1125 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1126 pw.println(" mUserState=" + dumpPowerState(mUserState));
1127 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1128 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1129 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1130 + " " + ((mNextTimeout-now)/1000) + "s from now");
1131 pw.println(" mDimScreen=" + mDimScreen
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001132 + " mStayOnConditions=" + mStayOnConditions
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001133 + " mPreparingForScreenOn=" + mPreparingForScreenOn
1134 + " mSkippedScreenOn=" + mSkippedScreenOn);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001135 pw.println(" mScreenOffReason=" + mScreenOffReason
1136 + " mUserState=" + mUserState);
1137 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1138 + ',' + mBroadcastQueue[2] + "}");
1139 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1140 + ',' + mBroadcastWhy[2] + "}");
1141 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1142 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1143 + " mUserActivityAllowed=" + mUserActivityAllowed);
1144 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1145 + " mScreenOffDelay=" + mScreenOffDelay);
1146 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1147 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1148 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1149 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1150 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1151 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1152 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1153 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1154 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1155 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1156 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1157 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1158 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1159 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1160 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1161 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1162 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1163 pw.println(" mLightSensorValue=" + mLightSensorValue
1164 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001165 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1166 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001167 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1168 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1169 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1170 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1171 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1172 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
Mike Lockwoodca44df82010-02-25 13:48:49 -05001174 int N = mLocks.size();
1175 pw.println();
1176 pw.println("mLocks.size=" + N + ":");
1177 for (int i=0; i<N; i++) {
1178 WakeLock wl = mLocks.get(i);
1179 String type = lockType(wl.flags & LOCK_MASK);
1180 String acquireCausesWakeup = "";
1181 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1182 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1183 }
1184 String activated = "";
1185 if (wl.activated) {
1186 activated = " activated";
1187 }
1188 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001189 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1190 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001192
1193 pw.println();
1194 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1195 for (PokeLock p: mPokeLocks.values()) {
1196 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001197 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1198 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001199 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1200 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1201 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1202 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001204
Mike Lockwoodca44df82010-02-25 13:48:49 -05001205 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
1208
Joe Onorato7999bff2010-07-24 11:50:05 -04001209 private void setTimeoutLocked(long now, int nextState) {
1210 setTimeoutLocked(now, -1, nextState);
1211 }
1212
1213 // If they gave a timeoutOverride it is the number of seconds
1214 // to screen-off. Figure out where in the countdown cycle we
1215 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001216 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1217 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001218 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001219 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001220 long when = 0;
1221 if (timeoutOverride <= 0) {
1222 switch (nextState)
1223 {
1224 case SCREEN_BRIGHT:
1225 when = now + mKeylightDelay;
1226 break;
1227 case SCREEN_DIM:
1228 if (mDimDelay >= 0) {
1229 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001230 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001231 } else {
1232 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1233 }
1234 case SCREEN_OFF:
1235 synchronized (mLocks) {
1236 when = now + mScreenOffDelay;
1237 }
1238 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001239 default:
1240 when = now;
1241 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001243 } else {
1244 override: {
1245 if (timeoutOverride <= mScreenOffDelay) {
1246 when = now + timeoutOverride;
1247 nextState = SCREEN_OFF;
1248 break override;
1249 }
1250 timeoutOverride -= mScreenOffDelay;
1251
1252 if (mDimDelay >= 0) {
1253 if (timeoutOverride <= mDimDelay) {
1254 when = now + timeoutOverride;
1255 nextState = SCREEN_DIM;
1256 break override;
1257 }
1258 timeoutOverride -= mDimDelay;
1259 }
1260
1261 when = now + timeoutOverride;
1262 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001264 }
1265 if (mSpew) {
1266 Slog.d(TAG, "setTimeoutLocked now=" + now
1267 + " timeoutOverride=" + timeoutOverride
1268 + " nextState=" + nextState + " when=" + when);
1269 }
Joe Onorato797e6882010-08-26 14:46:01 -04001270
1271 mHandler.removeCallbacks(mTimeoutTask);
1272 mTimeoutTask.nextState = nextState;
1273 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1274 ? (originalTimeoutOverride - timeoutOverride)
1275 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001276 mHandler.postAtTime(mTimeoutTask, when);
1277 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280 }
1281
1282 private void cancelTimerLocked()
1283 {
1284 mHandler.removeCallbacks(mTimeoutTask);
1285 mTimeoutTask.nextState = -1;
1286 }
1287
1288 private class TimeoutTask implements Runnable
1289 {
1290 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001291 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 public void run()
1293 {
1294 synchronized (mLocks) {
1295 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001296 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
1298
1299 if (nextState == -1) {
1300 return;
1301 }
1302
1303 mUserState = this.nextState;
1304 setPowerState(this.nextState | mWakeLockState);
1305
1306 long now = SystemClock.uptimeMillis();
1307
1308 switch (this.nextState)
1309 {
1310 case SCREEN_BRIGHT:
1311 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001312 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 break;
1314 }
1315 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001316 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 break;
1318 }
1319 }
1320 }
1321 }
1322
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001323 private void sendNotificationLocked(boolean on, int why) {
1324 if (!mInitialized) {
1325 // No notifications sent until first initialization is done.
1326 // This is so that when we are moving from our initial state
1327 // which looks like the screen was off to it being on, we do not
1328 // go through the process of waiting for the higher-level user
1329 // space to be ready before turning up the display brightness.
1330 // (And also do not send needless broadcasts about the screen.)
1331 return;
1332 }
Joe Onorato64c62ba2009-03-24 20:13:57 -07001333 if (!on) {
1334 mStillNeedSleepNotification = false;
1335 }
1336
Joe Onorato128e7292009-03-24 18:41:31 -07001337 // Add to the queue.
1338 int index = 0;
1339 while (mBroadcastQueue[index] != -1) {
1340 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 }
Joe Onorato128e7292009-03-24 18:41:31 -07001342 mBroadcastQueue[index] = on ? 1 : 0;
1343 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344
Joe Onorato128e7292009-03-24 18:41:31 -07001345 // If we added it position 2, then there is a pair that can be stripped.
1346 // If we added it position 1 and we're turning the screen off, we can strip
1347 // the pair and do nothing, because the screen is already off, and therefore
1348 // keyguard has already been enabled.
1349 // However, if we added it at position 1 and we're turning it on, then position
1350 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1351 // on, so have to run the queue then.
1352 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001353 // While we're collapsing them, if it's going off, and the new reason
1354 // is more significant than the first, then use the new one.
1355 if (!on && mBroadcastWhy[0] > why) {
1356 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001357 }
1358 mBroadcastQueue[0] = on ? 1 : 0;
1359 mBroadcastQueue[1] = -1;
1360 mBroadcastQueue[2] = -1;
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001361 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001362 mBroadcastWakeLock.release();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001363 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
Mike Lockwood9c90a372010-04-13 15:40:27 -04001364 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001365 index = 0;
1366 }
1367 if (index == 1 && !on) {
1368 mBroadcastQueue[0] = -1;
1369 mBroadcastQueue[1] = -1;
1370 index = -1;
1371 // The wake lock was being held, but we're not actually going to do any
1372 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001373 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001375 }
1376
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001377 // The broadcast queue has changed; make sure the screen is on if it
1378 // is now possible for it to be.
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001379 if (mSkippedScreenOn) {
1380 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1381 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001382
Joe Onorato128e7292009-03-24 18:41:31 -07001383 // Now send the message.
1384 if (index >= 0) {
1385 // Acquire the broadcast wake lock before changing the power
1386 // state. It will be release after the broadcast is sent.
1387 // We always increment the ref count for each notification in the queue
1388 // and always decrement when that notification is handled.
1389 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001390 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001391 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393 }
1394
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001395 private WindowManagerPolicy.ScreenOnListener mScreenOnListener =
1396 new WindowManagerPolicy.ScreenOnListener() {
1397 @Override public void onScreenOn() {
1398 synchronized (mLocks) {
1399 if (mPreparingForScreenOn) {
1400 mPreparingForScreenOn = false;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001401 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001402 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
1403 4, mBroadcastWakeLock.mCount);
1404 mBroadcastWakeLock.release();
1405 }
1406 }
1407 }
1408 };
1409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 private Runnable mNotificationTask = new Runnable()
1411 {
1412 public void run()
1413 {
Joe Onorato128e7292009-03-24 18:41:31 -07001414 while (true) {
1415 int value;
1416 int why;
1417 WindowManagerPolicy policy;
1418 synchronized (mLocks) {
1419 value = mBroadcastQueue[0];
1420 why = mBroadcastWhy[0];
1421 for (int i=0; i<2; i++) {
1422 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1423 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1424 }
1425 policy = getPolicyLocked();
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001426 if (value == 1 && !mPreparingForScreenOn) {
1427 mPreparingForScreenOn = true;
1428 mBroadcastWakeLock.acquire();
1429 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND,
1430 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
Joe Onorato128e7292009-03-24 18:41:31 -07001433 if (value == 1) {
1434 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001435
Dianne Hackborn38e29a62011-09-18 14:43:08 -07001436 policy.screenTurningOn(mScreenOnListener);
Joe Onorato128e7292009-03-24 18:41:31 -07001437 try {
1438 ActivityManagerNative.getDefault().wakingUp();
1439 } catch (RemoteException e) {
1440 // ignore it
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442
Joe Onorato128e7292009-03-24 18:41:31 -07001443 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001444 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001445 }
1446 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1447 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1448 mScreenOnBroadcastDone, mHandler, 0, null, null);
1449 } else {
1450 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001451 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001452 mBroadcastWakeLock.mCount);
1453 mBroadcastWakeLock.release();
1454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456 }
Joe Onorato128e7292009-03-24 18:41:31 -07001457 else if (value == 0) {
1458 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001459
Joe Onorato128e7292009-03-24 18:41:31 -07001460 policy.screenTurnedOff(why);
1461 try {
1462 ActivityManagerNative.getDefault().goingToSleep();
1463 } catch (RemoteException e) {
1464 // ignore it.
1465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466
Joe Onorato128e7292009-03-24 18:41:31 -07001467 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1468 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1469 mScreenOffBroadcastDone, mHandler, 0, null, null);
1470 } else {
1471 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001473 mBroadcastWakeLock.mCount);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001474 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -07001475 mBroadcastWakeLock.release();
1476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 }
1478 }
Joe Onorato128e7292009-03-24 18:41:31 -07001479 else {
1480 // If we're in this case, then this handler is running for a previous
1481 // paired transaction. mBroadcastWakeLock will already have been released.
1482 break;
1483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485 }
1486 };
1487
1488 long mScreenOnStart;
1489 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1490 public void onReceive(Context context, Intent intent) {
1491 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001492 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1494 mBroadcastWakeLock.release();
1495 }
1496 }
1497 };
1498
1499 long mScreenOffStart;
1500 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1501 public void onReceive(Context context, Intent intent) {
1502 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001503 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
1505 mBroadcastWakeLock.release();
1506 }
1507 }
1508 };
1509
1510 void logPointerUpEvent() {
1511 if (LOG_TOUCH_DOWNS) {
1512 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1513 mLastTouchDown = 0;
1514 }
1515 }
1516
1517 void logPointerDownEvent() {
1518 if (LOG_TOUCH_DOWNS) {
1519 // If we are not already timing a down/up sequence
1520 if (mLastTouchDown == 0) {
1521 mLastTouchDown = SystemClock.elapsedRealtime();
1522 mTouchCycles++;
1523 }
1524 }
1525 }
1526
1527 /**
1528 * Prevents the screen from turning on even if it *should* turn on due
1529 * to a subsequent full wake lock being acquired.
1530 * <p>
1531 * This is a temporary hack that allows an activity to "cover up" any
1532 * display glitches that happen during the activity's startup
1533 * sequence. (Specifically, this API was added to work around a
1534 * cosmetic bug in the "incoming call" sequence, where the lock screen
1535 * would flicker briefly before the incoming call UI became visible.)
1536 * TODO: There ought to be a more elegant way of doing this,
1537 * probably by having the PowerManager and ActivityManager
1538 * work together to let apps specify that the screen on/off
1539 * state should be synchronized with the Activity lifecycle.
1540 * <p>
1541 * Note that calling preventScreenOn(true) will NOT turn the screen
1542 * off if it's currently on. (This API only affects *future*
1543 * acquisitions of full wake locks.)
1544 * But calling preventScreenOn(false) WILL turn the screen on if
1545 * it's currently off because of a prior preventScreenOn(true) call.
1546 * <p>
1547 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1548 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1549 * call doesn't occur within 5 seconds, we'll turn the screen back on
1550 * ourselves (and log a warning about it); this prevents a buggy app
1551 * from disabling the screen forever.)
1552 * <p>
1553 * TODO: this feature should really be controlled by a new type of poke
1554 * lock (rather than an IPowerManager call).
1555 */
1556 public void preventScreenOn(boolean prevent) {
1557 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1558
1559 synchronized (mLocks) {
1560 if (prevent) {
1561 // First of all, grab a partial wake lock to
1562 // make sure the CPU stays on during the entire
1563 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1564 mPreventScreenOnPartialLock.acquire();
1565
1566 // Post a forceReenableScreen() call (for 5 seconds in the
1567 // future) to make sure the matching preventScreenOn(false) call
1568 // has happened by then.
1569 mHandler.removeCallbacks(mForceReenableScreenTask);
1570 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1571
1572 // Finally, set the flag that prevents the screen from turning on.
1573 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001574 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 mPreventScreenOn = true;
1576 } else {
1577 // (Re)enable the screen.
1578 mPreventScreenOn = false;
1579
1580 // We're "undoing" a the prior preventScreenOn(true) call, so we
1581 // no longer need the 5-second safeguard.
1582 mHandler.removeCallbacks(mForceReenableScreenTask);
1583
1584 // Forcibly turn on the screen if it's supposed to be on. (This
1585 // handles the case where the screen is currently off because of
1586 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001587 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1591 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001592 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
1596 }
1597
1598 // Release the partial wake lock that we held during the
1599 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1600 mPreventScreenOnPartialLock.release();
1601 }
1602 }
1603 }
1604
1605 public void setScreenBrightnessOverride(int brightness) {
1606 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1607
Mike Lockwoodf527c712010-06-10 14:12:33 -04001608 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 synchronized (mLocks) {
1610 if (mScreenBrightnessOverride != brightness) {
1611 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001612 if (isScreenOn()) {
1613 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 }
1617 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001618
1619 public void setButtonBrightnessOverride(int brightness) {
1620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1621
Mike Lockwoodf527c712010-06-10 14:12:33 -04001622 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001623 synchronized (mLocks) {
1624 if (mButtonBrightnessOverride != brightness) {
1625 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001626 if (isScreenOn()) {
1627 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1628 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001629 }
1630 }
1631 }
1632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 /**
1634 * Sanity-check that gets called 5 seconds after any call to
1635 * preventScreenOn(true). This ensures that the original call
1636 * is followed promptly by a call to preventScreenOn(false).
1637 */
1638 private void forceReenableScreen() {
1639 // We shouldn't get here at all if mPreventScreenOn is false, since
1640 // we should have already removed any existing
1641 // mForceReenableScreenTask messages...
1642 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 return;
1645 }
1646
1647 // Uh oh. It's been 5 seconds since a call to
1648 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1649 // This means the app that called preventScreenOn(true) is either
1650 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1651 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1652 // crashed before doing so.)
1653
1654 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001655 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 + "Forcing the screen back on...");
1657 preventScreenOn(false);
1658 }
1659
1660 private Runnable mForceReenableScreenTask = new Runnable() {
1661 public void run() {
1662 forceReenableScreen();
1663 }
1664 };
1665
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001666 private int setScreenStateLocked(boolean on) {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001667 if (DEBUG_SCREEN_ON) {
1668 RuntimeException e = new RuntimeException("here");
1669 e.fillInStackTrace();
1670 Slog.i(TAG, "Set screen state: " + on, e);
1671 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001672 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001673 if (err == 0) {
1674 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1675 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001676 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001677 if (!on) {
1678 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001679 mButtonLight.turnOff();
1680 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001681 // clear current value so we will update based on the new conditions
1682 // when the sensor is reenabled.
1683 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001684 // reset our highest light sensor value when the screen turns off
1685 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001686 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001687 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001688 }
1689 return err;
1690 }
1691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 private void setPowerState(int state)
1693 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001694 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696
Mike Lockwood435eb642009-12-03 08:40:18 -05001697 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 {
1699 synchronized (mLocks) {
1700 int err;
1701
1702 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001705 + " noChangeLights=" + noChangeLights
1706 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708
1709 if (noChangeLights) {
1710 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1711 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001712 if (mProximitySensorActive) {
1713 // don't turn on the screen when the proximity sensor lock is held
1714 newState = (newState & ~SCREEN_BRIGHT);
1715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716
1717 if (batteryIsLow()) {
1718 newState |= BATTERY_LOW_BIT;
1719 } else {
1720 newState &= ~BATTERY_LOW_BIT;
1721 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001722 if (newState == mPowerState && mInitialized) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 return;
1724 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001725
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001726 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 newState |= ALL_BRIGHT;
1728 }
1729
1730 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1731 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1732
Mike Lockwood51b84492009-11-16 21:51:18 -05001733 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001734 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001736 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001738 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001740 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001742 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001744 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1746 }
1747
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001748 final boolean stateChanged = mPowerState != newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749
1750 if (oldScreenOn != newScreenOn) {
1751 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001752 // When the user presses the power button, we need to always send out the
1753 // notification that it's going to sleep so the keyguard goes on. But
1754 // we can't do that until the screen fades out, so we don't show the keyguard
1755 // too early.
1756 if (mStillNeedSleepNotification) {
1757 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1758 }
1759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 // Turn on the screen UNLESS there was a prior
1761 // preventScreenOn(true) request. (Note that the lifetime
1762 // of a single preventScreenOn() request is limited to 5
1763 // seconds to prevent a buggy app from disabling the
1764 // screen forever; see forceReenableScreen().)
1765 boolean reallyTurnScreenOn = true;
1766 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001767 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 + mPreventScreenOn);
1769 }
1770
1771 if (mPreventScreenOn) {
1772 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001773 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
1775 reallyTurnScreenOn = false;
1776 }
1777 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001778 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 long identity = Binder.clearCallingIdentity();
1780 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001781 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 mBatteryStats.noteScreenOn();
1783 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001784 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 } finally {
1786 Binder.restoreCallingIdentity(identity);
1787 }
1788 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001789 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 // But continue as if we really did turn the screen on...
1791 err = 0;
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 mLastTouchDown = 0;
1795 mTotalTouchDownTime = 0;
1796 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001797 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 mTotalTouchDownTime, mTouchCycles);
1799 if (err == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 sendNotificationLocked(true, -1);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001801 // Update the lights *after* taking care of turning the
1802 // screen on, so we do this after our notifications are
1803 // enqueued and thus will delay turning on the screen light
1804 // until the windows are correctly displayed.
1805 if (stateChanged) {
1806 updateLightsLocked(newState, 0);
1807 }
1808 mPowerState |= SCREEN_ON_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 } else {
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001812 // Update the lights *before* taking care of turning the
1813 // screen off, so we can initiate any animations that are desired.
1814 if (stateChanged) {
1815 updateLightsLocked(newState, 0);
1816 }
1817
Mike Lockwood497087e32009-11-08 18:33:03 -05001818 // cancel light sensor task
1819 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001820 mLightSensorPendingDecrease = false;
1821 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 mScreenOffTime = SystemClock.elapsedRealtime();
1823 long identity = Binder.clearCallingIdentity();
1824 try {
1825 mBatteryStats.noteScreenOff();
1826 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 } finally {
1829 Binder.restoreCallingIdentity(identity);
1830 }
1831 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001832 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001834 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 err = 0;
1837 mLastTouchDown = 0;
1838 }
1839 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001840 } else if (stateChanged) {
1841 // Screen on/off didn't change, but lights may have.
1842 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001844
1845 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1846
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001847 updateNativePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001848
1849 mInitialized = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001852
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001853 private void updateNativePowerStateLocked() {
1854 nativeSetPowerState(
1855 (mPowerState & SCREEN_ON_BIT) != 0,
1856 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001858
Mike Lockwood435eb642009-12-03 08:40:18 -05001859 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001861 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001863 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1864 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001866 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001868 mScreenOffReason = reason;
1869 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
1871 return err;
1872 }
1873
1874 private boolean batteryIsLow() {
1875 return (!mIsPowered &&
1876 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1877 }
1878
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001879 private boolean shouldDeferScreenOnLocked() {
1880 if (mPreparingForScreenOn) {
1881 // Currently waiting for confirmation from the policy that it
1882 // is okay to turn on the screen. Don't allow the screen to go
1883 // on until that is done.
1884 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1885 "updateLights: delaying screen on due to mPreparingForScreenOn");
1886 return true;
1887 } else {
1888 // If there is a screen-on command in the notification queue, we
1889 // can't turn the screen on until it has been processed (and we
1890 // have set mPreparingForScreenOn) or it has been dropped.
1891 for (int i=0; i<mBroadcastQueue.length; i++) {
1892 if (mBroadcastQueue[i] == 1) {
1893 if (DEBUG_SCREEN_ON) Slog.i(TAG,
1894 "updateLights: delaying screen on due to notification queue");
1895 return true;
1896 }
1897 }
1898 }
1899 return false;
1900 }
1901
The Android Open Source Project10592532009-03-18 17:39:46 -07001902 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001903 final int oldState = mPowerState;
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001904
1905 // If the screen is not currently on, we will want to delay actually
1906 // turning the lights on if we are still getting the UI put up.
1907 if ((oldState&SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
1908 // Don't turn screen on until we know we are really ready to.
1909 // This is to avoid letting the screen go on before things like the
1910 // lock screen have been displayed.
1911 if ((mSkippedScreenOn=shouldDeferScreenOnLocked())) {
1912 newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
1913 }
1914 }
1915
Joe Onorato60607a92010-10-23 14:49:30 -07001916 if ((newState & SCREEN_ON_BIT) != 0) {
1917 // Only turn on the buttons or keyboard if the screen is also on.
1918 // We should never see the buttons on but not the screen.
1919 newState = applyButtonState(newState);
1920 newState = applyKeyboardState(newState);
1921 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001922 final int realDifference = (newState ^ oldState);
1923 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001925 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 int offMask = 0;
1929 int dimMask = 0;
1930 int onMask = 0;
1931
1932 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001935 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1936 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001938 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940 }
1941
1942 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001943 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1944 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001946 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 }
1949
1950 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001951 int nominalCurrentValue = -1;
1952 // If there was an actual difference in the light state, then
1953 // figure out the "ideal" current value based on the previous
1954 // state. Otherwise, this is a change due to the brightness
1955 // override, so we want to animate from whatever the current
1956 // value is.
1957 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1958 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1959 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1960 nominalCurrentValue = preferredBrightness;
1961 break;
1962 case SCREEN_ON_BIT:
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001963 nominalCurrentValue = mScreenBrightnessDim;
Joe Onoratob08a1af2010-10-11 19:28:58 -07001964 break;
1965 case 0:
1966 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1967 break;
1968 case SCREEN_BRIGHT_BIT:
1969 default:
1970 // not possible
1971 nominalCurrentValue = (int)mScreenBrightness.curValue;
1972 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001973 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001974 }
1975 int brightness = preferredBrightness;
1976 int steps = ANIM_STEPS;
1977 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1978 // dim or turn off backlight, depending on if the screen is on
1979 // the scale is because the brightness ramp isn't linear and this biases
1980 // it so the later parts take longer.
1981 final float scale = 1.5f;
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04001982 float ratio = (((float)mScreenBrightnessDim)/preferredBrightness);
Joe Onoratob08a1af2010-10-11 19:28:58 -07001983 if (ratio > 1.0f) ratio = 1.0f;
1984 if ((newState & SCREEN_ON_BIT) == 0) {
1985 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1986 // was bright
1987 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001989 // was dim
1990 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001992 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001994 if ((oldState & SCREEN_ON_BIT) != 0) {
1995 // was bright
1996 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1997 } else {
1998 // was dim
1999 steps = (int)(ANIM_STEPS*ratio);
2000 }
2001 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
2002 // If the "stay on while plugged in" option is
2003 // turned on, then the screen will often not
2004 // automatically turn off while plugged in. To
2005 // still have a sense of when it is inactive, we
2006 // will then count going dim as turning off.
2007 mScreenOffTime = SystemClock.elapsedRealtime();
2008 }
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002009 brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 }
2011 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002012 long identity = Binder.clearCallingIdentity();
2013 try {
2014 mBatteryStats.noteScreenBrightness(brightness);
2015 } catch (RemoteException e) {
2016 // Nothing interesting to do.
2017 } finally {
2018 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002020 mScreenBrightness.setTargetLocked(brightness, steps,
2021 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07002022 if (DEBUG_SCREEN_ON) {
2023 RuntimeException e = new RuntimeException("here");
2024 e.fillInStackTrace();
2025 Slog.i(TAG, "Setting screen brightness: " + brightness, e);
2026 mScreenBrightness.setTargetLocked(brightness, steps,
2027 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
2028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002030
Joe Onorato60607a92010-10-23 14:49:30 -07002031 if (mSpew) {
2032 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
2033 + " dimMask=0x" + Integer.toHexString(dimMask)
2034 + " onMask=0x" + Integer.toHexString(onMask)
2035 + " difference=0x" + Integer.toHexString(difference)
2036 + " realDifference=0x" + Integer.toHexString(realDifference)
2037 + " forceState=0x" + Integer.toHexString(forceState)
2038 );
2039 }
2040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04002042 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002043 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045 if (dimMask != 0) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002046 int brightness = mScreenBrightnessDim;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 if ((newState & BATTERY_LOW_BIT) != 0 &&
2048 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2049 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2050 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002051 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002052 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054 if (onMask != 0) {
2055 int brightness = getPreferredBrightness();
2056 if ((newState & BATTERY_LOW_BIT) != 0 &&
2057 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
2058 brightness = Power.BRIGHTNESS_LOW_BATTERY;
2059 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04002060 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002061 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064
The Android Open Source Project10592532009-03-18 17:39:46 -07002065 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05002066 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05002067 ? LightsService.BRIGHTNESS_MODE_SENSOR
2068 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07002069 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002070 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07002071 }
2072 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002073 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002074 }
2075 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002076 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07002077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
Joe Onoratob08a1af2010-10-11 19:28:58 -07002080 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 boolean initialized;
2084 int targetValue;
2085 float curValue;
2086 float delta;
2087 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 BrightnessState(int m) {
2090 mask = m;
2091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 public void dump(PrintWriter pw, String prefix) {
2094 pw.println(prefix + "animating=" + animating
2095 + " targetValue=" + targetValue
2096 + " curValue=" + curValue
2097 + " delta=" + delta);
2098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002099
Joe Onoratob08a1af2010-10-11 19:28:58 -07002100 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002101 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (!initialized) {
2103 initialized = true;
2104 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002105 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002106 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
2108 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002109 delta = (targetValue -
2110 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2111 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07002113 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002114 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2115 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002116 + " nominalCurrentValue=" + nominalCurrentValue
2117 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002120
2121 if (mSpew) {
2122 Slog.i(TAG, "scheduling light animator");
2123 }
2124 mScreenOffHandler.removeCallbacks(this);
2125 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 boolean stepLocked() {
2129 if (!animating) return false;
2130 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002131 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 + " target=" + targetValue + " delta=" + delta);
2133 }
2134 curValue += delta;
2135 int curIntValue = (int)curValue;
2136 boolean more = true;
2137 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002138 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 more = false;
2140 } else if (delta > 0) {
2141 if (curIntValue >= targetValue) {
2142 curValue = curIntValue = targetValue;
2143 more = false;
2144 }
2145 } else {
2146 if (curIntValue <= targetValue) {
2147 curValue = curIntValue = targetValue;
2148 more = false;
2149 }
2150 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002151 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002152 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002153 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002154 return more;
2155 }
2156
Joe Onorato3d3db602010-10-18 16:08:16 -04002157 void jumpToTargetLocked() {
2158 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002159 setLightBrightness(mask, targetValue);
2160 final int tv = targetValue;
2161 curValue = tv;
2162 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002163 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002164 }
2165
Joe Onorato3d3db602010-10-18 16:08:16 -04002166 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 animating = more;
2168 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002169 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002170 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
2172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002176 if (mAnimateScreenLights) {
2177 synchronized (mLocks) {
2178 long now = SystemClock.uptimeMillis();
2179 boolean more = mScreenBrightness.stepLocked();
2180 if (more) {
2181 mScreenOffHandler.postAtTime(this, now+(1000/60));
2182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002184 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002185 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002186 // we're turning off
2187 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2188 if (animate) {
2189 // It's pretty scary to hold mLocks for this long, and we should
2190 // redesign this, but it works for now.
2191 nativeStartSurfaceFlingerAnimation(
2192 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2193 ? 0 : mAnimationSetting);
2194 }
2195 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
2198 }
2199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 private int getPreferredBrightness() {
2202 try {
2203 if (mScreenBrightnessOverride >= 0) {
2204 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002205 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002206 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002207 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
2209 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2210 SCREEN_BRIGHTNESS);
2211 // Don't let applications turn the screen all the way off
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002212 return Math.max(brightness, mScreenBrightnessDim);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 } catch (SettingNotFoundException snfe) {
2214 return Power.BRIGHTNESS_ON;
2215 }
2216 }
2217
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002218 private int applyButtonState(int state) {
2219 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002220 if ((state & BATTERY_LOW_BIT) != 0) {
2221 // do not override brightness if the battery is low
2222 return state;
2223 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002224 if (mButtonBrightnessOverride >= 0) {
2225 brightness = mButtonBrightnessOverride;
2226 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2227 brightness = mLightSensorButtonBrightness;
2228 }
2229 if (brightness > 0) {
2230 return state | BUTTON_BRIGHT_BIT;
2231 } else if (brightness == 0) {
2232 return state & ~BUTTON_BRIGHT_BIT;
2233 } else {
2234 return state;
2235 }
2236 }
2237
2238 private int applyKeyboardState(int state) {
2239 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002240 if ((state & BATTERY_LOW_BIT) != 0) {
2241 // do not override brightness if the battery is low
2242 return state;
2243 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002244 if (!mKeyboardVisible) {
2245 brightness = 0;
2246 } else if (mButtonBrightnessOverride >= 0) {
2247 brightness = mButtonBrightnessOverride;
2248 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2249 brightness = mLightSensorKeyboardBrightness;
2250 }
2251 if (brightness > 0) {
2252 return state | KEYBOARD_BRIGHT_BIT;
2253 } else if (brightness == 0) {
2254 return state & ~KEYBOARD_BRIGHT_BIT;
2255 } else {
2256 return state;
2257 }
2258 }
2259
Charles Mendis322591c2009-10-29 11:06:59 -07002260 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 synchronized (mLocks) {
2262 return (mPowerState & SCREEN_ON_BIT) != 0;
2263 }
2264 }
2265
Charles Mendis322591c2009-10-29 11:06:59 -07002266 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 synchronized (mLocks) {
2268 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2269 }
2270 }
2271
Mike Lockwood497087e32009-11-08 18:33:03 -05002272 private boolean isScreenTurningOffLocked() {
2273 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2274 }
2275
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002276 private boolean shouldLog(long time) {
2277 synchronized (mLocks) {
2278 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2279 mWarningSpewThrottleTime = time;
2280 mWarningSpewThrottleCount = 0;
2281 return true;
2282 } else if (mWarningSpewThrottleCount < 30) {
2283 mWarningSpewThrottleCount++;
2284 return true;
2285 } else {
2286 return false;
2287 }
2288 }
2289 }
2290
Mike Lockwood200b30b2009-09-20 00:23:59 -04002291 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002292 if (isScreenTurningOffLocked()) {
2293 // cancel animation so userActivity will succeed
2294 mScreenBrightness.animating = false;
2295 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002296 boolean savedActivityAllowed = mUserActivityAllowed;
2297 mUserActivityAllowed = true;
2298 userActivity(SystemClock.uptimeMillis(), false);
2299 mUserActivityAllowed = savedActivityAllowed;
2300 }
2301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002304 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 }
2306
2307 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002308 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2309 != PackageManager.PERMISSION_GRANTED) {
2310 if (shouldLog(time)) {
2311 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2312 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2313 }
2314 return;
2315 }
2316
Joe Onorato7999bff2010-07-24 11:50:05 -04002317 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319
2320 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002321 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323
2324 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002325 userActivity(time, -1, noChangeLights, eventType, force);
2326 }
2327
2328 /*
2329 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2330 * on with user activity. Don't use this function.
2331 */
2332 public void clearUserActivityTimeout(long now, long timeout) {
2333 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2334 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2335 userActivity(now, timeout, false, OTHER_EVENT, false);
2336 }
2337
2338 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2339 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340
Joe Onorato1a542c72010-11-08 09:48:20 -08002341 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002342 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002343 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002344 }
2345 return;
2346 }
2347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 synchronized (mLocks) {
2349 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002350 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 + " mUserActivityAllowed=" + mUserActivityAllowed
2352 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002353 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2354 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002355 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002356 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
Mike Lockwood05067122009-10-27 23:07:25 -04002358 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002359 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002360 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002361 return;
2362 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002363 // Disable proximity sensor if if user presses power key while we are in the
2364 // "waiting for proximity sensor to go negative" state.
2365 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2366 mProximitySensorActive = false;
2367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (mLastEventTime <= time || force) {
2369 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002370 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002371 // Only turn on button backlights if a button was pressed
2372 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002373 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2375 } else {
2376 // don't clear button/keyboard backlights when the screen is touched.
2377 mUserState |= SCREEN_BRIGHT;
2378 }
2379
Dianne Hackborn617f8772009-03-31 15:04:46 -07002380 int uid = Binder.getCallingUid();
2381 long ident = Binder.clearCallingIdentity();
2382 try {
2383 mBatteryStats.noteUserActivity(uid, eventType);
2384 } catch (RemoteException e) {
2385 // Ignore
2386 } finally {
2387 Binder.restoreCallingIdentity(ident);
2388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002389
Michael Chane96440f2009-05-06 10:27:36 -07002390 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002391 setPowerState(mUserState | mWakeLockState, noChangeLights,
2392 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002393 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
2395 }
2396 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002397
2398 if (mPolicy != null) {
2399 mPolicy.userActivity();
2400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 }
2402
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002403 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2404 try {
2405 int i;
2406 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2407 if (sensorValue < mAutoBrightnessLevels[i]) {
2408 break;
2409 }
2410 }
2411 return values[i];
2412 } catch (Exception e) {
2413 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002414 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002415 return 255;
2416 }
2417 }
2418
Mike Lockwood20f87d72009-11-05 16:08:51 -05002419 private Runnable mProximityTask = new Runnable() {
2420 public void run() {
2421 synchronized (mLocks) {
2422 if (mProximityPendingValue != -1) {
2423 proximityChangedLocked(mProximityPendingValue == 1);
2424 mProximityPendingValue = -1;
2425 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002426 if (mProximityPartialLock.isHeld()) {
2427 mProximityPartialLock.release();
2428 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002429 }
2430 }
2431 };
2432
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002433 private Runnable mAutoBrightnessTask = new Runnable() {
2434 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002435 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002436 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2437 int value = (int)mLightSensorPendingValue;
2438 mLightSensorPendingDecrease = false;
2439 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002440 lightSensorChangedLocked(value);
2441 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002442 }
2443 }
2444 };
2445
Mike Lockwoodb2865412010-02-02 22:40:33 -05002446 private void dockStateChanged(int state) {
2447 synchronized (mLocks) {
2448 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2449 if (mIsDocked) {
2450 mHighestLightSensorValue = -1;
2451 }
2452 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2453 // force lights recalculation
2454 int value = (int)mLightSensorValue;
2455 mLightSensorValue = -1;
2456 lightSensorChangedLocked(value);
2457 }
2458 }
2459 }
2460
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002461 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002462 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002463 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002464 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002465
Joe Onorato06eb33a2010-10-25 14:09:21 -07002466 // Don't do anything if the screen is off.
2467 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2468 if (mDebugLightSensor) {
2469 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2470 }
2471 return;
2472 }
2473
Mike Lockwoodb2865412010-02-02 22:40:33 -05002474 // do not allow light sensor value to decrease
2475 if (mHighestLightSensorValue < value) {
2476 mHighestLightSensorValue = value;
2477 }
2478
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002479 if (mLightSensorValue != value) {
2480 mLightSensorValue = value;
2481 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002482 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2483 // we only do this if we are undocked, since lighting should be stable when
2484 // stationary in a dock.
2485 int lcdValue = getAutoBrightnessValue(
2486 (mIsDocked ? value : mHighestLightSensorValue),
2487 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002488 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002489 int keyboardValue;
2490 if (mKeyboardVisible) {
2491 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2492 } else {
2493 keyboardValue = 0;
2494 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002495 mLightSensorScreenBrightness = lcdValue;
2496 mLightSensorButtonBrightness = buttonValue;
2497 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002498
2499 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002500 Slog.d(TAG, "lcdValue " + lcdValue);
2501 Slog.d(TAG, "buttonValue " + buttonValue);
2502 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002503 }
2504
Mike Lockwood4984e732009-11-01 08:16:33 -05002505 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002506 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2507 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002508 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002509 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002510 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002511 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002512 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002513 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002514 }
2515 }
2516 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002517 }
2518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 /**
2520 * The user requested that we go to sleep (probably with the power button).
2521 * This overrides all wake locks that are held.
2522 */
2523 public void goToSleep(long time)
2524 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002525 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2526 }
2527
2528 /**
2529 * The user requested that we go to sleep (probably with the power button).
2530 * This overrides all wake locks that are held.
2531 */
2532 public void goToSleepWithReason(long time, int reason)
2533 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2535 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002536 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
2538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002541 * Reboot the device immediately, passing 'reason' (may be null)
2542 * to the underlying __reboot system call. Should not return.
2543 */
2544 public void reboot(String reason)
2545 {
2546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002547
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002548 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2549 throw new IllegalStateException("Too early to call reboot()");
2550 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002551
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002552 final String finalReason = reason;
2553 Runnable runnable = new Runnable() {
2554 public void run() {
2555 synchronized (this) {
2556 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002557 }
2558
San Mehat1e512792010-01-07 10:40:29 -08002559 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002560 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002561 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002562 mHandler.post(runnable);
2563
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002564 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002565 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002566 while (true) {
2567 try {
2568 runnable.wait();
2569 } catch (InterruptedException e) {
2570 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002571 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002572 }
2573 }
2574
Dan Egnor60d87622009-12-16 16:32:58 -08002575 /**
2576 * Crash the runtime (causing a complete restart of the Android framework).
2577 * Requires REBOOT permission. Mostly for testing. Should not return.
2578 */
2579 public void crash(final String message)
2580 {
2581 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2582 Thread t = new Thread("PowerManagerService.crash()") {
2583 public void run() { throw new RuntimeException(message); }
2584 };
2585 try {
2586 t.start();
2587 t.join();
2588 } catch (InterruptedException e) {
2589 Log.wtf(TAG, e);
2590 }
2591 }
2592
Mike Lockwood435eb642009-12-03 08:40:18 -05002593 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594
2595 if (mLastEventTime <= time) {
2596 mLastEventTime = time;
2597 // cancel all of the wake locks
2598 mWakeLockState = SCREEN_OFF;
2599 int N = mLocks.size();
2600 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002601 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 for (int i=0; i<N; i++) {
2603 WakeLock wl = mLocks.get(i);
2604 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002605 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2606 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2607 proxLock = true;
2608 } else {
2609 mLocks.get(i).activated = false;
2610 numCleared++;
2611 }
2612 }
2613 }
2614 if (!proxLock) {
2615 mProxIgnoredBecauseScreenTurnedOff = true;
2616 if (mDebugProximitySensor) {
2617 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 }
2619 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002620 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002621 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002623 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 cancelTimerLocked();
2625 }
2626 }
2627
2628 public long timeSinceScreenOn() {
2629 synchronized (mLocks) {
2630 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2631 return 0;
2632 }
2633 return SystemClock.elapsedRealtime() - mScreenOffTime;
2634 }
2635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002638 synchronized (mLocks) {
2639 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002640 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002641 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002642 if (mKeyboardVisible != visible) {
2643 mKeyboardVisible = visible;
2644 // don't signal user activity if the screen is off; other code
2645 // will take care of turning on due to a true change to the lid
2646 // switch and synchronized with the lock screen.
2647 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002648 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002649 // force recompute of backlight values
2650 if (mLightSensorValue >= 0) {
2651 int value = (int)mLightSensorValue;
2652 mLightSensorValue = -1;
2653 lightSensorChangedLocked(value);
2654 }
2655 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002656 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2657 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002658 }
2659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 }
2661
2662 /**
2663 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002664 * When disabling user activity we also reset user power state so the keyguard can reset its
2665 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 */
2667 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002668 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002669 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 synchronized (mLocks) {
2672 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002673 if (!enabled) {
2674 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2675 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678 }
2679
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002680 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002681 synchronized (mLocks) {
2682 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2683 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2684 mAutoBrightessEnabled = enabled;
2685 // This will get us a new value
2686 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002687 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002688 }
2689 }
2690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 /** Sets the screen off timeouts:
2692 * mKeylightDelay
2693 * mDimDelay
2694 * mScreenOffDelay
2695 * */
2696 private void setScreenOffTimeoutsLocked() {
2697 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002698 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 mDimDelay = -1;
2700 mScreenOffDelay = 0;
2701 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2702 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2703 mDimDelay = -1;
2704 mScreenOffDelay = 0;
2705 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002706 int totalDelay = mScreenOffTimeoutSetting;
2707 if (totalDelay > mMaximumScreenOffTimeout) {
2708 totalDelay = mMaximumScreenOffTimeout;
2709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2711 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002712 // negative number means stay on as long as possible.
2713 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 } else if (mKeylightDelay < totalDelay) {
2715 // subtract the time that the keylight delay. This will give us the
2716 // remainder of the time that we need to sleep to get the accurate
2717 // screen off timeout.
2718 mScreenOffDelay = totalDelay - mKeylightDelay;
2719 } else {
2720 mScreenOffDelay = 0;
2721 }
2722 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2723 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2724 mScreenOffDelay = LONG_DIM_TIME;
2725 } else {
2726 mDimDelay = -1;
2727 }
2728 }
2729 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002730 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2732 + " mDimScreen=" + mDimScreen);
2733 }
2734 }
2735
2736 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002737 * Refreshes cached secure settings. Called once on startup, and
2738 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 */
Doug Zongker43866e02010-01-07 12:09:54 -08002740 private void updateSettingsValues() {
2741 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002743 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002745 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747
2748 private class LockList extends ArrayList<WakeLock>
2749 {
2750 void addLock(WakeLock wl)
2751 {
2752 int index = getIndex(wl.binder);
2753 if (index < 0) {
2754 this.add(wl);
2755 }
2756 }
2757
2758 WakeLock removeLock(IBinder binder)
2759 {
2760 int index = getIndex(binder);
2761 if (index >= 0) {
2762 return this.remove(index);
2763 } else {
2764 return null;
2765 }
2766 }
2767
2768 int getIndex(IBinder binder)
2769 {
2770 int N = this.size();
2771 for (int i=0; i<N; i++) {
2772 if (this.get(i).binder == binder) {
2773 return i;
2774 }
2775 }
2776 return -1;
2777 }
2778
2779 int gatherState()
2780 {
2781 int result = 0;
2782 int N = this.size();
2783 for (int i=0; i<N; i++) {
2784 WakeLock wl = this.get(i);
2785 if (wl.activated) {
2786 if (isScreenLock(wl.flags)) {
2787 result |= wl.minState;
2788 }
2789 }
2790 }
2791 return result;
2792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002793
Michael Chane96440f2009-05-06 10:27:36 -07002794 int reactivateScreenLocksLocked()
2795 {
2796 int result = 0;
2797 int N = this.size();
2798 for (int i=0; i<N; i++) {
2799 WakeLock wl = this.get(i);
2800 if (isScreenLock(wl.flags)) {
2801 wl.activated = true;
2802 result |= wl.minState;
2803 }
2804 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002805 if (mDebugProximitySensor) {
2806 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2807 + mProxIgnoredBecauseScreenTurnedOff);
2808 }
2809 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002810 return result;
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
2813
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002814 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 synchronized (mLocks) {
2816 mPolicy = p;
2817 mLocks.notifyAll();
2818 }
2819 }
2820
2821 WindowManagerPolicy getPolicyLocked() {
2822 while (mPolicy == null || !mDoneBooting) {
2823 try {
2824 mLocks.wait();
2825 } catch (InterruptedException e) {
2826 // Ignore
2827 }
2828 }
2829 return mPolicy;
2830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002833 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2834 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2835 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002836 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002837 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002838 }
2839
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002840 // wait until sensors are enabled before turning on screen.
2841 // some devices will not activate the light sensor properly on boot
2842 // unless we do this.
2843 if (mUseSoftwareAutoBrightness) {
2844 // turn the screen on
2845 setPowerState(SCREEN_BRIGHT);
2846 } else {
2847 // turn everything on
2848 setPowerState(ALL_BRIGHT);
2849 }
2850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002852 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002854
Joe Onoratod28f7532010-11-06 12:56:53 -07002855 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2856
Dianne Hackborn617f8772009-03-31 15:04:46 -07002857 long identity = Binder.clearCallingIdentity();
2858 try {
2859 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2860 mBatteryStats.noteScreenOn();
2861 } catch (RemoteException e) {
2862 // Nothing interesting to do.
2863 } finally {
2864 Binder.restoreCallingIdentity(identity);
2865 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002866 }
2867 }
2868
2869 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002870 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002871 synchronized (mLocks) {
2872 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2874 updateWakeLockLocked();
2875 mLocks.notifyAll();
2876 }
2877 }
2878
Joe Onoratob08a1af2010-10-11 19:28:58 -07002879 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 public void monitor() {
2881 synchronized (mLocks) { }
2882 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002883
2884 public int getSupportedWakeLockFlags() {
2885 int result = PowerManager.PARTIAL_WAKE_LOCK
2886 | PowerManager.FULL_WAKE_LOCK
2887 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2888
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002889 if (mProximitySensor != null) {
2890 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2891 }
2892
2893 return result;
2894 }
2895
Mike Lockwood237a2992009-09-15 14:42:16 -04002896 public void setBacklightBrightness(int brightness) {
2897 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2898 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002899 synchronized (mLocks) {
Mike Lockwoodeb6456b2011-09-13 15:24:02 -04002900 brightness = Math.max(brightness, mScreenBrightnessDim);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002901 mLcdLight.setBrightness(brightness);
2902 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2903 mButtonLight.setBrightness(brightness);
2904 long identity = Binder.clearCallingIdentity();
2905 try {
2906 mBatteryStats.noteScreenBrightness(brightness);
2907 } catch (RemoteException e) {
2908 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2909 } finally {
2910 Binder.restoreCallingIdentity(identity);
2911 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002912
Joe Onoratob08a1af2010-10-11 19:28:58 -07002913 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002914 synchronized (mLocks) {
2915 mScreenBrightness.targetValue = brightness;
2916 mScreenBrightness.jumpToTargetLocked();
2917 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002918 }
2919 }
2920
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002921 public void setAttentionLight(boolean on, int color) {
2922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002923 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002924 }
2925
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002926 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002927 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002928 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002929 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002930 if (!mProximitySensorEnabled) {
2931 // clear calling identity so sensor manager battery stats are accurate
2932 long identity = Binder.clearCallingIdentity();
2933 try {
2934 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2935 SensorManager.SENSOR_DELAY_NORMAL);
2936 mProximitySensorEnabled = true;
2937 } finally {
2938 Binder.restoreCallingIdentity(identity);
2939 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002940 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002941 }
2942
2943 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002944 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002945 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002946 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002947 if (mProximitySensorEnabled) {
2948 // clear calling identity so sensor manager battery stats are accurate
2949 long identity = Binder.clearCallingIdentity();
2950 try {
2951 mSensorManager.unregisterListener(mProximityListener);
2952 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002953 if (mProximityPartialLock.isHeld()) {
2954 mProximityPartialLock.release();
2955 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002956 mProximitySensorEnabled = false;
2957 } finally {
2958 Binder.restoreCallingIdentity(identity);
2959 }
2960 if (mProximitySensorActive) {
2961 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002962 if (mDebugProximitySensor) {
2963 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2964 + mProxIgnoredBecauseScreenTurnedOff);
2965 }
2966 if (!mProxIgnoredBecauseScreenTurnedOff) {
2967 forceUserActivityLocked();
2968 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002969 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002970 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002971 }
2972
Mike Lockwood20f87d72009-11-05 16:08:51 -05002973 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002974 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002975 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002976 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002977 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002978 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002979 return;
2980 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002981 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002982 if (mDebugProximitySensor) {
2983 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2984 + mProxIgnoredBecauseScreenTurnedOff);
2985 }
2986 if (!mProxIgnoredBecauseScreenTurnedOff) {
2987 goToSleepLocked(SystemClock.uptimeMillis(),
2988 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2989 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002990 mProximitySensorActive = true;
2991 } else {
2992 // proximity sensor negative events trigger as user activity.
2993 // temporarily set mUserActivityAllowed to true so this will work
2994 // even when the keyguard is on.
2995 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002996 if (mDebugProximitySensor) {
2997 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2998 + mProxIgnoredBecauseScreenTurnedOff);
2999 }
3000 if (!mProxIgnoredBecauseScreenTurnedOff) {
3001 forceUserActivityLocked();
3002 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003003
3004 if (mProximityWakeLockCount == 0) {
3005 // disable sensor if we have no listeners left after proximity negative
3006 disableProximityLockLocked();
3007 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003008 }
3009 }
3010
Joe Onoratod28f7532010-11-06 12:56:53 -07003011 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003012 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07003013 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
3014 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
3015 }
3016 if (!mAutoBrightessEnabled) {
3017 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003018 }
3019 if (mSensorManager != null && mLightSensorEnabled != enable) {
3020 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003021 // clear calling identity so sensor manager battery stats are accurate
3022 long identity = Binder.clearCallingIdentity();
3023 try {
3024 if (enable) {
3025 mSensorManager.registerListener(mLightListener, mLightSensor,
3026 SensorManager.SENSOR_DELAY_NORMAL);
3027 } else {
3028 mSensorManager.unregisterListener(mLightListener);
3029 mHandler.removeCallbacks(mAutoBrightnessTask);
3030 }
3031 } finally {
3032 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04003033 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003034 }
3035 }
3036
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003037 SensorEventListener mProximityListener = new SensorEventListener() {
3038 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003039 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003040 synchronized (mLocks) {
3041 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05003042 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
3043 mLastProximityEventTime = milliseconds;
3044 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003045 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05003046
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003047 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05003048 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
3049 distance < mProximitySensor.getMaximumRange());
3050
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003051 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003052 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003053 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003054 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
3055 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
3056 mProximityPendingValue = (active ? 1 : 0);
3057 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003058 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003059 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003060 // process the value immediately
3061 mProximityPendingValue = -1;
3062 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003063 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05003064
3065 // update mProximityPartialLock state
3066 boolean held = mProximityPartialLock.isHeld();
3067 if (!held && proximityTaskQueued) {
3068 // hold wakelock until mProximityTask runs
3069 mProximityPartialLock.acquire();
3070 } else if (held && !proximityTaskQueued) {
3071 mProximityPartialLock.release();
3072 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003073 }
3074 }
3075
3076 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3077 // ignore
3078 }
3079 };
3080
3081 SensorEventListener mLightListener = new SensorEventListener() {
3082 public void onSensorChanged(SensorEvent event) {
3083 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05003084 // ignore light sensor while screen is turning off
3085 if (isScreenTurningOffLocked()) {
3086 return;
3087 }
3088
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003089 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003090 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003091 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003092 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003093 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05003094 if (mLightSensorValue == -1 ||
3095 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3096 // process the value immediately if screen has just turned on
3097 mHandler.removeCallbacks(mAutoBrightnessTask);
3098 mLightSensorPendingDecrease = false;
3099 mLightSensorPendingIncrease = false;
3100 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003101 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003102 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3103 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3104 (value == mLightSensorValue) ||
3105 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3106 // delay processing to debounce the sensor
3107 mHandler.removeCallbacks(mAutoBrightnessTask);
3108 mLightSensorPendingDecrease = (value < mLightSensorValue);
3109 mLightSensorPendingIncrease = (value > mLightSensorValue);
3110 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3111 mLightSensorPendingValue = value;
3112 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3113 }
3114 } else {
3115 mLightSensorPendingValue = value;
3116 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003117 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003118 }
3119 }
3120
3121 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3122 // ignore
3123 }
3124 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125}