blob: bbc26d68977059f64d0964598b86d9b732af42bc [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
82 private static final boolean LOG_PARTIAL_WL = false;
83
84 // Indicates whether touch-down cycles should be logged as part of the
85 // LOG_POWER_SCREEN_STATE log events
86 private static final boolean LOG_TOUCH_DOWNS = true;
87
88 private static final int LOCK_MASK = PowerManager.PARTIAL_WAKE_LOCK
89 | PowerManager.SCREEN_DIM_WAKE_LOCK
90 | PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Mike Lockwoodbc706a02009-07-27 13:50:57 -070091 | PowerManager.FULL_WAKE_LOCK
92 | PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94 // time since last state: time since last event:
Doug Zongker43866e02010-01-07 12:09:54 -080095 // The short keylight delay comes from secure settings; this is the default.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final int SHORT_KEYLIGHT_DELAY_DEFAULT = 6000; // t+6 sec
97 private static final int MEDIUM_KEYLIGHT_DELAY = 15000; // t+15 sec
98 private static final int LONG_KEYLIGHT_DELAY = 6000; // t+6 sec
99 private static final int LONG_DIM_TIME = 7000; // t+N-5 sec
100
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700101 // How long to wait to debounce light sensor changes.
Mike Lockwood9b8136922009-11-06 15:53:59 -0500102 private static final int LIGHT_SENSOR_DELAY = 2000;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700103
Mike Lockwood20f87d72009-11-05 16:08:51 -0500104 // For debouncing the proximity sensor.
105 private static final int PROXIMITY_SENSOR_DELAY = 1000;
106
Mike Lockwoodd20ea362009-09-15 00:13:38 -0400107 // trigger proximity if distance is less than 5 cm
108 private static final float PROXIMITY_THRESHOLD = 5.0f;
109
Doug Zongker43866e02010-01-07 12:09:54 -0800110 // Cached secure settings; see updateSettingsValues()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private int mShortKeylightDelay = SHORT_KEYLIGHT_DELAY_DEFAULT;
112
Amith Yamasani8b619832010-09-22 16:11:59 -0700113 // Default timeout for screen off, if not found in settings database = 15 seconds.
114 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15000;
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 // flags for setPowerState
117 private static final int SCREEN_ON_BIT = 0x00000001;
118 private static final int SCREEN_BRIGHT_BIT = 0x00000002;
119 private static final int BUTTON_BRIGHT_BIT = 0x00000004;
120 private static final int KEYBOARD_BRIGHT_BIT = 0x00000008;
121 private static final int BATTERY_LOW_BIT = 0x00000010;
122
123 // values for setPowerState
124
125 // SCREEN_OFF == everything off
126 private static final int SCREEN_OFF = 0x00000000;
127
128 // SCREEN_DIM == screen on, screen backlight dim
129 private static final int SCREEN_DIM = SCREEN_ON_BIT;
130
131 // SCREEN_BRIGHT == screen on, screen backlight bright
132 private static final int SCREEN_BRIGHT = SCREEN_ON_BIT | SCREEN_BRIGHT_BIT;
133
134 // SCREEN_BUTTON_BRIGHT == screen on, screen and button backlights bright
135 private static final int SCREEN_BUTTON_BRIGHT = SCREEN_BRIGHT | BUTTON_BRIGHT_BIT;
136
137 // SCREEN_BUTTON_BRIGHT == screen on, screen, button and keyboard backlights bright
138 private static final int ALL_BRIGHT = SCREEN_BUTTON_BRIGHT | KEYBOARD_BRIGHT_BIT;
139
140 // used for noChangeLights in setPowerState()
141 private static final int LIGHTS_MASK = SCREEN_BRIGHT_BIT | BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT;
142
Joe Onoratob08a1af2010-10-11 19:28:58 -0700143 boolean mAnimateScreenLights = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 static final int ANIM_STEPS = 60/4;
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400146 // Slower animation for autobrightness changes
147 static final int AUTOBRIGHTNESS_ANIM_STEPS = 60;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 // These magic numbers are the initial state of the LEDs at boot. Ideally
150 // we should read them from the driver, but our current hardware returns 0
151 // for the initial value. Oops!
152 static final int INITIAL_SCREEN_BRIGHTNESS = 255;
153 static final int INITIAL_BUTTON_BRIGHTNESS = Power.BRIGHTNESS_OFF;
154 static final int INITIAL_KEYBOARD_BRIGHTNESS = Power.BRIGHTNESS_OFF;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private final int MY_UID;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700157 private final int MY_PID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
159 private boolean mDoneBooting = false;
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500160 private boolean mBootCompleted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 private int mStayOnConditions = 0;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500162 private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
163 private final int[] mBroadcastWhy = new int[3];
Dianne Hackborn29aae6f2011-08-18 18:30:09 -0700164 private boolean mBroadcastingScreenOff = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private int mPartialCount = 0;
166 private int mPowerState;
Mike Lockwood435eb642009-12-03 08:40:18 -0500167 // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
168 // WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT or WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
169 private int mScreenOffReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 private int mUserState;
171 private boolean mKeyboardVisible = false;
172 private boolean mUserActivityAllowed = true;
Mike Lockwoodee2b0942009-11-09 14:09:02 -0500173 private int mProximityWakeLockCount = 0;
174 private boolean mProximitySensorEnabled = false;
Mike Lockwood36fc3022009-08-25 16:49:06 -0700175 private boolean mProximitySensorActive = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -0500176 private int mProximityPendingValue = -1; // -1 == nothing, 0 == inactive, 1 == active
177 private long mLastProximityEventTime;
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800178 private int mScreenOffTimeoutSetting;
179 private int mMaximumScreenOffTimeout = Integer.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private int mKeylightDelay;
181 private int mDimDelay;
182 private int mScreenOffDelay;
183 private int mWakeLockState;
184 private long mLastEventTime = 0;
185 private long mScreenOffTime;
186 private volatile WindowManagerPolicy mPolicy;
187 private final LockList mLocks = new LockList();
188 private Intent mScreenOffIntent;
189 private Intent mScreenOnIntent;
Mike Lockwood3a322132009-11-24 00:30:52 -0500190 private LightsService mLightsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private Context mContext;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500192 private LightsService.Light mLcdLight;
193 private LightsService.Light mButtonLight;
194 private LightsService.Light mKeyboardLight;
195 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private UnsynchronizedWakeLock mBroadcastWakeLock;
197 private UnsynchronizedWakeLock mStayOnWhilePluggedInScreenDimLock;
198 private UnsynchronizedWakeLock mStayOnWhilePluggedInPartialLock;
199 private UnsynchronizedWakeLock mPreventScreenOnPartialLock;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500200 private UnsynchronizedWakeLock mProximityPartialLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 private HandlerThread mHandlerThread;
Joe Onoratob08a1af2010-10-11 19:28:58 -0700202 private HandlerThread mScreenOffThread;
203 private Handler mScreenOffHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 private Handler mHandler;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500205 private final TimeoutTask mTimeoutTask = new TimeoutTask();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private final BrightnessState mScreenBrightness
The Android Open Source Project10592532009-03-18 17:39:46 -0700207 = new BrightnessState(SCREEN_BRIGHT_BIT);
Joe Onorato128e7292009-03-24 18:41:31 -0700208 private boolean mStillNeedSleepNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private boolean mIsPowered = false;
210 private IActivityManager mActivityService;
211 private IBatteryStats mBatteryStats;
212 private BatteryService mBatteryService;
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700213 private SensorManager mSensorManager;
214 private Sensor mProximitySensor;
Mike Lockwood8738e0c2009-10-04 08:44:47 -0400215 private Sensor mLightSensor;
216 private boolean mLightSensorEnabled;
217 private float mLightSensorValue = -1;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400218 private boolean mProxIgnoredBecauseScreenTurnedOff = false;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500219 private int mHighestLightSensorValue = -1;
Jim Rodovichd102fea2010-09-02 12:30:49 -0500220 private boolean mLightSensorPendingDecrease = false;
221 private boolean mLightSensorPendingIncrease = false;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700222 private float mLightSensorPendingValue = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500223 private int mLightSensorScreenBrightness = -1;
224 private int mLightSensorButtonBrightness = -1;
225 private int mLightSensorKeyboardBrightness = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private boolean mDimScreen = true;
Mike Lockwoodb2865412010-02-02 22:40:33 -0500227 private boolean mIsDocked = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private long mNextTimeout;
229 private volatile int mPokey = 0;
230 private volatile boolean mPokeAwakeOnSet = false;
231 private volatile boolean mInitComplete = false;
Mike Lockwoodca44df82010-02-25 13:48:49 -0500232 private final HashMap<IBinder,PokeLock> mPokeLocks = new HashMap<IBinder,PokeLock>();
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500233 // mLastScreenOnTime is the time the screen was last turned on
234 private long mLastScreenOnTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private boolean mPreventScreenOn;
236 private int mScreenBrightnessOverride = -1;
Mike Lockwoodfb73f792009-11-20 11:31:18 -0500237 private int mButtonBrightnessOverride = -1;
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400238 private boolean mUseSoftwareAutoBrightness;
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700239 private boolean mAutoBrightessEnabled;
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700240 private int[] mAutoBrightnessLevels;
241 private int[] mLcdBacklightValues;
242 private int[] mButtonBacklightValues;
243 private int[] mKeyboardBacklightValues;
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500244 private int mLightSensorWarmupTime;
Joe Onorato6d747652010-10-11 15:15:31 -0700245 boolean mUnplugTurnsOnScreen;
Joe Onorato4b9f62d2010-10-11 13:41:35 -0700246 private int mWarningSpewThrottleCount;
247 private long mWarningSpewThrottleTime;
Joe Onorato609695d2010-10-14 14:57:49 -0700248 private int mAnimationSetting = ANIM_SETTING_OFF;
249
250 // Must match with the ISurfaceComposer constants in C++.
251 private static final int ANIM_SETTING_ON = 0x01;
252 private static final int ANIM_SETTING_OFF = 0x10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 // Used when logging number and duration of touch-down cycles
255 private long mTotalTouchDownTime;
256 private long mLastTouchDown;
257 private int mTouchCycles;
258
259 // could be either static or controllable at runtime
260 private static final boolean mSpew = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -0400261 private static final boolean mDebugProximitySensor = (false || mSpew);
Mike Lockwooddd9668e2009-10-27 15:47:02 -0400262 private static final boolean mDebugLightSensor = (false || mSpew);
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700263
264 private native void nativeInit();
265 private native void nativeSetPowerState(boolean screenOn, boolean screenBright);
Joe Onorato609695d2010-10-14 14:57:49 -0700266 private native void nativeStartSurfaceFlingerAnimation(int mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 /*
269 static PrintStream mLog;
270 static {
271 try {
272 mLog = new PrintStream("/data/power.log");
273 }
274 catch (FileNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800275 android.util.Slog.e(TAG, "Life is hard", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277 }
278 static class Log {
279 static void d(String tag, String s) {
280 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800281 android.util.Slog.d(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283 static void i(String tag, String s) {
284 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800285 android.util.Slog.i(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287 static void w(String tag, String s) {
288 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800289 android.util.Slog.w(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 }
291 static void e(String tag, String s) {
292 mLog.println(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800293 android.util.Slog.e(tag, s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295 }
296 */
297
298 /**
299 * This class works around a deadlock between the lock in PowerManager.WakeLock
300 * and our synchronizing on mLocks. PowerManager.WakeLock synchronizes on its
301 * mToken object so it can be accessed from any thread, but it calls into here
302 * with its lock held. This class is essentially a reimplementation of
303 * PowerManager.WakeLock, but without that extra synchronized block, because we'll
304 * only call it with our own locks held.
305 */
306 private class UnsynchronizedWakeLock {
307 int mFlags;
308 String mTag;
309 IBinder mToken;
310 int mCount = 0;
311 boolean mRefCounted;
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500312 boolean mHeld;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
314 UnsynchronizedWakeLock(int flags, String tag, boolean refCounted) {
315 mFlags = flags;
316 mTag = tag;
317 mToken = new Binder();
318 mRefCounted = refCounted;
319 }
320
321 public void acquire() {
322 if (!mRefCounted || mCount++ == 0) {
323 long ident = Binder.clearCallingIdentity();
324 try {
325 PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700326 MY_UID, MY_PID, mTag, null);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500327 mHeld = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 } finally {
329 Binder.restoreCallingIdentity(ident);
330 }
331 }
332 }
333
334 public void release() {
335 if (!mRefCounted || --mCount == 0) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500336 PowerManagerService.this.releaseWakeLockLocked(mToken, 0, false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500337 mHeld = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
339 if (mCount < 0) {
340 throw new RuntimeException("WakeLock under-locked " + mTag);
341 }
342 }
343
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500344 public boolean isHeld()
345 {
346 return mHeld;
347 }
348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 public String toString() {
350 return "UnsynchronizedWakeLock(mFlags=0x" + Integer.toHexString(mFlags)
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500351 + " mCount=" + mCount + " mHeld=" + mHeld + ")";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 }
353 }
354
355 private final class BatteryReceiver extends BroadcastReceiver {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 synchronized (mLocks) {
359 boolean wasPowered = mIsPowered;
360 mIsPowered = mBatteryService.isPowered();
361
362 if (mIsPowered != wasPowered) {
363 // update mStayOnWhilePluggedIn wake lock
364 updateWakeLockLocked();
365
366 // treat plugging and unplugging the devices as a user activity.
367 // users find it disconcerting when they unplug the device
368 // and it shuts off right away.
Mike Lockwood84a89342010-03-01 21:28:58 -0500369 // to avoid turning on the screen when unplugging, we only trigger
370 // user activity when screen was already on.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 // temporarily set mUserActivityAllowed to true so this will work
372 // even when the keyguard is on.
Joe Onorato6d747652010-10-11 15:15:31 -0700373 // However, you can also set config_unplugTurnsOnScreen to have it
374 // turn on. Some devices want this because they don't have a
375 // charging LED.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 synchronized (mLocks) {
Joe Onorato6d747652010-10-11 15:15:31 -0700377 if (!wasPowered || (mPowerState & SCREEN_ON_BIT) != 0 ||
378 mUnplugTurnsOnScreen) {
Mike Lockwood84a89342010-03-01 21:28:58 -0500379 forceUserActivityLocked();
380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 }
382 }
383 }
384 }
385 }
386
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500387 private final class BootCompletedReceiver extends BroadcastReceiver {
388 @Override
389 public void onReceive(Context context, Intent intent) {
390 bootCompleted();
391 }
392 }
393
Mike Lockwoodb2865412010-02-02 22:40:33 -0500394 private final class DockReceiver extends BroadcastReceiver {
395 @Override
396 public void onReceive(Context context, Intent intent) {
397 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
398 Intent.EXTRA_DOCK_STATE_UNDOCKED);
399 dockStateChanged(state);
400 }
401 }
402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 /**
404 * Set the setting that determines whether the device stays on when plugged in.
405 * The argument is a bit string, with each bit specifying a power source that,
406 * when the device is connected to that source, causes the device to stay on.
407 * See {@link android.os.BatteryManager} for the list of power sources that
408 * can be specified. Current values include {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
409 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
410 * @param val an {@code int} containing the bits that specify which power sources
411 * should cause the device to stay on.
412 */
413 public void setStayOnSetting(int val) {
414 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS, null);
415 Settings.System.putInt(mContext.getContentResolver(),
416 Settings.System.STAY_ON_WHILE_PLUGGED_IN, val);
417 }
418
Dianne Hackborndf83afa2010-01-20 13:37:26 -0800419 public void setMaximumScreenOffTimeount(int timeMs) {
420 mContext.enforceCallingOrSelfPermission(
421 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
422 synchronized (mLocks) {
423 mMaximumScreenOffTimeout = timeMs;
424 // recalculate everything
425 setScreenOffTimeoutsLocked();
426 }
427 }
428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 private class SettingsObserver implements Observer {
Amith Yamasani8b619832010-09-22 16:11:59 -0700430 private int getInt(String name, int defValue) {
431 ContentValues values = mSettings.getValues(name);
432 Integer iVal = values != null ? values.getAsInteger(Settings.System.VALUE) : null;
433 return iVal != null ? iVal : defValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435
Joe Onorato609695d2010-10-14 14:57:49 -0700436 private float getFloat(String name, float defValue) {
437 ContentValues values = mSettings.getValues(name);
438 Float fVal = values != null ? values.getAsFloat(Settings.System.VALUE) : null;
439 return fVal != null ? fVal : defValue;
440 }
441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 public void update(Observable o, Object arg) {
443 synchronized (mLocks) {
Amith Yamasani8b619832010-09-22 16:11:59 -0700444 // STAY_ON_WHILE_PLUGGED_IN, default to when plugged into AC
445 mStayOnConditions = getInt(STAY_ON_WHILE_PLUGGED_IN,
446 BatteryManager.BATTERY_PLUGGED_AC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 updateWakeLockLocked();
448
Amith Yamasani8b619832010-09-22 16:11:59 -0700449 // SCREEN_OFF_TIMEOUT, default to 15 seconds
450 mScreenOffTimeoutSetting = getInt(SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451
Joe Onorato609695d2010-10-14 14:57:49 -0700452 // DIM_SCREEN
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 //mDimScreen = getInt(DIM_SCREEN) != 0;
454
Amith Yamasani8b619832010-09-22 16:11:59 -0700455 // SCREEN_BRIGHTNESS_MODE, default to manual
456 setScreenBrightnessMode(getInt(SCREEN_BRIGHTNESS_MODE,
457 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL));
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 // recalculate everything
460 setScreenOffTimeoutsLocked();
Joe Onorato609695d2010-10-14 14:57:49 -0700461
462 final float windowScale = getFloat(WINDOW_ANIMATION_SCALE, 1.0f);
463 final float transitionScale = getFloat(TRANSITION_ANIMATION_SCALE, 1.0f);
464 mAnimationSetting = 0;
465 if (windowScale > 0.5f) {
466 mAnimationSetting |= ANIM_SETTING_OFF;
467 }
468 if (transitionScale > 0.5f) {
469 // Uncomment this if you want the screen-on animation.
470 // mAnimationSetting |= ANIM_SETTING_ON;
471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 }
473 }
474 }
475
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700476 PowerManagerService() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 // Hack to get our uid... should have a func for this.
478 long token = Binder.clearCallingIdentity();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700479 MY_UID = Process.myUid();
480 MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 Binder.restoreCallingIdentity(token);
482
483 // XXX remove this when the kernel doesn't timeout wake locks
484 Power.setLastUserActivityTimeout(7*24*3600*1000); // one week
485
486 // assume nothing is on yet
487 mUserState = mPowerState = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 // Add ourself to the Watchdog monitors.
490 Watchdog.getInstance().addMonitor(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
492
493 private ContentQueryMap mSettings;
494
Mike Lockwood3a322132009-11-24 00:30:52 -0500495 void init(Context context, LightsService lights, IActivityManager activity,
The Android Open Source Project10592532009-03-18 17:39:46 -0700496 BatteryService battery) {
Mike Lockwood3a322132009-11-24 00:30:52 -0500497 mLightsService = lights;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 mContext = context;
499 mActivityService = activity;
500 mBatteryStats = BatteryStatsService.getService();
501 mBatteryService = battery;
502
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500503 mLcdLight = lights.getLight(LightsService.LIGHT_ID_BACKLIGHT);
504 mButtonLight = lights.getLight(LightsService.LIGHT_ID_BUTTONS);
505 mKeyboardLight = lights.getLight(LightsService.LIGHT_ID_KEYBOARD);
506 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
507
Joe Onoratob08a1af2010-10-11 19:28:58 -0700508 nativeInit();
509 synchronized (mLocks) {
510 updateNativePowerStateLocked();
511 }
512
513 mInitComplete = false;
514 mScreenOffThread = new HandlerThread("PowerManagerService.mScreenOffThread") {
515 @Override
516 protected void onLooperPrepared() {
517 mScreenOffHandler = new Handler();
518 synchronized (mScreenOffThread) {
519 mInitComplete = true;
520 mScreenOffThread.notifyAll();
521 }
522 }
523 };
524 mScreenOffThread.start();
525
526 synchronized (mScreenOffThread) {
527 while (!mInitComplete) {
528 try {
529 mScreenOffThread.wait();
530 } catch (InterruptedException e) {
531 // Ignore
532 }
533 }
534 }
535
536 mInitComplete = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 mHandlerThread = new HandlerThread("PowerManagerService") {
538 @Override
539 protected void onLooperPrepared() {
540 super.onLooperPrepared();
541 initInThread();
542 }
543 };
544 mHandlerThread.start();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 synchronized (mHandlerThread) {
547 while (!mInitComplete) {
548 try {
549 mHandlerThread.wait();
550 } catch (InterruptedException e) {
551 // Ignore
552 }
553 }
554 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700555
556 nativeInit();
557 synchronized (mLocks) {
558 updateNativePowerStateLocked();
559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 void initInThread() {
563 mHandler = new Handler();
564
565 mBroadcastWakeLock = new UnsynchronizedWakeLock(
Joe Onorato128e7292009-03-24 18:41:31 -0700566 PowerManager.PARTIAL_WAKE_LOCK, "sleep_broadcast", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 mStayOnWhilePluggedInScreenDimLock = new UnsynchronizedWakeLock(
568 PowerManager.SCREEN_DIM_WAKE_LOCK, "StayOnWhilePluggedIn Screen Dim", false);
569 mStayOnWhilePluggedInPartialLock = new UnsynchronizedWakeLock(
570 PowerManager.PARTIAL_WAKE_LOCK, "StayOnWhilePluggedIn Partial", false);
571 mPreventScreenOnPartialLock = new UnsynchronizedWakeLock(
572 PowerManager.PARTIAL_WAKE_LOCK, "PreventScreenOn Partial", false);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -0500573 mProximityPartialLock = new UnsynchronizedWakeLock(
574 PowerManager.PARTIAL_WAKE_LOCK, "Proximity Partial", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575
576 mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
577 mScreenOnIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
578 mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
579 mScreenOffIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
580
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700581 Resources resources = mContext.getResources();
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400582
Joe Onoratob08a1af2010-10-11 19:28:58 -0700583 mAnimateScreenLights = resources.getBoolean(
584 com.android.internal.R.bool.config_animateScreenLights);
585
Joe Onorato6d747652010-10-11 15:15:31 -0700586 mUnplugTurnsOnScreen = resources.getBoolean(
587 com.android.internal.R.bool.config_unplugTurnsOnScreen);
588
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400589 // read settings for auto-brightness
590 mUseSoftwareAutoBrightness = resources.getBoolean(
591 com.android.internal.R.bool.config_automatic_brightness_available);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400592 if (mUseSoftwareAutoBrightness) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700593 mAutoBrightnessLevels = resources.getIntArray(
594 com.android.internal.R.array.config_autoBrightnessLevels);
595 mLcdBacklightValues = resources.getIntArray(
596 com.android.internal.R.array.config_autoBrightnessLcdBacklightValues);
597 mButtonBacklightValues = resources.getIntArray(
598 com.android.internal.R.array.config_autoBrightnessButtonBacklightValues);
599 mKeyboardBacklightValues = resources.getIntArray(
600 com.android.internal.R.array.config_autoBrightnessKeyboardBacklightValues);
Mike Lockwood20ee6f22009-11-07 20:33:47 -0500601 mLightSensorWarmupTime = resources.getInteger(
602 com.android.internal.R.integer.config_lightSensorWarmupTime);
Mike Lockwoodd7786b42009-10-15 17:09:16 -0700603 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700604
605 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 Cursor settingsCursor = resolver.query(Settings.System.CONTENT_URI, null,
607 "(" + Settings.System.NAME + "=?) or ("
608 + Settings.System.NAME + "=?) or ("
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700609 + Settings.System.NAME + "=?) or ("
Joe Onorato609695d2010-10-14 14:57:49 -0700610 + Settings.System.NAME + "=?) or ("
611 + Settings.System.NAME + "=?) or ("
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 + Settings.System.NAME + "=?)",
Mike Lockwooddc3494e2009-10-14 21:17:09 -0700613 new String[]{STAY_ON_WHILE_PLUGGED_IN, SCREEN_OFF_TIMEOUT, DIM_SCREEN,
Joe Onorato609695d2010-10-14 14:57:49 -0700614 SCREEN_BRIGHTNESS_MODE, WINDOW_ANIMATION_SCALE, TRANSITION_ANIMATION_SCALE},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 null);
616 mSettings = new ContentQueryMap(settingsCursor, Settings.System.NAME, true, mHandler);
617 SettingsObserver settingsObserver = new SettingsObserver();
618 mSettings.addObserver(settingsObserver);
619
620 // pretend that the settings changed so we will get their initial state
621 settingsObserver.update(mSettings, null);
622
623 // register for the battery changed notifications
624 IntentFilter filter = new IntentFilter();
625 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
626 mContext.registerReceiver(new BatteryReceiver(), filter);
Mike Lockwood2d7bb812009-11-15 18:12:22 -0500627 filter = new IntentFilter();
628 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
629 mContext.registerReceiver(new BootCompletedReceiver(), filter);
Mike Lockwoodb2865412010-02-02 22:40:33 -0500630 filter = new IntentFilter();
631 filter.addAction(Intent.ACTION_DOCK_EVENT);
632 mContext.registerReceiver(new DockReceiver(), filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633
Doug Zongker43866e02010-01-07 12:09:54 -0800634 // Listen for secure settings changes
635 mContext.getContentResolver().registerContentObserver(
636 Settings.Secure.CONTENT_URI, true,
637 new ContentObserver(new Handler()) {
638 public void onChange(boolean selfChange) {
639 updateSettingsValues();
640 }
641 });
642 updateSettingsValues();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 synchronized (mHandlerThread) {
645 mInitComplete = true;
646 mHandlerThread.notifyAll();
647 }
648 }
649
650 private class WakeLock implements IBinder.DeathRecipient
651 {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700652 WakeLock(int f, IBinder b, String t, int u, int p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 super();
654 flags = f;
655 binder = b;
656 tag = t;
657 uid = u == MY_UID ? Process.SYSTEM_UID : u;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700658 pid = p;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 if (u != MY_UID || (
660 !"KEEP_SCREEN_ON_FLAG".equals(tag)
661 && !"KeyInputQueue".equals(tag))) {
662 monitorType = (f & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK
663 ? BatteryStats.WAKE_TYPE_PARTIAL
664 : BatteryStats.WAKE_TYPE_FULL;
665 } else {
666 monitorType = -1;
667 }
668 try {
669 b.linkToDeath(this, 0);
670 } catch (RemoteException e) {
671 binderDied();
672 }
673 }
674 public void binderDied() {
675 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500676 releaseWakeLockLocked(this.binder, 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
678 }
679 final int flags;
680 final IBinder binder;
681 final String tag;
682 final int uid;
Mike Lockwoodf5bd0922010-03-22 17:10:15 -0400683 final int pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 final int monitorType;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700685 WorkSource ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 boolean activated = true;
687 int minState;
688 }
689
690 private void updateWakeLockLocked() {
691 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
692 // keep the device on if we're plugged in and mStayOnWhilePluggedIn is set.
693 mStayOnWhilePluggedInScreenDimLock.acquire();
694 mStayOnWhilePluggedInPartialLock.acquire();
695 } else {
696 mStayOnWhilePluggedInScreenDimLock.release();
697 mStayOnWhilePluggedInPartialLock.release();
698 }
699 }
700
701 private boolean isScreenLock(int flags)
702 {
703 int n = flags & LOCK_MASK;
704 return n == PowerManager.FULL_WAKE_LOCK
705 || n == PowerManager.SCREEN_BRIGHT_WAKE_LOCK
Joe Onorato8274a0e2010-10-05 17:38:09 -0400706 || n == PowerManager.SCREEN_DIM_WAKE_LOCK
707 || n == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
709
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700710 void enforceWakeSourcePermission(int uid, int pid) {
711 if (uid == Process.myUid()) {
712 return;
713 }
714 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
715 pid, uid, null);
716 }
717
718 public void acquireWakeLock(int flags, IBinder lock, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 int uid = Binder.getCallingUid();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700720 int pid = Binder.getCallingPid();
Michael Chane96440f2009-05-06 10:27:36 -0700721 if (uid != Process.myUid()) {
722 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
723 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700724 if (ws != null) {
725 enforceWakeSourcePermission(uid, pid);
726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 long ident = Binder.clearCallingIdentity();
728 try {
729 synchronized (mLocks) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700730 acquireWakeLockLocked(flags, lock, uid, pid, tag, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 }
732 } finally {
733 Binder.restoreCallingIdentity(ident);
734 }
735 }
736
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700737 void noteStartWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700738 if (wl.monitorType >= 0) {
739 long origId = Binder.clearCallingIdentity();
740 try {
741 if (ws != null) {
742 mBatteryStats.noteStartWakelockFromSource(ws, wl.pid, wl.tag,
743 wl.monitorType);
744 } else {
745 mBatteryStats.noteStartWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
746 }
747 } catch (RemoteException e) {
748 // Ignore
749 } finally {
750 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700751 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700752 }
753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700755 void noteStopWakeLocked(WakeLock wl, WorkSource ws) {
Dianne Hackborn70be1672010-09-14 11:13:03 -0700756 if (wl.monitorType >= 0) {
757 long origId = Binder.clearCallingIdentity();
758 try {
759 if (ws != null) {
760 mBatteryStats.noteStopWakelockFromSource(ws, wl.pid, wl.tag,
761 wl.monitorType);
762 } else {
763 mBatteryStats.noteStopWakelock(wl.uid, wl.pid, wl.tag, wl.monitorType);
764 }
765 } catch (RemoteException e) {
766 // Ignore
767 } finally {
768 Binder.restoreCallingIdentity(origId);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700769 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700770 }
771 }
772
773 public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,
774 WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800776 Slog.d(TAG, "acquireWakeLock flags=0x" + Integer.toHexString(flags) + " tag=" + tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700779 if (ws != null && ws.size() == 0) {
780 ws = null;
781 }
782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 int index = mLocks.getIndex(lock);
784 WakeLock wl;
785 boolean newlock;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700786 boolean diffsource;
787 WorkSource oldsource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 if (index < 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700789 wl = new WakeLock(flags, lock, tag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 switch (wl.flags & LOCK_MASK)
791 {
792 case PowerManager.FULL_WAKE_LOCK:
Mike Lockwood4984e732009-11-01 08:16:33 -0500793 if (mUseSoftwareAutoBrightness) {
Mike Lockwood3333fa42009-10-26 14:50:42 -0400794 wl.minState = SCREEN_BRIGHT;
795 } else {
796 wl.minState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 break;
799 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
800 wl.minState = SCREEN_BRIGHT;
801 break;
802 case PowerManager.SCREEN_DIM_WAKE_LOCK:
803 wl.minState = SCREEN_DIM;
804 break;
805 case PowerManager.PARTIAL_WAKE_LOCK:
Mike Lockwoodbc706a02009-07-27 13:50:57 -0700806 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 break;
808 default:
809 // just log and bail. we're in the server, so don't
810 // throw an exception.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 Slog.e(TAG, "bad wakelock type for lock '" + tag + "' "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 + " flags=" + flags);
813 return;
814 }
815 mLocks.addLock(wl);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700816 if (ws != null) {
817 wl.ws = new WorkSource(ws);
818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 newlock = true;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700820 diffsource = false;
821 oldsource = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 } else {
823 wl = mLocks.get(index);
824 newlock = false;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700825 oldsource = wl.ws;
826 if (oldsource != null) {
827 if (ws == null) {
828 wl.ws = null;
829 diffsource = true;
830 } else {
831 diffsource = oldsource.diff(ws);
832 }
833 } else if (ws != null) {
834 diffsource = true;
835 } else {
836 diffsource = false;
837 }
838 if (diffsource) {
839 wl.ws = new WorkSource(ws);
840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
842 if (isScreenLock(flags)) {
843 // if this causes a wakeup, we reactivate all of the locks and
844 // set it to whatever they want. otherwise, we modulate that
845 // by the current state so we never turn it more on than
846 // it already is.
Joe Onorato8274a0e2010-10-05 17:38:09 -0400847 if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
848 mProximityWakeLockCount++;
849 if (mProximityWakeLockCount == 1) {
850 enableProximityLockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 } else {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400853 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
854 int oldWakeLockState = mWakeLockState;
855 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwooddb97f602011-09-02 11:59:08 -0400856
857 // Disable proximity sensor if if user presses power key while we are in the
858 // "waiting for proximity sensor to go negative" state.
859 if ((mWakeLockState & SCREEN_ON_BIT) != 0
860 && mProximitySensorActive && mProximityWakeLockCount == 0) {
861 mProximitySensorActive = false;
862 }
863
Joe Onorato8274a0e2010-10-05 17:38:09 -0400864 if (mSpew) {
865 Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)
866 + " mWakeLockState=0x"
867 + Integer.toHexString(mWakeLockState)
868 + " previous wakeLockState=0x"
869 + Integer.toHexString(oldWakeLockState));
870 }
871 } else {
872 if (mSpew) {
873 Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)
874 + " mLocks.gatherState()=0x"
875 + Integer.toHexString(mLocks.gatherState())
876 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));
877 }
878 mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
Joe Onorato8274a0e2010-10-05 17:38:09 -0400880 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883 else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
884 if (newlock) {
885 mPartialCount++;
886 if (mPartialCount == 1) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800887 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 }
890 Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);
891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700893 if (diffsource) {
894 // If the lock sources have changed, need to first release the
895 // old ones.
896 noteStopWakeLocked(wl, oldsource);
897 }
898 if (newlock || diffsource) {
899 noteStartWakeLocked(wl, ws);
900 }
901 }
902
903 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws) {
904 int uid = Binder.getCallingUid();
905 int pid = Binder.getCallingPid();
906 if (ws != null && ws.size() == 0) {
907 ws = null;
908 }
909 if (ws != null) {
910 enforceWakeSourcePermission(uid, pid);
911 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700912 synchronized (mLocks) {
913 int index = mLocks.getIndex(lock);
914 if (index < 0) {
915 throw new IllegalArgumentException("Wake lock not active");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
Dianne Hackborn70be1672010-09-14 11:13:03 -0700917 WakeLock wl = mLocks.get(index);
918 WorkSource oldsource = wl.ws;
919 wl.ws = ws != null ? new WorkSource(ws) : null;
920 noteStopWakeLocked(wl, oldsource);
921 noteStartWakeLocked(wl, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 }
923 }
924
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500925 public void releaseWakeLock(IBinder lock, int flags) {
Michael Chane96440f2009-05-06 10:27:36 -0700926 int uid = Binder.getCallingUid();
927 if (uid != Process.myUid()) {
928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930
931 synchronized (mLocks) {
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500932 releaseWakeLockLocked(lock, flags, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934 }
935
Mike Lockwood0e39ea82009-11-18 15:37:10 -0500936 private void releaseWakeLockLocked(IBinder lock, int flags, boolean death) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 WakeLock wl = mLocks.removeLock(lock);
938 if (wl == null) {
939 return;
940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800943 Slog.d(TAG, "releaseWakeLock flags=0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 + Integer.toHexString(wl.flags) + " tag=" + wl.tag);
945 }
946
947 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -0400948 if ((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {
949 mProximityWakeLockCount--;
950 if (mProximityWakeLockCount == 0) {
951 if (mProximitySensorActive &&
952 ((flags & PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE) != 0)) {
953 // wait for proximity sensor to go negative before disabling sensor
954 if (mDebugProximitySensor) {
955 Slog.d(TAG, "waiting for proximity sensor to go negative");
956 }
957 } else {
958 disableProximityLockLocked();
959 }
960 }
961 } else {
962 mWakeLockState = mLocks.gatherState();
963 // goes in the middle to reduce flicker
964 if ((wl.flags & PowerManager.ON_AFTER_RELEASE) != 0) {
965 userActivity(SystemClock.uptimeMillis(), -1, false, OTHER_EVENT, false);
966 }
967 setPowerState(mWakeLockState | mUserState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970 else if ((wl.flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {
971 mPartialCount--;
972 if (mPartialCount == 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973 if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 0, wl.tag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 Power.releaseWakeLock(PARTIAL_NAME);
975 }
976 }
977 // Unlink the lock from the binder.
978 wl.binder.unlinkToDeath(wl, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
Dianne Hackborn70be1672010-09-14 11:13:03 -0700980 noteStopWakeLocked(wl, wl.ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 private class PokeLock implements IBinder.DeathRecipient
984 {
985 PokeLock(int p, IBinder b, String t) {
986 super();
987 this.pokey = p;
988 this.binder = b;
989 this.tag = t;
990 try {
991 b.linkToDeath(this, 0);
992 } catch (RemoteException e) {
993 binderDied();
994 }
995 }
996 public void binderDied() {
997 setPokeLock(0, this.binder, this.tag);
998 }
999 int pokey;
1000 IBinder binder;
1001 String tag;
1002 boolean awakeOnSet;
1003 }
1004
1005 public void setPokeLock(int pokey, IBinder token, String tag) {
1006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1007 if (token == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001008 Slog.e(TAG, "setPokeLock got null token for tag='" + tag + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 return;
1010 }
1011
1012 if ((pokey & POKE_LOCK_TIMEOUT_MASK) == POKE_LOCK_TIMEOUT_MASK) {
1013 throw new IllegalArgumentException("setPokeLock can't have both POKE_LOCK_SHORT_TIMEOUT"
1014 + " and POKE_LOCK_MEDIUM_TIMEOUT");
1015 }
1016
1017 synchronized (mLocks) {
1018 if (pokey != 0) {
1019 PokeLock p = mPokeLocks.get(token);
1020 int oldPokey = 0;
1021 if (p != null) {
1022 oldPokey = p.pokey;
1023 p.pokey = pokey;
1024 } else {
1025 p = new PokeLock(pokey, token, tag);
1026 mPokeLocks.put(token, p);
1027 }
1028 int oldTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1029 int newTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
1030 if (((mPowerState & SCREEN_ON_BIT) == 0) && (oldTimeout != newTimeout)) {
1031 p.awakeOnSet = true;
1032 }
1033 } else {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001034 PokeLock rLock = mPokeLocks.remove(token);
1035 if (rLock != null) {
1036 token.unlinkToDeath(rLock, 0);
1037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039
1040 int oldPokey = mPokey;
1041 int cumulative = 0;
1042 boolean oldAwakeOnSet = mPokeAwakeOnSet;
1043 boolean awakeOnSet = false;
1044 for (PokeLock p: mPokeLocks.values()) {
1045 cumulative |= p.pokey;
1046 if (p.awakeOnSet) {
1047 awakeOnSet = true;
1048 }
1049 }
1050 mPokey = cumulative;
1051 mPokeAwakeOnSet = awakeOnSet;
1052
1053 int oldCumulativeTimeout = oldPokey & POKE_LOCK_TIMEOUT_MASK;
1054 int newCumulativeTimeout = pokey & POKE_LOCK_TIMEOUT_MASK;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 if (oldCumulativeTimeout != newCumulativeTimeout) {
1057 setScreenOffTimeoutsLocked();
1058 // reset the countdown timer, but use the existing nextState so it doesn't
1059 // change anything
1060 setTimeoutLocked(SystemClock.uptimeMillis(), mTimeoutTask.nextState);
1061 }
1062 }
1063 }
1064
1065 private static String lockType(int type)
1066 {
1067 switch (type)
1068 {
1069 case PowerManager.FULL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001070 return "FULL_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001072 return "SCREEN_BRIGHT_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 case PowerManager.SCREEN_DIM_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001074 return "SCREEN_DIM_WAKE_LOCK ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 case PowerManager.PARTIAL_WAKE_LOCK:
David Brown251faa62009-08-02 22:04:36 -07001076 return "PARTIAL_WAKE_LOCK ";
1077 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1078 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 default:
David Brown251faa62009-08-02 22:04:36 -07001080 return "??? ";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 }
1083
1084 private static String dumpPowerState(int state) {
1085 return (((state & KEYBOARD_BRIGHT_BIT) != 0)
1086 ? "KEYBOARD_BRIGHT_BIT " : "")
1087 + (((state & SCREEN_BRIGHT_BIT) != 0)
1088 ? "SCREEN_BRIGHT_BIT " : "")
1089 + (((state & SCREEN_ON_BIT) != 0)
1090 ? "SCREEN_ON_BIT " : "")
1091 + (((state & BATTERY_LOW_BIT) != 0)
1092 ? "BATTERY_LOW_BIT " : "");
1093 }
1094
1095 @Override
1096 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1097 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1098 != PackageManager.PERMISSION_GRANTED) {
1099 pw.println("Permission Denial: can't dump PowerManager from from pid="
1100 + Binder.getCallingPid()
1101 + ", uid=" + Binder.getCallingUid());
1102 return;
1103 }
1104
1105 long now = SystemClock.uptimeMillis();
1106
Mike Lockwoodca44df82010-02-25 13:48:49 -05001107 synchronized (mLocks) {
1108 pw.println("Power Manager State:");
1109 pw.println(" mIsPowered=" + mIsPowered
1110 + " mPowerState=" + mPowerState
1111 + " mScreenOffTime=" + (SystemClock.elapsedRealtime()-mScreenOffTime)
1112 + " ms");
1113 pw.println(" mPartialCount=" + mPartialCount);
1114 pw.println(" mWakeLockState=" + dumpPowerState(mWakeLockState));
1115 pw.println(" mUserState=" + dumpPowerState(mUserState));
1116 pw.println(" mPowerState=" + dumpPowerState(mPowerState));
1117 pw.println(" mLocks.gather=" + dumpPowerState(mLocks.gatherState()));
1118 pw.println(" mNextTimeout=" + mNextTimeout + " now=" + now
1119 + " " + ((mNextTimeout-now)/1000) + "s from now");
1120 pw.println(" mDimScreen=" + mDimScreen
1121 + " mStayOnConditions=" + mStayOnConditions);
1122 pw.println(" mScreenOffReason=" + mScreenOffReason
1123 + " mUserState=" + mUserState);
1124 pw.println(" mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
1125 + ',' + mBroadcastQueue[2] + "}");
1126 pw.println(" mBroadcastWhy={" + mBroadcastWhy[0] + ',' + mBroadcastWhy[1]
1127 + ',' + mBroadcastWhy[2] + "}");
1128 pw.println(" mPokey=" + mPokey + " mPokeAwakeonSet=" + mPokeAwakeOnSet);
1129 pw.println(" mKeyboardVisible=" + mKeyboardVisible
1130 + " mUserActivityAllowed=" + mUserActivityAllowed);
1131 pw.println(" mKeylightDelay=" + mKeylightDelay + " mDimDelay=" + mDimDelay
1132 + " mScreenOffDelay=" + mScreenOffDelay);
1133 pw.println(" mPreventScreenOn=" + mPreventScreenOn
1134 + " mScreenBrightnessOverride=" + mScreenBrightnessOverride
1135 + " mButtonBrightnessOverride=" + mButtonBrightnessOverride);
1136 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting
1137 + " mMaximumScreenOffTimeout=" + mMaximumScreenOffTimeout);
1138 pw.println(" mLastScreenOnTime=" + mLastScreenOnTime);
1139 pw.println(" mBroadcastWakeLock=" + mBroadcastWakeLock);
1140 pw.println(" mStayOnWhilePluggedInScreenDimLock=" + mStayOnWhilePluggedInScreenDimLock);
1141 pw.println(" mStayOnWhilePluggedInPartialLock=" + mStayOnWhilePluggedInPartialLock);
1142 pw.println(" mPreventScreenOnPartialLock=" + mPreventScreenOnPartialLock);
1143 pw.println(" mProximityPartialLock=" + mProximityPartialLock);
1144 pw.println(" mProximityWakeLockCount=" + mProximityWakeLockCount);
1145 pw.println(" mProximitySensorEnabled=" + mProximitySensorEnabled);
1146 pw.println(" mProximitySensorActive=" + mProximitySensorActive);
1147 pw.println(" mProximityPendingValue=" + mProximityPendingValue);
1148 pw.println(" mLastProximityEventTime=" + mLastProximityEventTime);
1149 pw.println(" mLightSensorEnabled=" + mLightSensorEnabled);
1150 pw.println(" mLightSensorValue=" + mLightSensorValue
1151 + " mLightSensorPendingValue=" + mLightSensorPendingValue);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001152 pw.println(" mLightSensorPendingDecrease=" + mLightSensorPendingDecrease
1153 + " mLightSensorPendingIncrease=" + mLightSensorPendingIncrease);
Mike Lockwoodca44df82010-02-25 13:48:49 -05001154 pw.println(" mLightSensorScreenBrightness=" + mLightSensorScreenBrightness
1155 + " mLightSensorButtonBrightness=" + mLightSensorButtonBrightness
1156 + " mLightSensorKeyboardBrightness=" + mLightSensorKeyboardBrightness);
1157 pw.println(" mUseSoftwareAutoBrightness=" + mUseSoftwareAutoBrightness);
1158 pw.println(" mAutoBrightessEnabled=" + mAutoBrightessEnabled);
1159 mScreenBrightness.dump(pw, " mScreenBrightness: ");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001160
Mike Lockwoodca44df82010-02-25 13:48:49 -05001161 int N = mLocks.size();
1162 pw.println();
1163 pw.println("mLocks.size=" + N + ":");
1164 for (int i=0; i<N; i++) {
1165 WakeLock wl = mLocks.get(i);
1166 String type = lockType(wl.flags & LOCK_MASK);
1167 String acquireCausesWakeup = "";
1168 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
1169 acquireCausesWakeup = "ACQUIRE_CAUSES_WAKEUP ";
1170 }
1171 String activated = "";
1172 if (wl.activated) {
1173 activated = " activated";
1174 }
1175 pw.println(" " + type + " '" + wl.tag + "'" + acquireCausesWakeup
Mike Lockwoodf5bd0922010-03-22 17:10:15 -04001176 + activated + " (minState=" + wl.minState + ", uid=" + wl.uid
1177 + ", pid=" + wl.pid + ")");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
Mike Lockwoodca44df82010-02-25 13:48:49 -05001179
1180 pw.println();
1181 pw.println("mPokeLocks.size=" + mPokeLocks.size() + ":");
1182 for (PokeLock p: mPokeLocks.values()) {
1183 pw.println(" poke lock '" + p.tag + "':"
Joe Onorato1a542c72010-11-08 09:48:20 -08001184 + ((p.pokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0
1185 ? " POKE_LOCK_IGNORE_TOUCH_EVENTS" : "")
Mike Lockwoodca44df82010-02-25 13:48:49 -05001186 + ((p.pokey & POKE_LOCK_SHORT_TIMEOUT) != 0
1187 ? " POKE_LOCK_SHORT_TIMEOUT" : "")
1188 + ((p.pokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0
1189 ? " POKE_LOCK_MEDIUM_TIMEOUT" : ""));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
Mike Lockwoodca44df82010-02-25 13:48:49 -05001192 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
1195
Joe Onorato7999bff2010-07-24 11:50:05 -04001196 private void setTimeoutLocked(long now, int nextState) {
1197 setTimeoutLocked(now, -1, nextState);
1198 }
1199
1200 // If they gave a timeoutOverride it is the number of seconds
1201 // to screen-off. Figure out where in the countdown cycle we
1202 // should jump to.
Joe Onorato797e6882010-08-26 14:46:01 -04001203 private void setTimeoutLocked(long now, final long originalTimeoutOverride, int nextState) {
1204 long timeoutOverride = originalTimeoutOverride;
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001205 if (mBootCompleted) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001206 synchronized (mLocks) {
Joe Onorato7999bff2010-07-24 11:50:05 -04001207 long when = 0;
1208 if (timeoutOverride <= 0) {
1209 switch (nextState)
1210 {
1211 case SCREEN_BRIGHT:
1212 when = now + mKeylightDelay;
1213 break;
1214 case SCREEN_DIM:
1215 if (mDimDelay >= 0) {
1216 when = now + mDimDelay;
Andreas Huber84047bc2010-07-27 16:49:10 -07001217 break;
Joe Onorato7999bff2010-07-24 11:50:05 -04001218 } else {
1219 Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
1220 }
1221 case SCREEN_OFF:
1222 synchronized (mLocks) {
1223 when = now + mScreenOffDelay;
1224 }
1225 break;
Andreas Huber84047bc2010-07-27 16:49:10 -07001226 default:
1227 when = now;
1228 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001230 } else {
1231 override: {
1232 if (timeoutOverride <= mScreenOffDelay) {
1233 when = now + timeoutOverride;
1234 nextState = SCREEN_OFF;
1235 break override;
1236 }
1237 timeoutOverride -= mScreenOffDelay;
1238
1239 if (mDimDelay >= 0) {
1240 if (timeoutOverride <= mDimDelay) {
1241 when = now + timeoutOverride;
1242 nextState = SCREEN_DIM;
1243 break override;
1244 }
1245 timeoutOverride -= mDimDelay;
1246 }
1247
1248 when = now + timeoutOverride;
1249 nextState = SCREEN_BRIGHT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
Joe Onorato7999bff2010-07-24 11:50:05 -04001251 }
1252 if (mSpew) {
1253 Slog.d(TAG, "setTimeoutLocked now=" + now
1254 + " timeoutOverride=" + timeoutOverride
1255 + " nextState=" + nextState + " when=" + when);
1256 }
Joe Onorato797e6882010-08-26 14:46:01 -04001257
1258 mHandler.removeCallbacks(mTimeoutTask);
1259 mTimeoutTask.nextState = nextState;
1260 mTimeoutTask.remainingTimeoutOverride = timeoutOverride > 0
1261 ? (originalTimeoutOverride - timeoutOverride)
1262 : -1;
Joe Onorato7999bff2010-07-24 11:50:05 -04001263 mHandler.postAtTime(mTimeoutTask, when);
1264 mNextTimeout = when; // for debugging
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
1267 }
1268
1269 private void cancelTimerLocked()
1270 {
1271 mHandler.removeCallbacks(mTimeoutTask);
1272 mTimeoutTask.nextState = -1;
1273 }
1274
1275 private class TimeoutTask implements Runnable
1276 {
1277 int nextState; // access should be synchronized on mLocks
Joe Onorato797e6882010-08-26 14:46:01 -04001278 long remainingTimeoutOverride;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 public void run()
1280 {
1281 synchronized (mLocks) {
1282 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 Slog.d(TAG, "user activity timeout timed out nextState=" + this.nextState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285
1286 if (nextState == -1) {
1287 return;
1288 }
1289
1290 mUserState = this.nextState;
1291 setPowerState(this.nextState | mWakeLockState);
1292
1293 long now = SystemClock.uptimeMillis();
1294
1295 switch (this.nextState)
1296 {
1297 case SCREEN_BRIGHT:
1298 if (mDimDelay >= 0) {
Joe Onorato797e6882010-08-26 14:46:01 -04001299 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_DIM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 break;
1301 }
1302 case SCREEN_DIM:
Joe Onorato797e6882010-08-26 14:46:01 -04001303 setTimeoutLocked(now, remainingTimeoutOverride, SCREEN_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 break;
1305 }
1306 }
1307 }
1308 }
1309
1310 private void sendNotificationLocked(boolean on, int why)
1311 {
Joe Onorato64c62ba2009-03-24 20:13:57 -07001312 if (!on) {
1313 mStillNeedSleepNotification = false;
1314 }
1315
Joe Onorato128e7292009-03-24 18:41:31 -07001316 // Add to the queue.
1317 int index = 0;
1318 while (mBroadcastQueue[index] != -1) {
1319 index++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
Joe Onorato128e7292009-03-24 18:41:31 -07001321 mBroadcastQueue[index] = on ? 1 : 0;
1322 mBroadcastWhy[index] = why;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323
Joe Onorato128e7292009-03-24 18:41:31 -07001324 // If we added it position 2, then there is a pair that can be stripped.
1325 // If we added it position 1 and we're turning the screen off, we can strip
1326 // the pair and do nothing, because the screen is already off, and therefore
1327 // keyguard has already been enabled.
1328 // However, if we added it at position 1 and we're turning it on, then position
1329 // 0 was to turn it off, and we can't strip that, because keyguard needs to come
1330 // on, so have to run the queue then.
1331 if (index == 2) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08001332 // While we're collapsing them, if it's going off, and the new reason
1333 // is more significant than the first, then use the new one.
1334 if (!on && mBroadcastWhy[0] > why) {
1335 mBroadcastWhy[0] = why;
Joe Onorato128e7292009-03-24 18:41:31 -07001336 }
1337 mBroadcastQueue[0] = on ? 1 : 0;
1338 mBroadcastQueue[1] = -1;
1339 mBroadcastQueue[2] = -1;
Mike Lockwood9c90a372010-04-13 15:40:27 -04001340 mBroadcastWakeLock.release();
1341 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001342 index = 0;
1343 }
1344 if (index == 1 && !on) {
1345 mBroadcastQueue[0] = -1;
1346 mBroadcastQueue[1] = -1;
1347 index = -1;
1348 // The wake lock was being held, but we're not actually going to do any
1349 // broadcasts, so release the wake lock.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001350 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 1, mBroadcastWakeLock.mCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 mBroadcastWakeLock.release();
Joe Onorato128e7292009-03-24 18:41:31 -07001352 }
1353
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001354 // The broadcast queue has changed; make sure the screen is on if it
1355 // is now possible for it to be.
1356 updateNativePowerStateLocked();
1357
Joe Onorato128e7292009-03-24 18:41:31 -07001358 // Now send the message.
1359 if (index >= 0) {
1360 // Acquire the broadcast wake lock before changing the power
1361 // state. It will be release after the broadcast is sent.
1362 // We always increment the ref count for each notification in the queue
1363 // and always decrement when that notification is handled.
1364 mBroadcastWakeLock.acquire();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001365 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, mBroadcastWakeLock.mCount);
Joe Onorato128e7292009-03-24 18:41:31 -07001366 mHandler.post(mNotificationTask);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368 }
1369
1370 private Runnable mNotificationTask = new Runnable()
1371 {
1372 public void run()
1373 {
Joe Onorato128e7292009-03-24 18:41:31 -07001374 while (true) {
1375 int value;
1376 int why;
1377 WindowManagerPolicy policy;
1378 synchronized (mLocks) {
1379 value = mBroadcastQueue[0];
1380 why = mBroadcastWhy[0];
1381 for (int i=0; i<2; i++) {
1382 mBroadcastQueue[i] = mBroadcastQueue[i+1];
1383 mBroadcastWhy[i] = mBroadcastWhy[i+1];
1384 }
1385 policy = getPolicyLocked();
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001386 if (value == 0) {
1387 mBroadcastingScreenOff = true;
1388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
Joe Onorato128e7292009-03-24 18:41:31 -07001390 if (value == 1) {
1391 mScreenOnStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001392
Joe Onorato128e7292009-03-24 18:41:31 -07001393 policy.screenTurnedOn();
1394 try {
1395 ActivityManagerNative.getDefault().wakingUp();
1396 } catch (RemoteException e) {
1397 // ignore it
1398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399
Joe Onorato128e7292009-03-24 18:41:31 -07001400 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001401 Slog.d(TAG, "mBroadcastWakeLock=" + mBroadcastWakeLock);
Joe Onorato128e7292009-03-24 18:41:31 -07001402 }
1403 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1404 mContext.sendOrderedBroadcast(mScreenOnIntent, null,
1405 mScreenOnBroadcastDone, mHandler, 0, null, null);
1406 } else {
1407 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001408 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2,
Joe Onorato128e7292009-03-24 18:41:31 -07001409 mBroadcastWakeLock.mCount);
1410 mBroadcastWakeLock.release();
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 }
Joe Onorato128e7292009-03-24 18:41:31 -07001414 else if (value == 0) {
1415 mScreenOffStart = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001416
Joe Onorato128e7292009-03-24 18:41:31 -07001417 policy.screenTurnedOff(why);
1418 try {
1419 ActivityManagerNative.getDefault().goingToSleep();
1420 } catch (RemoteException e) {
1421 // ignore it.
1422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Joe Onorato128e7292009-03-24 18:41:31 -07001424 if (mContext != null && ActivityManagerNative.isSystemReady()) {
1425 mContext.sendOrderedBroadcast(mScreenOffIntent, null,
1426 mScreenOffBroadcastDone, mHandler, 0, null, null);
1427 } else {
1428 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
Joe Onorato128e7292009-03-24 18:41:31 -07001430 mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001431 mBroadcastingScreenOff = false;
1432 updateNativePowerStateLocked();
Joe Onorato128e7292009-03-24 18:41:31 -07001433 mBroadcastWakeLock.release();
1434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 }
Joe Onorato128e7292009-03-24 18:41:31 -07001437 else {
1438 // If we're in this case, then this handler is running for a previous
1439 // paired transaction. mBroadcastWakeLock will already have been released.
1440 break;
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443 }
1444 };
1445
1446 long mScreenOnStart;
1447 private BroadcastReceiver mScreenOnBroadcastDone = new BroadcastReceiver() {
1448 public void onReceive(Context context, Intent intent) {
1449 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001450 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 SystemClock.uptimeMillis() - mScreenOnStart, mBroadcastWakeLock.mCount);
1452 mBroadcastWakeLock.release();
1453 }
1454 }
1455 };
1456
1457 long mScreenOffStart;
1458 private BroadcastReceiver mScreenOffBroadcastDone = new BroadcastReceiver() {
1459 public void onReceive(Context context, Intent intent) {
1460 synchronized (mLocks) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001461 EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 SystemClock.uptimeMillis() - mScreenOffStart, mBroadcastWakeLock.mCount);
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001463 synchronized (mLocks) {
1464 mBroadcastingScreenOff = false;
1465 updateNativePowerStateLocked();
1466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 mBroadcastWakeLock.release();
1468 }
1469 }
1470 };
1471
1472 void logPointerUpEvent() {
1473 if (LOG_TOUCH_DOWNS) {
1474 mTotalTouchDownTime += SystemClock.elapsedRealtime() - mLastTouchDown;
1475 mLastTouchDown = 0;
1476 }
1477 }
1478
1479 void logPointerDownEvent() {
1480 if (LOG_TOUCH_DOWNS) {
1481 // If we are not already timing a down/up sequence
1482 if (mLastTouchDown == 0) {
1483 mLastTouchDown = SystemClock.elapsedRealtime();
1484 mTouchCycles++;
1485 }
1486 }
1487 }
1488
1489 /**
1490 * Prevents the screen from turning on even if it *should* turn on due
1491 * to a subsequent full wake lock being acquired.
1492 * <p>
1493 * This is a temporary hack that allows an activity to "cover up" any
1494 * display glitches that happen during the activity's startup
1495 * sequence. (Specifically, this API was added to work around a
1496 * cosmetic bug in the "incoming call" sequence, where the lock screen
1497 * would flicker briefly before the incoming call UI became visible.)
1498 * TODO: There ought to be a more elegant way of doing this,
1499 * probably by having the PowerManager and ActivityManager
1500 * work together to let apps specify that the screen on/off
1501 * state should be synchronized with the Activity lifecycle.
1502 * <p>
1503 * Note that calling preventScreenOn(true) will NOT turn the screen
1504 * off if it's currently on. (This API only affects *future*
1505 * acquisitions of full wake locks.)
1506 * But calling preventScreenOn(false) WILL turn the screen on if
1507 * it's currently off because of a prior preventScreenOn(true) call.
1508 * <p>
1509 * Any call to preventScreenOn(true) MUST be followed promptly by a call
1510 * to preventScreenOn(false). In fact, if the preventScreenOn(false)
1511 * call doesn't occur within 5 seconds, we'll turn the screen back on
1512 * ourselves (and log a warning about it); this prevents a buggy app
1513 * from disabling the screen forever.)
1514 * <p>
1515 * TODO: this feature should really be controlled by a new type of poke
1516 * lock (rather than an IPowerManager call).
1517 */
1518 public void preventScreenOn(boolean prevent) {
1519 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1520
1521 synchronized (mLocks) {
1522 if (prevent) {
1523 // First of all, grab a partial wake lock to
1524 // make sure the CPU stays on during the entire
1525 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1526 mPreventScreenOnPartialLock.acquire();
1527
1528 // Post a forceReenableScreen() call (for 5 seconds in the
1529 // future) to make sure the matching preventScreenOn(false) call
1530 // has happened by then.
1531 mHandler.removeCallbacks(mForceReenableScreenTask);
1532 mHandler.postDelayed(mForceReenableScreenTask, 5000);
1533
1534 // Finally, set the flag that prevents the screen from turning on.
1535 // (Below, in setPowerState(), we'll check mPreventScreenOn and
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001536 // we *won't* call setScreenStateLocked(true) if it's set.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 mPreventScreenOn = true;
1538 } else {
1539 // (Re)enable the screen.
1540 mPreventScreenOn = false;
1541
1542 // We're "undoing" a the prior preventScreenOn(true) call, so we
1543 // no longer need the 5-second safeguard.
1544 mHandler.removeCallbacks(mForceReenableScreenTask);
1545
1546 // Forcibly turn on the screen if it's supposed to be on. (This
1547 // handles the case where the screen is currently off because of
1548 // a prior preventScreenOn(true) call.)
Mike Lockwoode090281422009-11-14 21:02:56 -05001549 if (!mProximitySensorActive && (mPowerState & SCREEN_ON_BIT) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 Slog.d(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 "preventScreenOn: turning on after a prior preventScreenOn(true)!");
1553 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001554 int err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if (err != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001556 Slog.w(TAG, "preventScreenOn: error from setScreenStateLocked(): " + err);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 }
1559
1560 // Release the partial wake lock that we held during the
1561 // preventScreenOn(true) -> preventScreenOn(false) sequence.
1562 mPreventScreenOnPartialLock.release();
1563 }
1564 }
1565 }
1566
1567 public void setScreenBrightnessOverride(int brightness) {
1568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1569
Mike Lockwoodf527c712010-06-10 14:12:33 -04001570 if (mSpew) Slog.d(TAG, "setScreenBrightnessOverride " + brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 synchronized (mLocks) {
1572 if (mScreenBrightnessOverride != brightness) {
1573 mScreenBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001574 if (isScreenOn()) {
1575 updateLightsLocked(mPowerState, SCREEN_ON_BIT);
1576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 }
1579 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001580
1581 public void setButtonBrightnessOverride(int brightness) {
1582 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
1583
Mike Lockwoodf527c712010-06-10 14:12:33 -04001584 if (mSpew) Slog.d(TAG, "setButtonBrightnessOverride " + brightness);
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001585 synchronized (mLocks) {
1586 if (mButtonBrightnessOverride != brightness) {
1587 mButtonBrightnessOverride = brightness;
Mike Lockwoodf527c712010-06-10 14:12:33 -04001588 if (isScreenOn()) {
1589 updateLightsLocked(mPowerState, BUTTON_BRIGHT_BIT | KEYBOARD_BRIGHT_BIT);
1590 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001591 }
1592 }
1593 }
1594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 /**
1596 * Sanity-check that gets called 5 seconds after any call to
1597 * preventScreenOn(true). This ensures that the original call
1598 * is followed promptly by a call to preventScreenOn(false).
1599 */
1600 private void forceReenableScreen() {
1601 // We shouldn't get here at all if mPreventScreenOn is false, since
1602 // we should have already removed any existing
1603 // mForceReenableScreenTask messages...
1604 if (!mPreventScreenOn) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 Slog.w(TAG, "forceReenableScreen: mPreventScreenOn is false, nothing to do");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 return;
1607 }
1608
1609 // Uh oh. It's been 5 seconds since a call to
1610 // preventScreenOn(true) and we haven't re-enabled the screen yet.
1611 // This means the app that called preventScreenOn(true) is either
1612 // slow (i.e. it took more than 5 seconds to call preventScreenOn(false)),
1613 // or buggy (i.e. it forgot to call preventScreenOn(false), or
1614 // crashed before doing so.)
1615
1616 // Log a warning, and forcibly turn the screen back on.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 Slog.w(TAG, "App called preventScreenOn(true) but didn't promptly reenable the screen! "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 + "Forcing the screen back on...");
1619 preventScreenOn(false);
1620 }
1621
1622 private Runnable mForceReenableScreenTask = new Runnable() {
1623 public void run() {
1624 forceReenableScreen();
1625 }
1626 };
1627
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001628 private int setScreenStateLocked(boolean on) {
1629 int err = Power.setScreenState(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001630 if (err == 0) {
1631 mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
1632 if (mUseSoftwareAutoBrightness) {
Joe Onoratod28f7532010-11-06 12:56:53 -07001633 enableLightSensorLocked(on);
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001634 if (!on) {
1635 // make sure button and key backlights are off too
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001636 mButtonLight.turnOff();
1637 mKeyboardLight.turnOff();
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001638 // clear current value so we will update based on the new conditions
1639 // when the sensor is reenabled.
1640 mLightSensorValue = -1;
Mike Lockwoodb2865412010-02-02 22:40:33 -05001641 // reset our highest light sensor value when the screen turns off
1642 mHighestLightSensorValue = -1;
Mike Lockwood20ee6f22009-11-07 20:33:47 -05001643 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07001644 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001645 }
1646 return err;
1647 }
1648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 private void setPowerState(int state)
1650 {
Mike Lockwood435eb642009-12-03 08:40:18 -05001651 setPowerState(state, false, WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653
Mike Lockwood435eb642009-12-03 08:40:18 -05001654 private void setPowerState(int newState, boolean noChangeLights, int reason)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 {
1656 synchronized (mLocks) {
1657 int err;
1658
1659 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001660 Slog.d(TAG, "setPowerState: mPowerState=0x" + Integer.toHexString(mPowerState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 + " newState=0x" + Integer.toHexString(newState)
Mike Lockwood435eb642009-12-03 08:40:18 -05001662 + " noChangeLights=" + noChangeLights
1663 + " reason=" + reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665
1666 if (noChangeLights) {
1667 newState = (newState & ~LIGHTS_MASK) | (mPowerState & LIGHTS_MASK);
1668 }
Mike Lockwood36fc3022009-08-25 16:49:06 -07001669 if (mProximitySensorActive) {
1670 // don't turn on the screen when the proximity sensor lock is held
1671 newState = (newState & ~SCREEN_BRIGHT);
1672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673
1674 if (batteryIsLow()) {
1675 newState |= BATTERY_LOW_BIT;
1676 } else {
1677 newState &= ~BATTERY_LOW_BIT;
1678 }
1679 if (newState == mPowerState) {
1680 return;
1681 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001682
Mike Lockwood2d7bb812009-11-15 18:12:22 -05001683 if (!mBootCompleted && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 newState |= ALL_BRIGHT;
1685 }
1686
1687 boolean oldScreenOn = (mPowerState & SCREEN_ON_BIT) != 0;
1688 boolean newScreenOn = (newState & SCREEN_ON_BIT) != 0;
1689
Mike Lockwood51b84492009-11-16 21:51:18 -05001690 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001691 Slog.d(TAG, "setPowerState: mPowerState=" + mPowerState
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 + " newState=" + newState + " noChangeLights=" + noChangeLights);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001693 Slog.d(TAG, " oldKeyboardBright=" + ((mPowerState & KEYBOARD_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 + " newKeyboardBright=" + ((newState & KEYBOARD_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001695 Slog.d(TAG, " oldScreenBright=" + ((mPowerState & SCREEN_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 + " newScreenBright=" + ((newState & SCREEN_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001697 Slog.d(TAG, " oldButtonBright=" + ((mPowerState & BUTTON_BRIGHT_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 + " newButtonBright=" + ((newState & BUTTON_BRIGHT_BIT) != 0));
Joe Onorato8a9b2202010-02-26 18:56:32 -08001699 Slog.d(TAG, " oldScreenOn=" + oldScreenOn
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 + " newScreenOn=" + newScreenOn);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001701 Slog.d(TAG, " oldBatteryLow=" + ((mPowerState & BATTERY_LOW_BIT) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
1703 }
1704
1705 if (mPowerState != newState) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001706 updateLightsLocked(newState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
1708 }
1709
1710 if (oldScreenOn != newScreenOn) {
1711 if (newScreenOn) {
Joe Onorato128e7292009-03-24 18:41:31 -07001712 // When the user presses the power button, we need to always send out the
1713 // notification that it's going to sleep so the keyguard goes on. But
1714 // we can't do that until the screen fades out, so we don't show the keyguard
1715 // too early.
1716 if (mStillNeedSleepNotification) {
1717 sendNotificationLocked(false, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1718 }
1719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 // Turn on the screen UNLESS there was a prior
1721 // preventScreenOn(true) request. (Note that the lifetime
1722 // of a single preventScreenOn() request is limited to 5
1723 // seconds to prevent a buggy app from disabling the
1724 // screen forever; see forceReenableScreen().)
1725 boolean reallyTurnScreenOn = true;
1726 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001727 Slog.d(TAG, "- turning screen on... mPreventScreenOn = "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 + mPreventScreenOn);
1729 }
1730
1731 if (mPreventScreenOn) {
1732 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001733 Slog.d(TAG, "- PREVENTING screen from really turning on!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735 reallyTurnScreenOn = false;
1736 }
1737 if (reallyTurnScreenOn) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001738 err = setScreenStateLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 long identity = Binder.clearCallingIdentity();
1740 try {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05001741 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 mBatteryStats.noteScreenOn();
1743 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001744 Slog.w(TAG, "RemoteException calling noteScreenOn on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 } finally {
1746 Binder.restoreCallingIdentity(identity);
1747 }
1748 } else {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001749 setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 // But continue as if we really did turn the screen on...
1751 err = 0;
1752 }
1753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 mLastTouchDown = 0;
1755 mTotalTouchDownTime = 0;
1756 mTouchCycles = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001757 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 mTotalTouchDownTime, mTouchCycles);
1759 if (err == 0) {
1760 mPowerState |= SCREEN_ON_BIT;
1761 sendNotificationLocked(true, -1);
1762 }
1763 } else {
Mike Lockwood497087e32009-11-08 18:33:03 -05001764 // cancel light sensor task
1765 mHandler.removeCallbacks(mAutoBrightnessTask);
Jim Rodovichd102fea2010-09-02 12:30:49 -05001766 mLightSensorPendingDecrease = false;
1767 mLightSensorPendingIncrease = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 mScreenOffTime = SystemClock.elapsedRealtime();
1769 long identity = Binder.clearCallingIdentity();
1770 try {
1771 mBatteryStats.noteScreenOff();
1772 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001773 Slog.w(TAG, "RemoteException calling noteScreenOff on BatteryStatsService", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 } finally {
1775 Binder.restoreCallingIdentity(identity);
1776 }
1777 mPowerState &= ~SCREEN_ON_BIT;
Mike Lockwood435eb642009-12-03 08:40:18 -05001778 mScreenOffReason = reason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 if (!mScreenBrightness.animating) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001780 err = screenOffFinishedAnimatingLocked(reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 err = 0;
1783 mLastTouchDown = 0;
1784 }
1785 }
1786 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001787
1788 updateNativePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001791
1792 private void updateNativePowerStateLocked() {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07001793 if ((mPowerState & SCREEN_ON_BIT) != 0) {
1794 // Don't turn screen on if we are currently reporting a screen off.
1795 // This is to avoid letting the screen go on before things like the
1796 // lock screen have been displayed due to it going off.
1797 if (mBroadcastingScreenOff) {
1798 // Currently broadcasting that the screen is off. Don't
1799 // allow screen to go on until that is done.
1800 return;
1801 }
1802 for (int i=0; i<mBroadcastQueue.length; i++) {
1803 if (mBroadcastQueue[i] == 0) {
1804 // A screen off is currently enqueued.
1805 return;
1806 }
1807 }
1808 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001809 nativeSetPowerState(
1810 (mPowerState & SCREEN_ON_BIT) != 0,
1811 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
1812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001813
Mike Lockwood435eb642009-12-03 08:40:18 -05001814 private int screenOffFinishedAnimatingLocked(int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 // I don't think we need to check the current state here because all of these
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001816 // Power.setScreenState and sendNotificationLocked can both handle being
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 // called multiple times in the same state. -joeo
Joe Onoratob08a1af2010-10-11 19:28:58 -07001818 EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, reason, mTotalTouchDownTime,
1819 mTouchCycles);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 mLastTouchDown = 0;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04001821 int err = setScreenStateLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (err == 0) {
Mike Lockwood435eb642009-12-03 08:40:18 -05001823 mScreenOffReason = reason;
1824 sendNotificationLocked(false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
1826 return err;
1827 }
1828
1829 private boolean batteryIsLow() {
1830 return (!mIsPowered &&
1831 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
1832 }
1833
The Android Open Source Project10592532009-03-18 17:39:46 -07001834 private void updateLightsLocked(int newState, int forceState) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001835 final int oldState = mPowerState;
Joe Onorato60607a92010-10-23 14:49:30 -07001836 if ((newState & SCREEN_ON_BIT) != 0) {
1837 // Only turn on the buttons or keyboard if the screen is also on.
1838 // We should never see the buttons on but not the screen.
1839 newState = applyButtonState(newState);
1840 newState = applyKeyboardState(newState);
1841 }
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07001842 final int realDifference = (newState ^ oldState);
1843 final int difference = realDifference | forceState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 if (difference == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001845 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 int offMask = 0;
1849 int dimMask = 0;
1850 int onMask = 0;
1851
1852 int preferredBrightness = getPreferredBrightness();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if ((difference & KEYBOARD_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001855 if ((newState & KEYBOARD_BRIGHT_BIT) == 0) {
1856 offMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001858 onMask |= KEYBOARD_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860 }
1861
1862 if ((difference & BUTTON_BRIGHT_BIT) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001863 if ((newState & BUTTON_BRIGHT_BIT) == 0) {
1864 offMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001866 onMask |= BUTTON_BRIGHT_BIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868 }
1869
1870 if ((difference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001871 int nominalCurrentValue = -1;
1872 // If there was an actual difference in the light state, then
1873 // figure out the "ideal" current value based on the previous
1874 // state. Otherwise, this is a change due to the brightness
1875 // override, so we want to animate from whatever the current
1876 // value is.
1877 if ((realDifference & (SCREEN_ON_BIT | SCREEN_BRIGHT_BIT)) != 0) {
1878 switch (oldState & (SCREEN_BRIGHT_BIT|SCREEN_ON_BIT)) {
1879 case SCREEN_BRIGHT_BIT | SCREEN_ON_BIT:
1880 nominalCurrentValue = preferredBrightness;
1881 break;
1882 case SCREEN_ON_BIT:
1883 nominalCurrentValue = Power.BRIGHTNESS_DIM;
1884 break;
1885 case 0:
1886 nominalCurrentValue = Power.BRIGHTNESS_OFF;
1887 break;
1888 case SCREEN_BRIGHT_BIT:
1889 default:
1890 // not possible
1891 nominalCurrentValue = (int)mScreenBrightness.curValue;
1892 break;
Joe Onorato128e7292009-03-24 18:41:31 -07001893 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001894 }
1895 int brightness = preferredBrightness;
1896 int steps = ANIM_STEPS;
1897 if ((newState & SCREEN_BRIGHT_BIT) == 0) {
1898 // dim or turn off backlight, depending on if the screen is on
1899 // the scale is because the brightness ramp isn't linear and this biases
1900 // it so the later parts take longer.
1901 final float scale = 1.5f;
1902 float ratio = (((float)Power.BRIGHTNESS_DIM)/preferredBrightness);
1903 if (ratio > 1.0f) ratio = 1.0f;
1904 if ((newState & SCREEN_ON_BIT) == 0) {
1905 if ((oldState & SCREEN_BRIGHT_BIT) != 0) {
1906 // was bright
1907 steps = ANIM_STEPS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001909 // was dim
1910 steps = (int)(ANIM_STEPS*ratio*scale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001912 brightness = Power.BRIGHTNESS_OFF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07001914 if ((oldState & SCREEN_ON_BIT) != 0) {
1915 // was bright
1916 steps = (int)(ANIM_STEPS*(1.0f-ratio)*scale);
1917 } else {
1918 // was dim
1919 steps = (int)(ANIM_STEPS*ratio);
1920 }
1921 if (mStayOnConditions != 0 && mBatteryService.isPowered(mStayOnConditions)) {
1922 // If the "stay on while plugged in" option is
1923 // turned on, then the screen will often not
1924 // automatically turn off while plugged in. To
1925 // still have a sense of when it is inactive, we
1926 // will then count going dim as turning off.
1927 mScreenOffTime = SystemClock.elapsedRealtime();
1928 }
1929 brightness = Power.BRIGHTNESS_DIM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
1931 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001932 long identity = Binder.clearCallingIdentity();
1933 try {
1934 mBatteryStats.noteScreenBrightness(brightness);
1935 } catch (RemoteException e) {
1936 // Nothing interesting to do.
1937 } finally {
1938 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07001940 mScreenBrightness.setTargetLocked(brightness, steps,
1941 INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001943
Joe Onorato60607a92010-10-23 14:49:30 -07001944 if (mSpew) {
1945 Slog.d(TAG, "offMask=0x" + Integer.toHexString(offMask)
1946 + " dimMask=0x" + Integer.toHexString(dimMask)
1947 + " onMask=0x" + Integer.toHexString(onMask)
1948 + " difference=0x" + Integer.toHexString(difference)
1949 + " realDifference=0x" + Integer.toHexString(realDifference)
1950 + " forceState=0x" + Integer.toHexString(forceState)
1951 );
1952 }
1953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 if (offMask != 0) {
Mike Lockwood48358bd2010-04-17 22:29:20 -04001955 if (mSpew) Slog.i(TAG, "Setting brightess off: " + offMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001956 setLightBrightness(offMask, Power.BRIGHTNESS_OFF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
1958 if (dimMask != 0) {
1959 int brightness = Power.BRIGHTNESS_DIM;
1960 if ((newState & BATTERY_LOW_BIT) != 0 &&
1961 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1962 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1963 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001964 if (mSpew) Slog.i(TAG, "Setting brightess dim " + brightness + ": " + dimMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001965 setLightBrightness(dimMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 if (onMask != 0) {
1968 int brightness = getPreferredBrightness();
1969 if ((newState & BATTERY_LOW_BIT) != 0 &&
1970 brightness > Power.BRIGHTNESS_LOW_BATTERY) {
1971 brightness = Power.BRIGHTNESS_LOW_BATTERY;
1972 }
Mike Lockwood48358bd2010-04-17 22:29:20 -04001973 if (mSpew) Slog.i(TAG, "Setting brightess on " + brightness + ": " + onMask);
The Android Open Source Project10592532009-03-18 17:39:46 -07001974 setLightBrightness(onMask, brightness);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977
The Android Open Source Project10592532009-03-18 17:39:46 -07001978 private void setLightBrightness(int mask, int value) {
Mike Lockwoodcc9a63d2009-11-10 07:50:28 -05001979 int brightnessMode = (mAutoBrightessEnabled
Mike Lockwood3a322132009-11-24 00:30:52 -05001980 ? LightsService.BRIGHTNESS_MODE_SENSOR
1981 : LightsService.BRIGHTNESS_MODE_USER);
The Android Open Source Project10592532009-03-18 17:39:46 -07001982 if ((mask & SCREEN_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001983 mLcdLight.setBrightness(value, brightnessMode);
The Android Open Source Project10592532009-03-18 17:39:46 -07001984 }
1985 if ((mask & BUTTON_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001986 mButtonLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001987 }
1988 if ((mask & KEYBOARD_BRIGHT_BIT) != 0) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001989 mKeyboardLight.setBrightness(value);
The Android Open Source Project10592532009-03-18 17:39:46 -07001990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992
Joe Onoratob08a1af2010-10-11 19:28:58 -07001993 class BrightnessState implements Runnable {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 final int mask;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 boolean initialized;
1997 int targetValue;
1998 float curValue;
1999 float delta;
2000 boolean animating;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 BrightnessState(int m) {
2003 mask = m;
2004 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 public void dump(PrintWriter pw, String prefix) {
2007 pw.println(prefix + "animating=" + animating
2008 + " targetValue=" + targetValue
2009 + " curValue=" + curValue
2010 + " delta=" + delta);
2011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002012
Joe Onoratob08a1af2010-10-11 19:28:58 -07002013 void setTargetLocked(int target, int stepsToTarget, int initialValue,
Joe Onorato128e7292009-03-24 18:41:31 -07002014 int nominalCurrentValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 if (!initialized) {
2016 initialized = true;
2017 curValue = (float)initialValue;
Dianne Hackbornaa80b602009-10-09 17:38:26 -07002018 } else if (targetValue == target) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002019 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 targetValue = target;
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002022 delta = (targetValue -
2023 (nominalCurrentValue >= 0 ? nominalCurrentValue : curValue))
2024 / stepsToTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 if (mSpew) {
Joe Onorato128e7292009-03-24 18:41:31 -07002026 String noticeMe = nominalCurrentValue == curValue ? "" : " ******************";
Joe Onorato3d3db602010-10-18 16:08:16 -04002027 Slog.i(TAG, "setTargetLocked mask=" + mask + " curValue=" + curValue
2028 + " target=" + target + " targetValue=" + targetValue + " delta=" + delta
Joe Onorato128e7292009-03-24 18:41:31 -07002029 + " nominalCurrentValue=" + nominalCurrentValue
2030 + noticeMe);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032 animating = true;
Joe Onoratob08a1af2010-10-11 19:28:58 -07002033
2034 if (mSpew) {
2035 Slog.i(TAG, "scheduling light animator");
2036 }
2037 mScreenOffHandler.removeCallbacks(this);
2038 mScreenOffHandler.post(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 boolean stepLocked() {
2042 if (!animating) return false;
2043 if (false && mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002044 Slog.i(TAG, "Step target " + mask + ": cur=" + curValue
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 + " target=" + targetValue + " delta=" + delta);
2046 }
2047 curValue += delta;
2048 int curIntValue = (int)curValue;
2049 boolean more = true;
2050 if (delta == 0) {
Dianne Hackborn9ed4a4b2009-03-25 17:10:37 -07002051 curValue = curIntValue = targetValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 more = false;
2053 } else if (delta > 0) {
2054 if (curIntValue >= targetValue) {
2055 curValue = curIntValue = targetValue;
2056 more = false;
2057 }
2058 } else {
2059 if (curIntValue <= targetValue) {
2060 curValue = curIntValue = targetValue;
2061 more = false;
2062 }
2063 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002064 if (mSpew) Slog.d(TAG, "Animating curIntValue=" + curIntValue + ": " + mask);
The Android Open Source Project10592532009-03-18 17:39:46 -07002065 setLightBrightness(mask, curIntValue);
Joe Onorato3d3db602010-10-18 16:08:16 -04002066 finishAnimationLocked(more, curIntValue);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002067 return more;
2068 }
2069
Joe Onorato3d3db602010-10-18 16:08:16 -04002070 void jumpToTargetLocked() {
2071 if (mSpew) Slog.d(TAG, "jumpToTargetLocked targetValue=" + targetValue + ": " + mask);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002072 setLightBrightness(mask, targetValue);
2073 final int tv = targetValue;
2074 curValue = tv;
2075 targetValue = -1;
Joe Onorato3d3db602010-10-18 16:08:16 -04002076 finishAnimationLocked(false, tv);
Joe Onoratob08a1af2010-10-11 19:28:58 -07002077 }
2078
Joe Onorato3d3db602010-10-18 16:08:16 -04002079 private void finishAnimationLocked(boolean more, int curIntValue) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 animating = more;
2081 if (!more) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002082 if (mask == SCREEN_BRIGHT_BIT && curIntValue == Power.BRIGHTNESS_OFF) {
Mike Lockwood435eb642009-12-03 08:40:18 -05002083 screenOffFinishedAnimatingLocked(mScreenOffReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 public void run() {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002089 if (mAnimateScreenLights) {
2090 synchronized (mLocks) {
2091 long now = SystemClock.uptimeMillis();
2092 boolean more = mScreenBrightness.stepLocked();
2093 if (more) {
2094 mScreenOffHandler.postAtTime(this, now+(1000/60));
2095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
Joe Onoratob08a1af2010-10-11 19:28:58 -07002097 } else {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002098 synchronized (mLocks) {
Joe Onorato3d3db602010-10-18 16:08:16 -04002099 // we're turning off
2100 final boolean animate = animating && targetValue == Power.BRIGHTNESS_OFF;
2101 if (animate) {
2102 // It's pretty scary to hold mLocks for this long, and we should
2103 // redesign this, but it works for now.
2104 nativeStartSurfaceFlingerAnimation(
2105 mScreenOffReason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR
2106 ? 0 : mAnimationSetting);
2107 }
2108 mScreenBrightness.jumpToTargetLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
2111 }
2112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 private int getPreferredBrightness() {
2115 try {
2116 if (mScreenBrightnessOverride >= 0) {
2117 return mScreenBrightnessOverride;
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002118 } else if (mLightSensorScreenBrightness >= 0 && mUseSoftwareAutoBrightness
Mike Lockwood27c6dd72009-11-04 08:57:07 -05002119 && mAutoBrightessEnabled) {
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002120 return mLightSensorScreenBrightness;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122 final int brightness = Settings.System.getInt(mContext.getContentResolver(),
2123 SCREEN_BRIGHTNESS);
2124 // Don't let applications turn the screen all the way off
2125 return Math.max(brightness, Power.BRIGHTNESS_DIM);
2126 } catch (SettingNotFoundException snfe) {
2127 return Power.BRIGHTNESS_ON;
2128 }
2129 }
2130
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002131 private int applyButtonState(int state) {
2132 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002133 if ((state & BATTERY_LOW_BIT) != 0) {
2134 // do not override brightness if the battery is low
2135 return state;
2136 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002137 if (mButtonBrightnessOverride >= 0) {
2138 brightness = mButtonBrightnessOverride;
2139 } else if (mLightSensorButtonBrightness >= 0 && mUseSoftwareAutoBrightness) {
2140 brightness = mLightSensorButtonBrightness;
2141 }
2142 if (brightness > 0) {
2143 return state | BUTTON_BRIGHT_BIT;
2144 } else if (brightness == 0) {
2145 return state & ~BUTTON_BRIGHT_BIT;
2146 } else {
2147 return state;
2148 }
2149 }
2150
2151 private int applyKeyboardState(int state) {
2152 int brightness = -1;
Mike Lockwood48358bd2010-04-17 22:29:20 -04002153 if ((state & BATTERY_LOW_BIT) != 0) {
2154 // do not override brightness if the battery is low
2155 return state;
2156 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002157 if (!mKeyboardVisible) {
2158 brightness = 0;
2159 } else if (mButtonBrightnessOverride >= 0) {
2160 brightness = mButtonBrightnessOverride;
2161 } else if (mLightSensorKeyboardBrightness >= 0 && mUseSoftwareAutoBrightness) {
2162 brightness = mLightSensorKeyboardBrightness;
2163 }
2164 if (brightness > 0) {
2165 return state | KEYBOARD_BRIGHT_BIT;
2166 } else if (brightness == 0) {
2167 return state & ~KEYBOARD_BRIGHT_BIT;
2168 } else {
2169 return state;
2170 }
2171 }
2172
Charles Mendis322591c2009-10-29 11:06:59 -07002173 public boolean isScreenOn() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 synchronized (mLocks) {
2175 return (mPowerState & SCREEN_ON_BIT) != 0;
2176 }
2177 }
2178
Charles Mendis322591c2009-10-29 11:06:59 -07002179 boolean isScreenBright() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 synchronized (mLocks) {
2181 return (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT;
2182 }
2183 }
2184
Mike Lockwood497087e32009-11-08 18:33:03 -05002185 private boolean isScreenTurningOffLocked() {
2186 return (mScreenBrightness.animating && mScreenBrightness.targetValue == 0);
2187 }
2188
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002189 private boolean shouldLog(long time) {
2190 synchronized (mLocks) {
2191 if (time > (mWarningSpewThrottleTime + (60*60*1000))) {
2192 mWarningSpewThrottleTime = time;
2193 mWarningSpewThrottleCount = 0;
2194 return true;
2195 } else if (mWarningSpewThrottleCount < 30) {
2196 mWarningSpewThrottleCount++;
2197 return true;
2198 } else {
2199 return false;
2200 }
2201 }
2202 }
2203
Mike Lockwood200b30b2009-09-20 00:23:59 -04002204 private void forceUserActivityLocked() {
Mike Lockwoode090281422009-11-14 21:02:56 -05002205 if (isScreenTurningOffLocked()) {
2206 // cancel animation so userActivity will succeed
2207 mScreenBrightness.animating = false;
2208 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002209 boolean savedActivityAllowed = mUserActivityAllowed;
2210 mUserActivityAllowed = true;
2211 userActivity(SystemClock.uptimeMillis(), false);
2212 mUserActivityAllowed = savedActivityAllowed;
2213 }
2214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
2216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Joe Onorato7999bff2010-07-24 11:50:05 -04002217 userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
2219
2220 public void userActivity(long time, boolean noChangeLights) {
Joe Onorato4b9f62d2010-10-11 13:41:35 -07002221 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
2222 != PackageManager.PERMISSION_GRANTED) {
2223 if (shouldLog(time)) {
2224 Slog.w(TAG, "Caller does not have DEVICE_POWER permission. pid="
2225 + Binder.getCallingPid() + " uid=" + Binder.getCallingUid());
2226 }
2227 return;
2228 }
2229
Joe Onorato7999bff2010-07-24 11:50:05 -04002230 userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 }
2232
2233 public void userActivity(long time, boolean noChangeLights, int eventType) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002234 userActivity(time, -1, noChangeLights, eventType, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236
2237 public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
Joe Onorato7999bff2010-07-24 11:50:05 -04002238 userActivity(time, -1, noChangeLights, eventType, force);
2239 }
2240
2241 /*
2242 * Reset the user activity timeout to now + timeout. This overrides whatever else is going
2243 * on with user activity. Don't use this function.
2244 */
2245 public void clearUserActivityTimeout(long now, long timeout) {
2246 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2247 Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
2248 userActivity(now, timeout, false, OTHER_EVENT, false);
2249 }
2250
2251 private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
2252 int eventType, boolean force) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253
Joe Onorato1a542c72010-11-08 09:48:20 -08002254 if (((mPokey & POKE_LOCK_IGNORE_TOUCH_EVENTS) != 0) && (eventType == TOUCH_EVENT)) {
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002255 if (false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002256 Slog.d(TAG, "dropping touch mPokey=0x" + Integer.toHexString(mPokey));
Joe Onoratoe68ffcb2009-03-24 19:11:13 -07002257 }
2258 return;
2259 }
2260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 synchronized (mLocks) {
2262 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002263 Slog.d(TAG, "userActivity mLastEventTime=" + mLastEventTime + " time=" + time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 + " mUserActivityAllowed=" + mUserActivityAllowed
2265 + " mUserState=0x" + Integer.toHexString(mUserState)
Mike Lockwood36fc3022009-08-25 16:49:06 -07002266 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState)
2267 + " mProximitySensorActive=" + mProximitySensorActive
Joe Onorato797e6882010-08-26 14:46:01 -04002268 + " timeoutOverride=" + timeoutOverride
Mike Lockwood36fc3022009-08-25 16:49:06 -07002269 + " force=" + force);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 }
Mike Lockwood05067122009-10-27 23:07:25 -04002271 // ignore user activity if we are in the process of turning off the screen
Mike Lockwood497087e32009-11-08 18:33:03 -05002272 if (isScreenTurningOffLocked()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002273 Slog.d(TAG, "ignoring user activity while turning off screen");
Mike Lockwood05067122009-10-27 23:07:25 -04002274 return;
2275 }
Mike Lockwood0e39ea82009-11-18 15:37:10 -05002276 // Disable proximity sensor if if user presses power key while we are in the
2277 // "waiting for proximity sensor to go negative" state.
2278 if (mProximitySensorActive && mProximityWakeLockCount == 0) {
2279 mProximitySensorActive = false;
2280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 if (mLastEventTime <= time || force) {
2282 mLastEventTime = time;
Mike Lockwood36fc3022009-08-25 16:49:06 -07002283 if ((mUserActivityAllowed && !mProximitySensorActive) || force) {
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002284 // Only turn on button backlights if a button was pressed
2285 // and auto brightness is disabled
Mike Lockwood4984e732009-11-01 08:16:33 -05002286 if (eventType == BUTTON_EVENT && !mUseSoftwareAutoBrightness) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 mUserState = (mKeyboardVisible ? ALL_BRIGHT : SCREEN_BUTTON_BRIGHT);
2288 } else {
2289 // don't clear button/keyboard backlights when the screen is touched.
2290 mUserState |= SCREEN_BRIGHT;
2291 }
2292
Dianne Hackborn617f8772009-03-31 15:04:46 -07002293 int uid = Binder.getCallingUid();
2294 long ident = Binder.clearCallingIdentity();
2295 try {
2296 mBatteryStats.noteUserActivity(uid, eventType);
2297 } catch (RemoteException e) {
2298 // Ignore
2299 } finally {
2300 Binder.restoreCallingIdentity(ident);
2301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002302
Michael Chane96440f2009-05-06 10:27:36 -07002303 mWakeLockState = mLocks.reactivateScreenLocksLocked();
Mike Lockwood435eb642009-12-03 08:40:18 -05002304 setPowerState(mUserState | mWakeLockState, noChangeLights,
2305 WindowManagerPolicy.OFF_BECAUSE_OF_USER);
Joe Onorato7999bff2010-07-24 11:50:05 -04002306 setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
2308 }
2309 }
Mike Lockwoodef731622010-01-27 17:51:34 -05002310
2311 if (mPolicy != null) {
2312 mPolicy.userActivity();
2313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002316 private int getAutoBrightnessValue(int sensorValue, int[] values) {
2317 try {
2318 int i;
2319 for (i = 0; i < mAutoBrightnessLevels.length; i++) {
2320 if (sensorValue < mAutoBrightnessLevels[i]) {
2321 break;
2322 }
2323 }
2324 return values[i];
2325 } catch (Exception e) {
2326 // guard against null pointer or index out of bounds errors
Joe Onorato8a9b2202010-02-26 18:56:32 -08002327 Slog.e(TAG, "getAutoBrightnessValue", e);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002328 return 255;
2329 }
2330 }
2331
Mike Lockwood20f87d72009-11-05 16:08:51 -05002332 private Runnable mProximityTask = new Runnable() {
2333 public void run() {
2334 synchronized (mLocks) {
2335 if (mProximityPendingValue != -1) {
2336 proximityChangedLocked(mProximityPendingValue == 1);
2337 mProximityPendingValue = -1;
2338 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002339 if (mProximityPartialLock.isHeld()) {
2340 mProximityPartialLock.release();
2341 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002342 }
2343 }
2344 };
2345
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002346 private Runnable mAutoBrightnessTask = new Runnable() {
2347 public void run() {
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002348 synchronized (mLocks) {
Jim Rodovichd102fea2010-09-02 12:30:49 -05002349 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
2350 int value = (int)mLightSensorPendingValue;
2351 mLightSensorPendingDecrease = false;
2352 mLightSensorPendingIncrease = false;
Mike Lockwoodfa68ab42009-10-20 11:08:49 -04002353 lightSensorChangedLocked(value);
2354 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002355 }
2356 }
2357 };
2358
Mike Lockwoodb2865412010-02-02 22:40:33 -05002359 private void dockStateChanged(int state) {
2360 synchronized (mLocks) {
2361 mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2362 if (mIsDocked) {
2363 mHighestLightSensorValue = -1;
2364 }
2365 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2366 // force lights recalculation
2367 int value = (int)mLightSensorValue;
2368 mLightSensorValue = -1;
2369 lightSensorChangedLocked(value);
2370 }
2371 }
2372 }
2373
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002374 private void lightSensorChangedLocked(int value) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002375 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002376 Slog.d(TAG, "lightSensorChangedLocked " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002377 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002378
Joe Onorato06eb33a2010-10-25 14:09:21 -07002379 // Don't do anything if the screen is off.
2380 if ((mPowerState & SCREEN_ON_BIT) == 0) {
2381 if (mDebugLightSensor) {
2382 Slog.d(TAG, "dropping lightSensorChangedLocked because screen is off");
2383 }
2384 return;
2385 }
2386
Mike Lockwoodb2865412010-02-02 22:40:33 -05002387 // do not allow light sensor value to decrease
2388 if (mHighestLightSensorValue < value) {
2389 mHighestLightSensorValue = value;
2390 }
2391
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002392 if (mLightSensorValue != value) {
2393 mLightSensorValue = value;
2394 if ((mPowerState & BATTERY_LOW_BIT) == 0) {
Mike Lockwoodb2865412010-02-02 22:40:33 -05002395 // use maximum light sensor value seen since screen went on for LCD to avoid flicker
2396 // we only do this if we are undocked, since lighting should be stable when
2397 // stationary in a dock.
2398 int lcdValue = getAutoBrightnessValue(
2399 (mIsDocked ? value : mHighestLightSensorValue),
2400 mLcdBacklightValues);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002401 int buttonValue = getAutoBrightnessValue(value, mButtonBacklightValues);
Mike Lockwooddf024922009-10-29 21:29:15 -04002402 int keyboardValue;
2403 if (mKeyboardVisible) {
2404 keyboardValue = getAutoBrightnessValue(value, mKeyboardBacklightValues);
2405 } else {
2406 keyboardValue = 0;
2407 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002408 mLightSensorScreenBrightness = lcdValue;
2409 mLightSensorButtonBrightness = buttonValue;
2410 mLightSensorKeyboardBrightness = keyboardValue;
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002411
2412 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002413 Slog.d(TAG, "lcdValue " + lcdValue);
2414 Slog.d(TAG, "buttonValue " + buttonValue);
2415 Slog.d(TAG, "keyboardValue " + keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002416 }
2417
Mike Lockwood4984e732009-11-01 08:16:33 -05002418 if (mAutoBrightessEnabled && mScreenBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002419 mScreenBrightness.setTargetLocked(lcdValue, AUTOBRIGHTNESS_ANIM_STEPS,
2420 INITIAL_SCREEN_BRIGHTNESS, (int)mScreenBrightness.curValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002421 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002422 if (mButtonBrightnessOverride < 0) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002423 mButtonLight.setBrightness(buttonValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002424 }
Mike Lockwoodfb73f792009-11-20 11:31:18 -05002425 if (mButtonBrightnessOverride < 0 || !mKeyboardVisible) {
Joe Onoratob08a1af2010-10-11 19:28:58 -07002426 mKeyboardLight.setBrightness(keyboardValue);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07002427 }
2428 }
2429 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002430 }
2431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 /**
2433 * The user requested that we go to sleep (probably with the power button).
2434 * This overrides all wake locks that are held.
2435 */
2436 public void goToSleep(long time)
2437 {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002438 goToSleepWithReason(time, WindowManagerPolicy.OFF_BECAUSE_OF_USER);
2439 }
2440
2441 /**
2442 * The user requested that we go to sleep (probably with the power button).
2443 * This overrides all wake locks that are held.
2444 */
2445 public void goToSleepWithReason(long time, int reason)
2446 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2448 synchronized (mLocks) {
Dianne Hackborn254cb442010-01-27 19:23:59 -08002449 goToSleepLocked(time, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 /**
Doug Zongker50a21f42009-11-19 12:49:53 -08002454 * Reboot the device immediately, passing 'reason' (may be null)
2455 * to the underlying __reboot system call. Should not return.
2456 */
2457 public void reboot(String reason)
2458 {
2459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
San Mehat14e69af2010-01-06 14:58:18 -08002460
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002461 if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
2462 throw new IllegalStateException("Too early to call reboot()");
2463 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002464
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002465 final String finalReason = reason;
2466 Runnable runnable = new Runnable() {
2467 public void run() {
2468 synchronized (this) {
2469 ShutdownThread.reboot(mContext, finalReason, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002470 }
2471
San Mehat1e512792010-01-07 10:40:29 -08002472 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002473 };
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002474 // ShutdownThread must run on a looper capable of displaying the UI.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002475 mHandler.post(runnable);
2476
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002477 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002478 synchronized (runnable) {
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002479 while (true) {
2480 try {
2481 runnable.wait();
2482 } catch (InterruptedException e) {
2483 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002484 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002485 }
2486 }
2487
Dan Egnor60d87622009-12-16 16:32:58 -08002488 /**
2489 * Crash the runtime (causing a complete restart of the Android framework).
2490 * Requires REBOOT permission. Mostly for testing. Should not return.
2491 */
2492 public void crash(final String message)
2493 {
2494 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
2495 Thread t = new Thread("PowerManagerService.crash()") {
2496 public void run() { throw new RuntimeException(message); }
2497 };
2498 try {
2499 t.start();
2500 t.join();
2501 } catch (InterruptedException e) {
2502 Log.wtf(TAG, e);
2503 }
2504 }
2505
Mike Lockwood435eb642009-12-03 08:40:18 -05002506 private void goToSleepLocked(long time, int reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507
2508 if (mLastEventTime <= time) {
2509 mLastEventTime = time;
2510 // cancel all of the wake locks
2511 mWakeLockState = SCREEN_OFF;
2512 int N = mLocks.size();
2513 int numCleared = 0;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002514 boolean proxLock = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 for (int i=0; i<N; i++) {
2516 WakeLock wl = mLocks.get(i);
2517 if (isScreenLock(wl.flags)) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002518 if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)
2519 && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
2520 proxLock = true;
2521 } else {
2522 mLocks.get(i).activated = false;
2523 numCleared++;
2524 }
2525 }
2526 }
2527 if (!proxLock) {
2528 mProxIgnoredBecauseScreenTurnedOff = true;
2529 if (mDebugProximitySensor) {
2530 Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 }
2532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002533 EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);
Joe Onorato128e7292009-03-24 18:41:31 -07002534 mStillNeedSleepNotification = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 mUserState = SCREEN_OFF;
Mike Lockwood435eb642009-12-03 08:40:18 -05002536 setPowerState(SCREEN_OFF, false, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 cancelTimerLocked();
2538 }
2539 }
2540
2541 public long timeSinceScreenOn() {
2542 synchronized (mLocks) {
2543 if ((mPowerState & SCREEN_ON_BIT) != 0) {
2544 return 0;
2545 }
2546 return SystemClock.elapsedRealtime() - mScreenOffTime;
2547 }
2548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 public void setKeyboardVisibility(boolean visible) {
Mike Lockwooda625b382009-09-12 17:36:03 -07002551 synchronized (mLocks) {
2552 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002553 Slog.d(TAG, "setKeyboardVisibility: " + visible);
Mike Lockwooda625b382009-09-12 17:36:03 -07002554 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002555 if (mKeyboardVisible != visible) {
2556 mKeyboardVisible = visible;
2557 // don't signal user activity if the screen is off; other code
2558 // will take care of turning on due to a true change to the lid
2559 // switch and synchronized with the lock screen.
2560 if ((mPowerState & SCREEN_ON_BIT) != 0) {
Mike Lockwood4984e732009-11-01 08:16:33 -05002561 if (mUseSoftwareAutoBrightness) {
Mike Lockwooddf024922009-10-29 21:29:15 -04002562 // force recompute of backlight values
2563 if (mLightSensorValue >= 0) {
2564 int value = (int)mLightSensorValue;
2565 mLightSensorValue = -1;
2566 lightSensorChangedLocked(value);
2567 }
2568 }
Mike Lockwood3c9435a2009-10-22 15:45:37 -04002569 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2570 }
Mike Lockwooda625b382009-09-12 17:36:03 -07002571 }
2572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574
2575 /**
2576 * When the keyguard is up, it manages the power state, and userActivity doesn't do anything.
Mike Lockwood50c548d2009-11-09 16:02:06 -05002577 * When disabling user activity we also reset user power state so the keyguard can reset its
2578 * short screen timeout when keyguard is unhidden.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 */
2580 public void enableUserActivity(boolean enabled) {
Mike Lockwood50c548d2009-11-09 16:02:06 -05002581 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002582 Slog.d(TAG, "enableUserActivity " + enabled);
Mike Lockwood50c548d2009-11-09 16:02:06 -05002583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 synchronized (mLocks) {
2585 mUserActivityAllowed = enabled;
Mike Lockwood50c548d2009-11-09 16:02:06 -05002586 if (!enabled) {
2587 // cancel timeout and clear mUserState so the keyguard can set a short timeout
2588 setTimeoutLocked(SystemClock.uptimeMillis(), 0);
2589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
2591 }
2592
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002593 private void setScreenBrightnessMode(int mode) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002594 synchronized (mLocks) {
2595 boolean enabled = (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2596 if (mUseSoftwareAutoBrightness && mAutoBrightessEnabled != enabled) {
2597 mAutoBrightessEnabled = enabled;
2598 // This will get us a new value
2599 enableLightSensorLocked(mAutoBrightessEnabled && isScreenOn());
Mike Lockwood2d155d22009-10-27 09:32:30 -04002600 }
Mike Lockwooddc3494e2009-10-14 21:17:09 -07002601 }
2602 }
2603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 /** Sets the screen off timeouts:
2605 * mKeylightDelay
2606 * mDimDelay
2607 * mScreenOffDelay
2608 * */
2609 private void setScreenOffTimeoutsLocked() {
2610 if ((mPokey & POKE_LOCK_SHORT_TIMEOUT) != 0) {
Doug Zongker43866e02010-01-07 12:09:54 -08002611 mKeylightDelay = mShortKeylightDelay; // Configurable via secure settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 mDimDelay = -1;
2613 mScreenOffDelay = 0;
2614 } else if ((mPokey & POKE_LOCK_MEDIUM_TIMEOUT) != 0) {
2615 mKeylightDelay = MEDIUM_KEYLIGHT_DELAY;
2616 mDimDelay = -1;
2617 mScreenOffDelay = 0;
2618 } else {
Dianne Hackborndf83afa2010-01-20 13:37:26 -08002619 int totalDelay = mScreenOffTimeoutSetting;
2620 if (totalDelay > mMaximumScreenOffTimeout) {
2621 totalDelay = mMaximumScreenOffTimeout;
2622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 mKeylightDelay = LONG_KEYLIGHT_DELAY;
2624 if (totalDelay < 0) {
Jim Millerbc4603b2010-08-30 21:21:34 -07002625 // negative number means stay on as long as possible.
2626 mScreenOffDelay = mMaximumScreenOffTimeout;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 } else if (mKeylightDelay < totalDelay) {
2628 // subtract the time that the keylight delay. This will give us the
2629 // remainder of the time that we need to sleep to get the accurate
2630 // screen off timeout.
2631 mScreenOffDelay = totalDelay - mKeylightDelay;
2632 } else {
2633 mScreenOffDelay = 0;
2634 }
2635 if (mDimScreen && totalDelay >= (LONG_KEYLIGHT_DELAY + LONG_DIM_TIME)) {
2636 mDimDelay = mScreenOffDelay - LONG_DIM_TIME;
2637 mScreenOffDelay = LONG_DIM_TIME;
2638 } else {
2639 mDimDelay = -1;
2640 }
2641 }
2642 if (mSpew) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002643 Slog.d(TAG, "setScreenOffTimeouts mKeylightDelay=" + mKeylightDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 + " mDimDelay=" + mDimDelay + " mScreenOffDelay=" + mScreenOffDelay
2645 + " mDimScreen=" + mDimScreen);
2646 }
2647 }
2648
2649 /**
Doug Zongker43866e02010-01-07 12:09:54 -08002650 * Refreshes cached secure settings. Called once on startup, and
2651 * on subsequent changes to secure settings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 */
Doug Zongker43866e02010-01-07 12:09:54 -08002653 private void updateSettingsValues() {
2654 mShortKeylightDelay = Settings.Secure.getInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 mContext.getContentResolver(),
Doug Zongker43866e02010-01-07 12:09:54 -08002656 Settings.Secure.SHORT_KEYLIGHT_DELAY_MS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 SHORT_KEYLIGHT_DELAY_DEFAULT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002658 // Slog.i(TAG, "updateSettingsValues(): mShortKeylightDelay now " + mShortKeylightDelay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 }
2660
2661 private class LockList extends ArrayList<WakeLock>
2662 {
2663 void addLock(WakeLock wl)
2664 {
2665 int index = getIndex(wl.binder);
2666 if (index < 0) {
2667 this.add(wl);
2668 }
2669 }
2670
2671 WakeLock removeLock(IBinder binder)
2672 {
2673 int index = getIndex(binder);
2674 if (index >= 0) {
2675 return this.remove(index);
2676 } else {
2677 return null;
2678 }
2679 }
2680
2681 int getIndex(IBinder binder)
2682 {
2683 int N = this.size();
2684 for (int i=0; i<N; i++) {
2685 if (this.get(i).binder == binder) {
2686 return i;
2687 }
2688 }
2689 return -1;
2690 }
2691
2692 int gatherState()
2693 {
2694 int result = 0;
2695 int N = this.size();
2696 for (int i=0; i<N; i++) {
2697 WakeLock wl = this.get(i);
2698 if (wl.activated) {
2699 if (isScreenLock(wl.flags)) {
2700 result |= wl.minState;
2701 }
2702 }
2703 }
2704 return result;
2705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002706
Michael Chane96440f2009-05-06 10:27:36 -07002707 int reactivateScreenLocksLocked()
2708 {
2709 int result = 0;
2710 int N = this.size();
2711 for (int i=0; i<N; i++) {
2712 WakeLock wl = this.get(i);
2713 if (isScreenLock(wl.flags)) {
2714 wl.activated = true;
2715 result |= wl.minState;
2716 }
2717 }
Joe Onorato8274a0e2010-10-05 17:38:09 -04002718 if (mDebugProximitySensor) {
2719 Slog.d(TAG, "reactivateScreenLocksLocked mProxIgnoredBecauseScreenTurnedOff="
2720 + mProxIgnoredBecauseScreenTurnedOff);
2721 }
2722 mProxIgnoredBecauseScreenTurnedOff = false;
Michael Chane96440f2009-05-06 10:27:36 -07002723 return result;
2724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 }
2726
Dianne Hackborna924dc0d2011-02-17 14:22:17 -08002727 public void setPolicy(WindowManagerPolicy p) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728 synchronized (mLocks) {
2729 mPolicy = p;
2730 mLocks.notifyAll();
2731 }
2732 }
2733
2734 WindowManagerPolicy getPolicyLocked() {
2735 while (mPolicy == null || !mDoneBooting) {
2736 try {
2737 mLocks.wait();
2738 } catch (InterruptedException e) {
2739 // Ignore
2740 }
2741 }
2742 return mPolicy;
2743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 void systemReady() {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002746 mSensorManager = new SensorManager(mHandlerThread.getLooper());
2747 mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
2748 // don't bother with the light sensor if auto brightness is handled in hardware
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04002749 if (mUseSoftwareAutoBrightness) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002750 mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002751 }
2752
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002753 // wait until sensors are enabled before turning on screen.
2754 // some devices will not activate the light sensor properly on boot
2755 // unless we do this.
2756 if (mUseSoftwareAutoBrightness) {
2757 // turn the screen on
2758 setPowerState(SCREEN_BRIGHT);
2759 } else {
2760 // turn everything on
2761 setPowerState(ALL_BRIGHT);
2762 }
2763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 synchronized (mLocks) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002765 Slog.d(TAG, "system ready!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 mDoneBooting = true;
Mike Lockwoodb42ab0f2010-03-04 08:02:44 -05002767
Joe Onoratod28f7532010-11-06 12:56:53 -07002768 enableLightSensorLocked(mUseSoftwareAutoBrightness && mAutoBrightessEnabled);
2769
Dianne Hackborn617f8772009-03-31 15:04:46 -07002770 long identity = Binder.clearCallingIdentity();
2771 try {
2772 mBatteryStats.noteScreenBrightness(getPreferredBrightness());
2773 mBatteryStats.noteScreenOn();
2774 } catch (RemoteException e) {
2775 // Nothing interesting to do.
2776 } finally {
2777 Binder.restoreCallingIdentity(identity);
2778 }
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002779 }
2780 }
2781
2782 void bootCompleted() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002783 Slog.d(TAG, "bootCompleted");
Mike Lockwood2d7bb812009-11-15 18:12:22 -05002784 synchronized (mLocks) {
2785 mBootCompleted = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 userActivity(SystemClock.uptimeMillis(), false, BUTTON_EVENT, true);
2787 updateWakeLockLocked();
2788 mLocks.notifyAll();
2789 }
2790 }
2791
Joe Onoratob08a1af2010-10-11 19:28:58 -07002792 // for watchdog
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 public void monitor() {
2794 synchronized (mLocks) { }
2795 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002796
2797 public int getSupportedWakeLockFlags() {
2798 int result = PowerManager.PARTIAL_WAKE_LOCK
2799 | PowerManager.FULL_WAKE_LOCK
2800 | PowerManager.SCREEN_DIM_WAKE_LOCK;
2801
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002802 if (mProximitySensor != null) {
2803 result |= PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
2804 }
2805
2806 return result;
2807 }
2808
Mike Lockwood237a2992009-09-15 14:42:16 -04002809 public void setBacklightBrightness(int brightness) {
2810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
2811 // Don't let applications turn the screen all the way off
Joe Onoratob08a1af2010-10-11 19:28:58 -07002812 synchronized (mLocks) {
2813 brightness = Math.max(brightness, Power.BRIGHTNESS_DIM);
2814 mLcdLight.setBrightness(brightness);
2815 mKeyboardLight.setBrightness(mKeyboardVisible ? brightness : 0);
2816 mButtonLight.setBrightness(brightness);
2817 long identity = Binder.clearCallingIdentity();
2818 try {
2819 mBatteryStats.noteScreenBrightness(brightness);
2820 } catch (RemoteException e) {
2821 Slog.w(TAG, "RemoteException calling noteScreenBrightness on BatteryStatsService", e);
2822 } finally {
2823 Binder.restoreCallingIdentity(identity);
2824 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002825
Joe Onoratob08a1af2010-10-11 19:28:58 -07002826 // update our animation state
Joe Onorato3d3db602010-10-18 16:08:16 -04002827 synchronized (mLocks) {
2828 mScreenBrightness.targetValue = brightness;
2829 mScreenBrightness.jumpToTargetLocked();
2830 }
Mike Lockwood237a2992009-09-15 14:42:16 -04002831 }
2832 }
2833
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002834 public void setAttentionLight(boolean on, int color) {
2835 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002836 mAttentionLight.setFlashing(color, LightsService.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Mike Lockwoodb11832d2009-11-25 15:25:55 -05002837 }
2838
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002839 private void enableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002840 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002841 Slog.d(TAG, "enableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002842 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002843 if (!mProximitySensorEnabled) {
2844 // clear calling identity so sensor manager battery stats are accurate
2845 long identity = Binder.clearCallingIdentity();
2846 try {
2847 mSensorManager.registerListener(mProximityListener, mProximitySensor,
2848 SensorManager.SENSOR_DELAY_NORMAL);
2849 mProximitySensorEnabled = true;
2850 } finally {
2851 Binder.restoreCallingIdentity(identity);
2852 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002853 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002854 }
2855
2856 private void disableProximityLockLocked() {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002857 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002858 Slog.d(TAG, "disableProximityLockLocked");
Mike Lockwood36fc3022009-08-25 16:49:06 -07002859 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002860 if (mProximitySensorEnabled) {
2861 // clear calling identity so sensor manager battery stats are accurate
2862 long identity = Binder.clearCallingIdentity();
2863 try {
2864 mSensorManager.unregisterListener(mProximityListener);
2865 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002866 if (mProximityPartialLock.isHeld()) {
2867 mProximityPartialLock.release();
2868 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002869 mProximitySensorEnabled = false;
2870 } finally {
2871 Binder.restoreCallingIdentity(identity);
2872 }
2873 if (mProximitySensorActive) {
2874 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002875 if (mDebugProximitySensor) {
2876 Slog.d(TAG, "disableProximityLockLocked mProxIgnoredBecauseScreenTurnedOff="
2877 + mProxIgnoredBecauseScreenTurnedOff);
2878 }
2879 if (!mProxIgnoredBecauseScreenTurnedOff) {
2880 forceUserActivityLocked();
2881 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002882 }
Mike Lockwood200b30b2009-09-20 00:23:59 -04002883 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002884 }
2885
Mike Lockwood20f87d72009-11-05 16:08:51 -05002886 private void proximityChangedLocked(boolean active) {
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002887 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002888 Slog.d(TAG, "proximityChangedLocked, active: " + active);
Mike Lockwood20f87d72009-11-05 16:08:51 -05002889 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002890 if (!mProximitySensorEnabled) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002891 Slog.d(TAG, "Ignoring proximity change after sensor is disabled");
Mike Lockwood0d72f7e2009-11-05 20:53:00 -05002892 return;
2893 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002894 if (active) {
Joe Onorato8274a0e2010-10-05 17:38:09 -04002895 if (mDebugProximitySensor) {
2896 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2897 + mProxIgnoredBecauseScreenTurnedOff);
2898 }
2899 if (!mProxIgnoredBecauseScreenTurnedOff) {
2900 goToSleepLocked(SystemClock.uptimeMillis(),
2901 WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);
2902 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002903 mProximitySensorActive = true;
2904 } else {
2905 // proximity sensor negative events trigger as user activity.
2906 // temporarily set mUserActivityAllowed to true so this will work
2907 // even when the keyguard is on.
2908 mProximitySensorActive = false;
Joe Onorato8274a0e2010-10-05 17:38:09 -04002909 if (mDebugProximitySensor) {
2910 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="
2911 + mProxIgnoredBecauseScreenTurnedOff);
2912 }
2913 if (!mProxIgnoredBecauseScreenTurnedOff) {
2914 forceUserActivityLocked();
2915 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002916
2917 if (mProximityWakeLockCount == 0) {
2918 // disable sensor if we have no listeners left after proximity negative
2919 disableProximityLockLocked();
2920 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002921 }
2922 }
2923
Joe Onoratod28f7532010-11-06 12:56:53 -07002924 private void enableLightSensorLocked(boolean enable) {
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002925 if (mDebugLightSensor) {
Joe Onoratod28f7532010-11-06 12:56:53 -07002926 Slog.d(TAG, "enableLightSensorLocked enable=" + enable
2927 + " mAutoBrightessEnabled=" + mAutoBrightessEnabled);
2928 }
2929 if (!mAutoBrightessEnabled) {
2930 enable = false;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002931 }
2932 if (mSensorManager != null && mLightSensorEnabled != enable) {
2933 mLightSensorEnabled = enable;
Mike Lockwood809ad0f2009-10-26 22:10:33 -04002934 // clear calling identity so sensor manager battery stats are accurate
2935 long identity = Binder.clearCallingIdentity();
2936 try {
2937 if (enable) {
2938 mSensorManager.registerListener(mLightListener, mLightSensor,
2939 SensorManager.SENSOR_DELAY_NORMAL);
2940 } else {
2941 mSensorManager.unregisterListener(mLightListener);
2942 mHandler.removeCallbacks(mAutoBrightnessTask);
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(identity);
Mike Lockwood06952d92009-08-13 16:05:38 -04002946 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07002947 }
2948 }
2949
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002950 SensorEventListener mProximityListener = new SensorEventListener() {
2951 public void onSensorChanged(SensorEvent event) {
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05002952 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002953 synchronized (mLocks) {
2954 float distance = event.values[0];
Mike Lockwood20f87d72009-11-05 16:08:51 -05002955 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;
2956 mLastProximityEventTime = milliseconds;
2957 mHandler.removeCallbacks(mProximityTask);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002958 boolean proximityTaskQueued = false;
Mike Lockwood20f87d72009-11-05 16:08:51 -05002959
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002960 // compare against getMaximumRange to support sensors that only return 0 or 1
Mike Lockwood20f87d72009-11-05 16:08:51 -05002961 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&
2962 distance < mProximitySensor.getMaximumRange());
2963
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002964 if (mDebugProximitySensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002965 Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);
Mike Lockwoodee2b0942009-11-09 14:09:02 -05002966 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05002967 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {
2968 // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing
2969 mProximityPendingValue = (active ? 1 : 0);
2970 mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002971 proximityTaskQueued = true;
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002972 } else {
Mike Lockwood20f87d72009-11-05 16:08:51 -05002973 // process the value immediately
2974 mProximityPendingValue = -1;
2975 proximityChangedLocked(active);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002976 }
Mike Lockwood0e5bb7f2009-11-14 06:36:31 -05002977
2978 // update mProximityPartialLock state
2979 boolean held = mProximityPartialLock.isHeld();
2980 if (!held && proximityTaskQueued) {
2981 // hold wakelock until mProximityTask runs
2982 mProximityPartialLock.acquire();
2983 } else if (held && !proximityTaskQueued) {
2984 mProximityPartialLock.release();
2985 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002986 }
2987 }
2988
2989 public void onAccuracyChanged(Sensor sensor, int accuracy) {
2990 // ignore
2991 }
2992 };
2993
2994 SensorEventListener mLightListener = new SensorEventListener() {
2995 public void onSensorChanged(SensorEvent event) {
2996 synchronized (mLocks) {
Mike Lockwood497087e32009-11-08 18:33:03 -05002997 // ignore light sensor while screen is turning off
2998 if (isScreenTurningOffLocked()) {
2999 return;
3000 }
3001
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003002 int value = (int)event.values[0];
Mike Lockwoodba8eb1e2009-11-08 19:31:18 -05003003 long milliseconds = SystemClock.elapsedRealtime();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003004 if (mDebugLightSensor) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003005 Slog.d(TAG, "onSensorChanged: light value: " + value);
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003006 }
Jim Rodovichd102fea2010-09-02 12:30:49 -05003007 if (mLightSensorValue == -1 ||
3008 milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
3009 // process the value immediately if screen has just turned on
3010 mHandler.removeCallbacks(mAutoBrightnessTask);
3011 mLightSensorPendingDecrease = false;
3012 mLightSensorPendingIncrease = false;
3013 lightSensorChangedLocked(value);
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003014 } else {
Jim Rodovichd102fea2010-09-02 12:30:49 -05003015 if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
3016 (value < mLightSensorValue && mLightSensorPendingIncrease) ||
3017 (value == mLightSensorValue) ||
3018 (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
3019 // delay processing to debounce the sensor
3020 mHandler.removeCallbacks(mAutoBrightnessTask);
3021 mLightSensorPendingDecrease = (value < mLightSensorValue);
3022 mLightSensorPendingIncrease = (value > mLightSensorValue);
3023 if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
3024 mLightSensorPendingValue = value;
3025 mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
3026 }
3027 } else {
3028 mLightSensorPendingValue = value;
3029 }
Mike Lockwoodd7786b42009-10-15 17:09:16 -07003030 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003031 }
3032 }
3033
3034 public void onAccuracyChanged(Sensor sensor, int accuracy) {
3035 // ignore
3036 }
3037 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038}